From 21baf0dc995299309df2483a9d2bfb38c76f11b2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:53:03 +0200 Subject: [PATCH 01/12] Screen overlays: blur and clamp from the texture's .png.mcmeta TextureMetadataSection's blur and clamp choose how vanilla samples a standalone texture (ReloadableTexture.setSampler). The atlas now keeps each texture's flags and the screen-effect quads (vignette, pumpkin blur, powder snow outline, underwater, equippable camera overlays) sample their sprite rectangle linearly and with clamp or repeat as those flags say, instead of always nearest and repeat. Fixes #335 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/gfx.rs | 2 +- crates/horizon-client/src/hud.rs | 43 +++++++- crates/horizon-client/src/screen.wgsl | 38 +++++-- crates/horizon-client/src/screen_effects.rs | 102 +++++++++++++++++- 5 files changed, 170 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4ad9db548..e947d2af5 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -222,6 +222,7 @@ impl Game<'_> { hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); self.screen_fx.build(&ScreenInputs { sprites: &self.gui.atlas.sprites, + flags: &self.gui.atlas.flags, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 127aaf737..c03193be4 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1921,7 +1921,7 @@ impl Renderer { source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), }); let screen_attributes = - wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4,4=>Uint32]; let screen_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0cc99b07b..cbf674136 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -18,11 +18,35 @@ pub struct Rect { pub w: u32, pub h: u32, } +/// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a +/// standalone texture (`ReloadableTexture.setSampler`: linear rather than +/// nearest filtering, clamp-to-edge rather than repeat addressing). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TextureFlags { + pub blur: bool, + pub clamp: bool, +} +impl TextureFlags { + /// The `texture` section of a `.png.mcmeta` file, if it sets either flag. + pub fn from_mcmeta(json: &str) -> Option { + let meta: serde_json::Value = serde_json::from_str(json).ok()?; + let section = meta.get("texture")?; + let flag = |key| section.get(key).and_then(serde_json::Value::as_bool) == Some(true); + let flags = Self { + blur: flag("blur"), + clamp: flag("clamp"), + }; + (flags != Self::default()).then_some(flags) + } +} pub struct HudAtlas { pub pixels: Vec, pub width: u32, pub height: u32, pub sprites: HashMap, + /// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others + /// sample as vanilla's defaults (nearest, repeat). + pub flags: HashMap, pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). pub font: crate::font::Font, @@ -211,7 +235,7 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { + let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { let name = path .strip_prefix(&textures) .ok()? @@ -226,11 +250,15 @@ impl HudAtlas { } else { pixels }; - (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) + let flags = fs::read_to_string(path.with_extension("png.mcmeta")) + .ok() + .and_then(|json| TextureFlags::from_mcmeta(&json)); + (w <= 1024 && (h <= 512 || name.starts_with("font/"))) + .then_some(((name, w, h, pixels), flags)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); - let mut images: Vec<_> = std::thread::scope(|scope| { + let decoded: Vec<_> = std::thread::scope(|scope| { let handles: Vec<_> = files .chunks(chunk) .map(|part| { @@ -242,6 +270,14 @@ impl HudAtlas { .flat_map(|h| h.join().unwrap_or_default()) .collect() }); + let mut flags = HashMap::new(); + let mut images: Vec = Vec::with_capacity(decoded.len()); + for (image, image_flags) in decoded { + if let Some(f) = image_flags { + flags.insert(image.0.clone(), f); + } + images.push(image); + } if full { images.extend(atlas_sprites(root, &images)); } @@ -337,6 +373,7 @@ impl HudAtlas { width, height, sprites, + flags, fire_animations, font, white, diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index 62cb2ee6c..a82b0f890 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -1,26 +1,50 @@ -// Full-screen camera effects (screen_effects.rs): clip-space quads sampling -// the shared 2D atlas with repeat inside each sprite rectangle. +// Full-screen camera effects (screen_effects.rs): clip-space quads reading +// one sprite rectangle of the shared 2D atlas as if it were its own texture, +// with the sampler vanilla gives it (ReloadableTexture.setSampler: linear +// when `blur`, clamp-to-edge when `clamp`, else nearest and repeat). @group(0) @binding(1) var atlas: texture_2d; -@group(0) @binding(2) var atlas_sampler: sampler; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @location(1) @interpolate(flat) rect: vec4, @location(2) color: vec4, + @location(3) @interpolate(flat) sampling: u32, } @vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, - @location(2) rect: vec4, @location(3) color: vec4) -> Out { + @location(2) rect: vec4, @location(3) color: vec4, + @location(4) sampling: u32) -> Out { var out: Out; out.clip = vec4(pos, 0.0, 1.0); out.uv = uv; out.rect = rect; out.color = color; + out.sampling = sampling; return out; } +const SAMPLE_BLUR: u32 = 1u; +const SAMPLE_CLAMP: u32 = 2u; +// A texel of the sprite, addressed by repeat or clamp-to-edge. +fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { + var q = ((p % size) + size) % size; + if clamp_edge { q = clamp(p, vec2(0), size - 1); } + return textureLoad(atlas, origin + q, 0); +} fn sample(in: Out) -> vec4 { - let f = fract(in.uv); - let uv = in.rect.xy + f * (in.rect.zw - in.rect.xy); - return textureSampleLevel(atlas, atlas_sampler, uv, 0.0) * in.color; + let dims = vec2(textureDimensions(atlas)); + let origin = vec2(round(in.rect.xy * dims)); + let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); + let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; + let p = in.uv * vec2(size); + if (in.sampling & SAMPLE_BLUR) == 0u { + return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; + } + // GL_LINEAR: the four texels around the sample point, weighted. + let c = p - 0.5; + let i = vec2(floor(c)); + let t = c - floor(c); + let a = mix(texel(origin, size, i, clamp_edge), texel(origin, size, i + vec2(1, 0), clamp_edge), t.x); + let b = mix(texel(origin, size, i + vec2(0, 1), clamp_edge), texel(origin, size, i + vec2(1, 1), clamp_edge), t.x); + return mix(a, b, t.y) * in.color; } @fragment fn fs_screen(in: Out) -> @location(0) vec4 { let c = sample(in); diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index bc7756453..48f468d4d 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -4,7 +4,10 @@ //! `hud_overlays::camera_overlays` (vignette, pumpkin blur, powder-snow //! outline, nether portal swirl). Positions are clip-space quads; textures //! come from the shared 2D atlas and may repeat. -use crate::{hud::Rect, hud_layout::GuiDraw}; +use crate::{ + hud::{Rect, TextureFlags}, + hud_layout::GuiDraw, +}; use std::collections::HashMap; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -24,6 +27,17 @@ pub struct ScreenVertex { /// Atlas rectangle (u0, v0, u1, v1) of the sprite. pub rect: [f32; 4], pub color: [f32; 4], + /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. + pub sampling: u32, +} +/// Linear filtering (`TextureMetadataSection.blur`), else nearest. +pub const SAMPLE_BLUR: u32 = 1; +/// Clamp-to-edge addressing (`TextureMetadataSection.clamp`), else repeat. +pub const SAMPLE_CLAMP: u32 = 2; +/// The sampling bits of a standalone texture's flags. +pub fn sampling(flags: TextureFlags) -> u32 { + let bit = |on: bool, bit: u32| if on { bit } else { 0 }; + bit(flags.blur, SAMPLE_BLUR) | bit(flags.clamp, SAMPLE_CLAMP) } #[derive(Clone, Debug)] pub struct ScreenQuad { @@ -34,6 +48,8 @@ pub struct ScreenQuad { /// What the camera sees this frame. pub struct ScreenInputs<'a> { pub sprites: &'a HashMap, + /// `.png.mcmeta` sampling of the standalone textures among `sprites`. + pub flags: &'a HashMap, pub aspect: f32, pub partial: f32, /// Particle sprite of the view-blocking block around the eye. @@ -92,17 +108,23 @@ impl ScreenEffects { pub fn build(&self, input: &ScreenInputs) -> Vec { let mut out = Vec::new(); let sprite = |name: &str| input.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + // Standalone textures (`ReloadableTexture.setSampler`) follow their + // metadata; atlas sprites (block overlay, fire, portal) sample + // nearest with repeat. + let texture_sampling = |name: &str| input.flags.get(name).copied().map_or(0, sampling); let scale = hand_scale(input.aspect); // Screen-effect quads live at view depth 0.5 in the hand projection. let hand_quad = |corners: [[f32; 2]; 4], uv: [[f32; 2]; 4], rect: [f32; 4], - color: [f32; 4]| ScreenQuad { + color: [f32; 4], + sampling: u32| ScreenQuad { vertices: std::array::from_fn(|i| ScreenVertex { pos: [corners[i][0] * scale[0], corners[i][1] * scale[1]], uv: uv[i], rect, color, + sampling, }), blend: Blend::Alpha, }; @@ -117,6 +139,7 @@ impl ScreenEffects { [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], rect, [c, c, c, 1.0], + 0, )); } if let Some((brightness, yaw, pitch)) = input.water @@ -129,6 +152,7 @@ impl ScreenEffects { uv, rect, [brightness, brightness, brightness, 0.1], + texture_sampling("misc/underwater"), )); } if input.on_fire @@ -150,11 +174,12 @@ impl ScreenEffects { [[1.0, 1.0], [0.0, 1.0], [0.0, 0.0], [1.0, 0.0]], rect, [1.0, 1.0, 1.0, alpha], + 0, )); } } // Hud camera overlays: GUI-space full-screen blits (v grows downwards). - let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend| ScreenQuad { + let gui = |rect: [f32; 4], color: [f32; 4], blend: Blend, sampling: u32| ScreenQuad { vertices: std::array::from_fn(|i| { let p = [[-1.0f32, 1.0], [1.0, 1.0], [1.0, -1.0], [-1.0, -1.0]][i]; ScreenVertex { @@ -162,6 +187,7 @@ impl ScreenEffects { uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i], rect, color, + sampling, } }), blend, @@ -188,7 +214,7 @@ impl ScreenEffects { Blend::Alpha }; if let Some(rect) = sprite(texture) { - out.push(gui(rect, rgba(*color), blend)); + out.push(gui(rect, rgba(*color), blend, texture_sampling(texture))); } } GuiDraw::AtlasSprite { @@ -197,7 +223,7 @@ impl ScreenEffects { .. } => { if let Some(rect) = sprite(name) { - out.push(gui(rect, rgba(*color), Blend::Alpha)); + out.push(gui(rect, rgba(*color), Blend::Alpha, 0)); } } _ => {} @@ -243,8 +269,10 @@ mod tests { }, ); let e = ScreenEffects::default(); + let flags = HashMap::new(); let input = ScreenInputs { sprites: &sprites, + flags: &flags, aspect: 1.6, partial: 0.0, block_overlay: None, @@ -255,5 +283,69 @@ mod tests { let quads = e.build(&input); assert_eq!(quads.len(), 1); assert_eq!(quads[0].blend, Blend::Vignette); + assert_eq!(quads[0].vertices[0].sampling, 0); + } + #[test] + fn standalone_textures_sample_by_their_metadata() { + let rect = Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }; + let sprites: HashMap<_, _> = ["misc/vignette", "misc/underwater", "block/stone"] + .map(|name| (name.to_owned(), rect)) + .into(); + let blur = TextureFlags { + blur: true, + clamp: false, + }; + let clamp = TextureFlags { + blur: false, + clamp: true, + }; + let flags: HashMap<_, _> = [ + ("misc/vignette".to_owned(), blur), + ("misc/underwater".to_owned(), clamp), + // Atlas sprites ignore the texture section. + ("block/stone".to_owned(), blur), + ] + .into(); + let quads = ScreenEffects::default().build(&ScreenInputs { + sprites: &sprites, + flags: &flags, + aspect: 1.6, + partial: 0.0, + block_overlay: Some("block/stone".to_owned()), + water: Some((1.0, 0.0, 0.0)), + on_fire: false, + gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)], + }); + let sampling: Vec<_> = quads.iter().map(|q| q.vertices[0].sampling).collect(); + assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]); + } + #[test] + fn mcmeta_texture_section() { + let parse = TextureFlags::from_mcmeta; + assert_eq!( + parse(r#"{"texture":{"blur":true}}"#), + Some(TextureFlags { + blur: true, + clamp: false + }) + ); + assert_eq!( + parse(r#"{"texture":{"clamp":true,"mipmap_strategy":"mean"}}"#), + Some(TextureFlags { + blur: false, + clamp: true + }) + ); + // Defaults (false, false) or no section: the default sampler. + assert_eq!(parse(r#"{"texture":{"blur":false}}"#), None); + assert_eq!(parse(r#"{"animation":{}}"#), None); + assert_eq!(parse("not json"), None); } } From 0c133101b695d8bccfa6d546411da6a171a80888 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 00:55:22 +0200 Subject: [PATCH 02/12] Screen overlays: wrap texels with a select, not integer modulo The camera overlays (the vignette every frame) read up to four texels a pixel, each wrapped with two integer modulos. Intel GPUs emulate integer division. Reducing the coordinate to one period first (fract, as the shader did before) leaves every read at most one texel outside the sprite, so a select wraps it. Same texels and weights; clamp-to-edge is unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/screen.wgsl | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index a82b0f890..f32274bc8 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -23,9 +23,11 @@ struct Out { } const SAMPLE_BLUR: u32 = 1u; const SAMPLE_CLAMP: u32 = 2u; -// A texel of the sprite, addressed by repeat or clamp-to-edge. +// A texel of the sprite, addressed by repeat or clamp-to-edge. With repeat, `p` is at most one +// texel outside the sprite (`sample` reduces the coordinate first), so wrapping is a select: no +// integer division, which Intel GPUs emulate (it cost 0.85 ms a frame on the vignette on an HD 620). fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { - var q = ((p % size) + size) % size; + var q = select(select(p, p - size, p >= size), p + size, p < vec2(0)); if clamp_edge { q = clamp(p, vec2(0), size - 1); } return textureLoad(atlas, origin + q, 0); } @@ -34,7 +36,8 @@ fn sample(in: Out) -> vec4 { let origin = vec2(round(in.rect.xy * dims)); let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; - let p = in.uv * vec2(size); + // Repeat: one period of the sprite, so every texel read is at most one outside it. + let p = select(fract(in.uv), in.uv, clamp_edge) * vec2(size); if (in.sampling & SAMPLE_BLUR) == 0u { return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; } From 7acebbae45fb84ec7c905e05f4ac4e4220914d0b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:23:58 +0200 Subject: [PATCH 03/12] Server players: the HUD's bubbles and golden hearts follow the server, absorption is saved, Nether lava pushes harder The server sends a player's own air supply and absorption amount (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID) when they change, and the client applies them: on the server thread and as a LAN guest the breath meter follows the server's Respiration-extended air (#1304) and the golden hearts show (#1306). The connected client's tick sets the helmet's Respiration and the Nether's FAST_LAVA as the window's own tick does (#1309). AbsorptionAmount is written from the live body and read back on load, in the window's world and for a server's players (#1307). lan_e2e: absorption, breath and lava checks. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/attribute_updates.rs | 5 + crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 6 + crates/horizon-client/src/game/remote.rs | 31 ++++- crates/horizon-client/src/lan/guest.rs | 9 ++ crates/horizon-client/src/lan/hub.rs | 25 +++- crates/horizon-client/src/lan/playerdata.rs | 7 + crates/horizon-client/src/motion.rs | 2 + crates/horizon-client/src/save.rs | 10 +- tools/lan_e2e.py | 122 +++++++++++++++++- 12 files changed, 215 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/attribute_updates.rs b/crates/horizon-client/src/attribute_updates.rs index b81db5835..1dcc21028 100644 --- a/crates/horizon-client/src/attribute_updates.rs +++ b/crates/horizon-client/src/attribute_updates.rs @@ -22,6 +22,11 @@ impl PlayerMotion { pub fn refresh_attributes(&mut self) -> Result<()> { live_updates::refresh(self) } + /// `Player.internalSetAbsorptionAmount`: the amount as given, unclamped + /// (the saved `AbsorptionAmount`, or what a client's server sent). + pub fn internal_set_absorption(&mut self, value: f32) -> Result<()> { + self.store_absorption(value) + } } impl HealthWorld for PlayerMotion { type Error = Box; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..d689ad8fc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9516,6 +9516,7 @@ impl Game<'_> { if let Some(p) = &self.player { level.position = Some([p.position.x, p.position.y, p.position.z]); level.health = p.health.health(); + level.absorption = p.health.absorption(); let extra = level .player_extra .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..b30adca5c 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -459,6 +459,8 @@ impl Game<'_> { "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), + "absorption": p.health.absorption(), + "air": p.air, "food": p.health.food.food, "saturation": p.health.food.saturation, "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..0ea2a6faa 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -393,6 +393,9 @@ impl Game<'_> { "sneaking": g.sneaking, "sleeping": g.bed, "health": g.health, + // The server's body: its air supply and golden hearts. + "air": g.motion.as_ref().map(|m| m.air), + "absorption": g.motion.as_ref().map(|m| m.health.absorption()), // FoodData: food level, saturation and exhaustion. "food": [ f64::from(g.food), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..65cbf2e5f 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -217,6 +217,12 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + // The saved golden hearts go on the first body of a player who + // has been here before. + let saved = host.hub.guests[i].saved_absorption.take(); + if let (Some(m), Some(amount)) = (host.hub.guests[i].motion.as_mut(), saved) { + let _ = m.internal_set_absorption(amount); + } let kept = host.hub.guests[i].logs_kept.take(); if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) { m.hurt_log = hurts; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..70096277f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1867,11 +1867,27 @@ impl Game<'_> { // player lies down in the bed, or gets up. if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { for (index, _, value) in &p.values { - if let (14, Value::OptPos(bed)) = (index, value) { - if bed.is_some() && self.sleeping.is_none() { - self.sleep_timer = 0; + match (index, value) { + (14, Value::OptPos(bed)) => { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; } - self.sleeping = *bed; + // Entity.DATA_AIR_SUPPLY_ID and + // Player.DATA_PLAYER_ABSORPTION_ID: the bubbles + // and golden hearts the server's player has. + (1, Value::Int(air)) => { + if let Some(pl) = self.player.as_mut() { + pl.air = *air; + } + } + (17, Value::Float(amount)) => { + if let Some(pl) = self.player.as_mut() { + let _ = pl.internal_set_absorption(*amount); + } + } + _ => {} } } } @@ -2997,6 +3013,13 @@ impl Game<'_> { ); let was_flying = player.flying; player.yaw = self.yaw; + // As the window's own tick has them: the helmet's Respiration + // (decreaseAirSupply) and the dimension's FAST_LAVA, the Nether's + // stronger lava current. + player.respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); + player.fluids.fast_lava = self.dim == Dim::Nether; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 1916344bb..3c5d4b50c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -149,6 +149,9 @@ pub struct Guest { /// The ender chest inventory (`PlayerEnderChestContainer`, 27 slots). pub ender_items: Vec>, pub health: f32, + /// The saved `AbsorptionAmount`, until the player's first body on the + /// server takes it (the body holds the live amount). + pub saved_absorption: Option, pub food: i32, pub saturation: f32, pub xp_level: i32, @@ -168,6 +171,10 @@ pub struct Guest { /// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`. pub sent_health: Option<(f32, i32, bool)>, pub sent_xp: Option<(f32, i32, i32)>, + /// The air supply and absorption the player's client was last sent + /// (Entity.DATA_AIR_SUPPLY_ID, Player.DATA_PLAYER_ABSORPTION_ID); their + /// defaults until either changes. + pub sent_air: (i32, f32), /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, /// The last action sequence to acknowledge at the next tick (-1: none). @@ -280,6 +287,7 @@ impl Guest { craft_result: None, ender_items: vec![None; 27], health: 20.0, + saved_absorption: None, food: 20, saturation: 5.0, xp_level: 0, @@ -292,6 +300,7 @@ impl Guest { menu_state: 0, sent_health: None, sent_xp: None, + sent_air: (300, 0.0), last_death: None, ack_up_to: std::cell::Cell::new(-1), sent_selected: 0, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index bf66f979b..1455e60b8 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1755,6 +1755,27 @@ impl Hub { })); } } + // ServerEntity.sendDirtyEntityData: the air supply and the absorption + // amount the server's body changed go to the player, whose HUD draws + // them (bubbles, golden hearts). + let g = &mut self.guests[i]; + if let Some(m) = g.motion.as_ref() { + let now = (m.air, m.health.absorption()); + let mut values = Vec::new(); + if now.0 != g.sent_air.0 { + values.push((1, serializer::INT, Value::Int(now.0))); + } + if now.1.to_bits() != g.sent_air.1.to_bits() { + values.push((17, serializer::FLOAT, Value::Float(now.1))); + } + if !values.is_empty() { + g.sent_air = now; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values, + })); + } + } // Sent when the health or the food level changes, or the saturation // reaches or leaves zero; a dead player's health of 0 too. let g = &mut self.guests[i]; @@ -2465,9 +2486,11 @@ impl Hub { global: false, })); } - // lastSentExp, lastSentHealth and lastSentFood. + // lastSentExp, lastSentHealth and lastSentFood; the client's new + // player starts with the default air and no absorption. g.sent_health = None; g.sent_xp = None; + g.sent_air = (300, 0.0); let (cx, cz) = g.chunk(); g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { x: cx, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..6a26306fb 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -61,6 +61,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.head_yaw = guest.yaw; guest.on_ground = level.on_ground; guest.health = level.health; + guest.saved_absorption = Some(level.absorption); guest.food = level.food; guest.saturation = level.saturation; guest.xp_level = level.xp_level; @@ -123,6 +124,12 @@ pub fn store(guest: &Guest, level: &mut Level) { level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; + level.absorption = guest + .motion + .as_ref() + .map_or(guest.saved_absorption.unwrap_or(0.0), |m| { + m.health.absorption() + }); level.food = guest.food; level.saturation = guest.saturation; level.xp_level = guest.xp_level; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..c0c882e0f 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -338,6 +338,8 @@ impl PlayerMotion { .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; self.set_health(level.health, false)?; + // LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount. + self.internal_set_absorption(level.absorption)?; self.health.food.food = level.food; self.health.food.saturation = level.saturation; self.flying = level.flying; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0cfe3c585..2fbb04dc4 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2266,6 +2266,8 @@ pub struct Level { pub position: Option<[f64; 3]>, pub rotation: [f32; 2], pub health: f32, + /// LivingEntity `AbsorptionAmount`: the golden hearts left. + pub absorption: f32, pub food: i32, pub saturation: f32, /// (slot, item, count, damage): 0..36 inventory, 100..103 armor (feet..head), 150 offhand. @@ -2455,6 +2457,7 @@ impl Level { } self.motion = read_doubles::<3>(p.get("Motion")).unwrap_or_default(); self.health = f("Health").map_or(20.0, |v| v as f32); + self.absorption = f("AbsorptionAmount").map_or(0.0, |v| v as f32); self.food = n("foodLevel").map_or(20, |v| v as i32); self.saturation = f("foodSaturationLevel").map_or(5.0, |v| v as f32); self.food_exhaustion = f("foodExhaustionLevel").unwrap_or(0.0) as f32; @@ -2626,6 +2629,7 @@ impl Level { ("OnGround", Tag::Byte(i8::from(self.on_ground))), ("fall_distance", Tag::Double(self.fall_distance.to_bits())), ("Health", Tag::Float(self.health.to_bits())), + ("AbsorptionAmount", Tag::Float(self.absorption.to_bits())), ("foodLevel", Tag::Int(self.food)), ("foodSaturationLevel", Tag::Float(self.saturation.to_bits())), ( @@ -2731,7 +2735,6 @@ impl Level { ("seenCredits", Tag::Byte(0)), ("HurtTime", Tag::Short(0)), ("DeathTime", Tag::Short(0)), - ("AbsorptionAmount", Tag::Float(0)), ("FallFlying", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); @@ -4114,6 +4117,7 @@ mod tests { position: Some([1.5, 70.0, -3.25]), rotation: [90.0, 10.0], health: 17.0, + absorption: 5.0, food: 15, saturation: 2.5, inventory: vec![ @@ -4144,6 +4148,7 @@ mod tests { assert_eq!(back.position, Some([1.5, 70.0, -3.25])); assert_eq!(back.rotation, [90.0, 10.0]); assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); + assert_eq!(back.absorption, 5.0); let mut inv = back.inventory.clone(); inv.sort(); assert_eq!( @@ -4178,10 +4183,13 @@ mod tests { let mut again = Level { player_extra: Some(extra), ender_items: ender, + // The live amount, not the one the loaded compound held (#1307). + absorption: 2.0, ..back }; again.write(&dir).unwrap(); let third = Level::read(&dir).unwrap(); + assert_eq!(third.absorption, 2.0); assert!(matches!( third .player_extra diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..a4fdafe71 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,12 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- absorption: the host and the guest each take Absorption II and a hit of 3: their own HUD has the + server's golden hearts, 8 then 5 (#1306). +- breath: the host and the guest each stay underwater for 15 s in a Respiration III helmet: their + own bubbles follow the server's air, which the enchantment makes last (#1304). +- lava: (--server-thread) the host and the guest each stand in a Nether lava current with Fire + Resistance, which pushes them at the Nether's strength (#1309). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +178,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'absorption', 'breath', 'lava'] class Game: @@ -2297,6 +2303,117 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def server_player(host, game): + """The player's entry on the server: the guest's in the host's `lan status`, on the server + thread the host's too; the host's own world otherwise.""" + if game is host and not SERVER_THREAD: + return own(host) + name = GUEST_NAME if game is not host else host.player + return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name) + + +def check_absorption(host, guest, out): + """Absorption II's golden hearts on each player's own HUD: 8 of them, and 5 once a hit of 3 took + its share: the client shows what the server's player has (#1306).""" + seen = {} + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='effect give @s minecraft:absorption 120 1') + game.wait(10) + given = own(game)['absorption'] + game('command', command='damage @s 3 minecraft:generic') + game.wait(20) + me = own(game) + server = server_player(host, game) + game.shot(out, 'absorption') + game('command', command='effect clear @s minecraft:absorption') + seen[game.name] = {'given': given, 'left': me['absorption'], 'health': me['health'], + 'server': server.get('absorption')} + for name, s in seen.items(): + assert s['given'] == 8.0 and s['left'] == 5.0 == s['server'] and s['health'] == 20.0, \ + f'{name}: {seen}' + return seen + + +def check_breath(host, guest, out): + """Underwater in a Respiration III helmet for 15 s: the enchantment makes the air last on the + server, and each player's own bubbles follow the server's air (#1304).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s armor.head with ' + 'minecraft:diamond_helmet[minecraft:enchantments={"minecraft:respiration":3}]') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:stone') + game('command', command=f'fill {x} {y} {z} {x} {y + 1} {z} minecraft:water') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + host.wait(300) + for game in (host, guest): + game.shot(out, 'breath') + seen[game.name] = {'own': own(game)['air'], 'server': server_player(host, game).get('air')} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='item replace entity @s armor.head with minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone') + guest.wait(40) + # 300 ticks lose about 75 of the 300 with Respiration III, all of it without. + for name, s in seen.items(): + assert s['server'] > 150 and abs(s['own'] - s['server']) <= 10, f'{name}: {seen}' + return seen + + +def check_lava(host, guest, out): + """(--server-thread) Standing in a settled Nether lava current with Fire Resistance: the + Nether's FAST_LAVA pushes each player about three times as hard as the Overworld's (#1309).""" + if not SERVER_THREAD: + return 'skipped (needs --server-thread)' + seen = {} + back = {g.name: pos_of(g) for g in (host, guest)} + try: + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'execute in minecraft:the_nether run tp @s 0.5 100 {z + 0.5}') + state = wait_dimension(game, 'minecraft:the_nether', 600) + assert state.get('dimension') == 'minecraft:the_nether', f'{game.name} is in {state.get("dimension")}' + game.wait(40) + # A one-wide obsidian channel along x: a source at x = -3, the current flowing east. + game('command', command=f'fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + game('command', command=f'fill -5 98 {z - 1} 6 98 {z + 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z - 1} 6 99 {z - 1} minecraft:obsidian') + game('command', command=f'fill -5 99 {z + 1} 6 99 {z + 1} minecraft:obsidian') + game('command', command=f'fill -4 99 {z} -4 99 {z} minecraft:obsidian') + game('command', command='effect give @s minecraft:fire_resistance 120 0 true') + game('command', command='gamemode survival') + game('command', command=f'setblock -3 99 {z} minecraft:lava') + host.wait(100) + for game, z in ((host, 0), (guest, 6)): + game('command', command=f'tp @s 0.5 99 {z + 0.5}') + host.wait(60) + for game, z in ((host, 0), (guest, 6)): + v = own(game)['velocity'] + seen[game.name] = {'vx': v[0], 'level': game.raw('block', 0, 99, z).get('state')} + game.shot(out, 'lava') + finally: + for game, z in ((host, 0), (guest, 6)): + host('command', command=f'execute in minecraft:the_nether run fill -5 98 {z - 2} 6 104 {z + 2} minecraft:air') + x, y, zz = back[game.name] + game('command', command='effect clear @s minecraft:fire_resistance') + game('command', command=f'execute in minecraft:overworld run tp @s {x:.2f} {y:.2f} {zz:.2f}') + for game in (host, guest): + wait_dimension(game, 'minecraft:overworld', 600) + guest.wait(40) + # The Overworld's current settles at about 0.0047 a tick, the Nether's at about 0.014. + for name, s in seen.items(): + assert s['vx'] > 0.009, f'{name}: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3192,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava} def run(ctl, out, resources, checks): From ed28e1dd0d6f6959179ba5f1914cfb69de14d1ae Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:56:08 +0200 Subject: [PATCH 04/12] Contact damage: magma, cactus, lit campfires and sweet berry bushes hurt in both modes Entity.applyEffectsFromBlocks: MagmaBlock.stepOn burns a player standing on it who is not sneaking (hot_floor, 1), CactusBlock and CampfireBlock.entityInside hurt what touches them (cactus 1, campfire 1, soul campfire 2, lit only). A server's players (LAN guests, and the host on the server thread) now get these and the grown sweet berry bush prick along the moves their client sent that tick: the server rebuilds the tick's movement history and runs the damage half of the block effects. lan_e2e `contacts`: magma, sneaking on magma, a lit campfire, a cactus, grown and young berry bushes, for the host and the guest. Fixes #1305, #1311, #1312, #1313. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 25 +++++++ crates/horizon-client/src/motion.rs | 73 ++++++++++++++++++- .../horizon-client/src/motion/environment.rs | 2 +- tools/lan_e2e.py | 64 +++++++++++++++- 4 files changed, 158 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..9d1181b80 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1765,6 +1765,7 @@ impl Game<'_> { } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; + let sneaking = g.sneaking; let sounds = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; @@ -1783,6 +1784,26 @@ impl Game<'_> { let _ = w.fluid_base_tick(); w.player.ground.on_ground = from_ground; let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect(); + // Entity.move's movementThisTick: each move, from where the + // tick's first one started. + let end = w.player.position; + let start = travelled + .iter() + .fold(end, |p, d| p.subtract(Vec3::new(d[0], d[1], d[2]))); + w.player.history.clear(); + let mut from = start; + for d in &travelled { + let delta = Vec3::new(d[0], d[1], d[2]); + let to = from.add_vector(delta); + w.player + .history + .add(horizon_world::entity_move::MovementRecord { + from, + to, + original: Some(delta), + }); + from = to; + } for (moved, on_ground) in moves { let movement = Vec3::new(moved[0], moved[1], moved[2]); if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 { @@ -1808,6 +1829,10 @@ impl Game<'_> { if w.climbable().unwrap_or(false) { w.player.fall_distance = 0.0; } + // Entity.applyEffectsFromBlocks along those moves: magma, cactus, + // lit campfires and grown sweet berry bushes hurt (#1305). + w.player.shift_key_down = sneaking; + let _ = w.server_block_damage(start); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1920026b9..8831a5912 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1029,9 +1029,22 @@ impl MotionWorld<'_, '_, '_> { } /// `Entity.applyEffectsFromBlocks` for the blocks Horizon's player reacts /// to inside its movement path: powder snow (`PowderSnowBlock.entityInside` - /// and the FREEZE / EXTINGUISH effects), cobwebs and sweet berry bushes. Pressure plates, tripwires and - /// rails are the world tick's scan. + /// and the FREEZE / EXTINGUISH effects), cobwebs, sweet berry bushes, + /// cactus and lit campfires, and the magma block it stands on + /// (`stepOn`). Pressure plates, tripwires and rails are the world tick's + /// scan. pub fn apply_effects_from_blocks(&mut self) -> Result<()> { + self.effects_from_blocks(false) + } + /// What `applyEffectsFromBlocks` does to a server's player along the + /// moves its client sent since `from` (in its history): the damage of + /// magma, cactus, lit campfires and grown sweet berry bushes. Its client + /// moves it, so the slowing and the rest are the client's. + pub fn server_block_damage(&mut self, from: Vec3) -> Result<()> { + self.player.old_position = from; + self.effects_from_blocks(true) + } + fn effects_from_blocks(&mut self, damage_only: bool) -> Result<()> { use horizon_world::entity_move::MovementRecord; let mut movements: Vec = self.player.history.records().iter().copied().collect(); @@ -1056,6 +1069,19 @@ impl MotionWorld<'_, '_, '_> { if self.player.spectator { return Ok(()); } + // Block.stepOn for the block under an entity on the ground: + // MagmaBlock's hot floor hurts unless it steps carefully (sneaks). + if self.player.ground.on_ground { + let on = self.legacy_on_position()?; + let magma = self + .assets + .registry + .state(self.block(on)) + .is_some_and(|s| s.name == "minecraft:magma_block"); + if magma && !self.player.shift_key_down { + self.environment_hurt("minecraft:hot_floor", 1.0)?; + } + } let mut visited = std::collections::HashSet::new(); let mut entered = Vec::new(); for movement in &movements { @@ -1081,6 +1107,7 @@ impl MotionWorld<'_, '_, '_> { &mut visited, &mut entered, budget, + damage_only, )?; from = to; } @@ -1093,11 +1120,19 @@ impl MotionWorld<'_, '_, '_> { &mut visited, &mut entered, 16, + damage_only, )?; } } if budget <= 0 { - self.check_inside_blocks(movement.to, movement.to, &mut visited, &mut entered, 1)?; + self.check_inside_blocks( + movement.to, + movement.to, + &mut visited, + &mut entered, + 1, + damage_only, + )?; } } // InsideBlockEffectApplier.StepBasedCollector: the blocks entered @@ -1137,6 +1172,7 @@ impl MotionWorld<'_, '_, '_> { visited: &mut std::collections::HashSet, entered: &mut Vec<(i32, BlockPos)>, max_iterations: i32, + damage_only: bool, ) -> Result { let deflated = self.player.dimensions.bounds(to).deflate(Vec3::new( f64::from(1.0e-5_f32), @@ -1213,6 +1249,33 @@ impl MotionWorld<'_, '_, '_> { } }; if inside && visited.insert(p.pack()) { + // CactusBlock and CampfireBlock.entityInside (`entity.hurt`). + match name { + "minecraft:cactus" => self.environment_hurt("minecraft:cactus", 1.0)?, + "minecraft:campfire" | "minecraft:soul_campfire" => { + let lit = self + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("lit")) + .is_some_and(|v| v == "true"); + let damage = if name == "minecraft:campfire" { + 1.0 + } else { + 2.0 + }; + if lit { + self.environment_hurt("minecraft:campfire", damage)?; + } + } + "minecraft:sweet_berry_bush" if damage_only => { + self.sweet_berry_bush_damage(state)?; + } + _ => {} + } + if damage_only { + continue; + } match name { "minecraft:powder_snow" => { self.powder_snow_inside(p)?; @@ -1261,6 +1324,10 @@ impl MotionWorld<'_, '_, '_> { /// is at least 0.003 on X or Z. fn sweet_berry_bush_inside(&mut self, state: BlockStateId) -> Result<()> { self.make_stuck_in_block(Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32))); + self.sweet_berry_bush_damage(state) + } + /// The server's half of `SweetBerryBushBlock.entityInside`: the prick. + fn sweet_berry_bush_damage(&mut self, state: BlockStateId) -> Result<()> { let age = self .assets .registry diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index a9bb33678..fc3c63c77 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -6,7 +6,7 @@ use horizon_world::{ living_fluid::{LivingFluidWorld, TravelFluidTag}, }; impl MotionWorld<'_, '_, '_> { - fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { + pub(super) fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { if self.player.invulnerable || self.player.spectator { return Ok(()); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..4226f8521 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,9 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- contacts: the host and the guest each stand on magma (and sneak on it), stand on a lit campfire, + walk against a cactus and through grown sweet berry bushes: the server hurts them, but + not the sneaking player or young bushes (#1305, #1311, #1312, #1313). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +175,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'contacts'] class Game: @@ -2297,6 +2300,62 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def check_contacts(host, guest, out): + """Blocks that hurt what touches them, on the server: standing on magma (but not sneaking on it) + and on a lit campfire, walking against a cactus and through grown sweet berry bushes, for the + host and the guest (#1305, #1311, #1312, #1313); a young bush pricks no one.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule natural_health_regeneration false') + seen = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 2, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='effect clear @s') + for case, blocks, walk in ( + ('magma', [(0, -1, 'minecraft:magma_block')], False), + ('sneaking', [(0, -1, 'minecraft:magma_block')], False), + ('campfire', [(0, 0, 'minecraft:campfire[lit=true]')], False), + ('cactus', [(2, -1, 'minecraft:sand'), (2, 0, 'minecraft:cactus')], True), + ('berries', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)] + + [(k, 0, 'minecraft:sweet_berry_bush[age=3]') for k in range(1, 4)], True), + ('young', [(k, -1, 'minecraft:grass_block') for k in range(1, 4)] + + [(k, 0, 'minecraft:sweet_berry_bush[age=0]') for k in range(1, 4)], True)): + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command=f'fill {x - 1} {y - 2} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone') + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air') + # A wall ends the walk before the player leaves the floor. + game('command', command=f'fill {x + 5} {y - 1} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:stone') + for dx, dy, block in blocks: + game('command', command=f'setblock {x + dx} {y + dy} {z} {block}') + stand = 0.5 if case == 'campfire' else 0.0 + game('command', command=f'tp @s {x + 0.5} {y + stand} {z + 0.5}') + game.raw('look-at', f'{x + 10:.2f}', f'{y + 1.6:.2f}', f'{z + 0.5:.2f}') + game.wait(30) + before = own(game)['health'] + keys = (['shift'] if case == 'sneaking' else []) + (['w'] if walk else []) + for k in keys: + game.raw('key', k, 'down') + game.wait(60) + for k in keys: + game.raw('key', k, 'up') + game.wait(10) + seen[f'{game.name}-{case}'] = (before, own(game)['health']) + game.shot(out, f'contacts-{case}') + host('command', command=f'fill {x - 1} {y} {z - 1} {x + 5} {y + 2} {z + 1} minecraft:air') + finally: + host('command', command='gamerule natural_health_regeneration true') + for case, (before, after) in seen.items(): + safe = case.endswith(('sneaking', 'young')) + assert (after == before) if safe else (after < before), f'{case}: {before} -> {after} (all: {seen})' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3134,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'contacts': check_contacts} def run(ctl, out, resources, checks): From 2898b40670eb253a924560d5edfe8c3a4256a725 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:58:56 +0200 Subject: [PATCH 05/12] Server players: an axe-disabled shield stays down 5 s, death forgets the digging ItemCooldowns ticks once a tick for each player: a server's players count their shield cooldown down in tick_guests, and the host's world in tick_world (it was in tick_using, which ran for the host and again for every guest's swap, so a guest's shield came back early on the server thread). A guest that dies stops digging (its mining, the delay and the crack go), so the block it was breaking doesn't break once it respawns. lan_e2e: `shield` (a vindicator's axe disables each player's shield; the server's cooldown then falls 40 in 40 ticks) and `deathmining` (die while breaking obsidian, respawn, the obsidian stays). `lan status` and the agent state report the shield cooldown. Fixes #1315, #1316. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 5 +- crates/horizon-client/src/game/agent.rs | 1 + crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 30 ++++ tools/lan_e2e.py | 133 +++++++++++++++++- 5 files changed, 167 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..f15b6e9f6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3581,8 +3581,6 @@ impl Game<'_> { } } fn tick_using(&mut self) { - // ItemCooldowns.tick for the shield. - self.shield_cooldown = self.shield_cooldown.saturating_sub(1); let Some(hand) = self.used_hand() else { return; }; @@ -4285,6 +4283,9 @@ impl Game<'_> { fn tick_world(&mut self, running: bool) -> Result<()> { self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects()); + // Player.tick's ItemCooldowns.tick for the window's player (a + // server's players count theirs down in `tick_guests`). + self.shield_cooldown = self.shield_cooldown.saturating_sub(1); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..f9a8e8c04 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -461,6 +461,7 @@ impl Game<'_> { "health": p.health.health(), "food": p.health.food.food, "saturation": p.health.food.saturation, + "shield_cooldown": self.shield_cooldown, "xp": { "level": self.experience.level, "progress": self.experience.progress, "total": self.experience.total }, "effects": self.potions.effects.list.iter().map(|e| json!({ "id": e.id, "duration_ticks": e.duration, "amplifier": e.amplifier })).collect::>(), }) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..f09d2cc22 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -390,6 +390,8 @@ impl Game<'_> { "placed": g.placed, "loaded": g.loaded, "game_mode": g.game_mode, + // ItemCooldowns: the ticks the shield an axe disabled stays down. + "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), "sneaking": g.sneaking, "sleeping": g.bed, "health": g.health, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0d70b16f6..4cf5d0a0e 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -34,6 +34,8 @@ pub(super) struct GuestPlay { destroy_delay: u32, using: Option<(usize, u32)>, use_delay: u32, + /// The shield's ItemCooldowns entry: an axe disabled it for this many ticks. + pub(super) shield_cooldown: u32, attack_ticks: u32, /// The main hand's item at the guest's last tick (`Game::attack_item`). attack_item: Option>, @@ -117,6 +119,7 @@ pub(super) struct GuestSwap { destroy_delay: u32, using: Option<(usize, u32)>, use_delay: u32, + pub(super) shield_cooldown: u32, attack_ticks: u32, attack_item: Option>, swing: horizon_client::first_person::SwingState, @@ -290,6 +293,7 @@ impl Game<'_> { let destroy_delay = std::mem::replace(&mut self.destroy_delay, play.destroy_delay); let using = std::mem::replace(&mut self.using, play.using.take()); let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay); + let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown); let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks); let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take()); let swing = std::mem::replace(&mut self.swing, play.swing); @@ -369,6 +373,7 @@ impl Game<'_> { destroy_delay, using, use_delay, + shield_cooldown, attack_ticks, attack_item, swing, @@ -421,6 +426,7 @@ impl Game<'_> { destroy_delay, using, use_delay, + shield_cooldown, attack_ticks, attack_item, swing, @@ -480,6 +486,7 @@ impl Game<'_> { play.destroy_delay = std::mem::replace(&mut self.destroy_delay, destroy_delay); play.using = std::mem::replace(&mut self.using, using); play.use_delay = std::mem::replace(&mut self.use_delay, use_delay); + play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown); play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks); play.attack_item = std::mem::replace(&mut self.attack_item, attack_item); play.swing = std::mem::replace(&mut self.swing, swing); @@ -1562,6 +1569,9 @@ 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). + play.shield_cooldown = play.shield_cooldown.saturating_sub(1); let digging = play.digging; let using = play.using.is_some(); let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100; @@ -1616,6 +1626,9 @@ impl Game<'_> { self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); self.guest_orbs(host, gi); + if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { + self.guest_forget_digging(host, conn); + } let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; @@ -1968,6 +1981,23 @@ impl Game<'_> { /// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the /// host and the other guests. + /// A player who dies digs and uses nothing any more: the block it was + /// breaking, or had left to break (`hasDelayedDestroy`), stays, and its + /// crack goes. Respawning gives it a new ServerPlayerGameMode (#1315). + fn guest_forget_digging(&mut self, host: &mut LanHost, conn: u32) { + let Some(play) = host.play.get_mut(&conn) else { + return; + }; + let cracked = play.digging.take().filter(|_| play.last_progress >= 0); + play.mining = None; + play.delayed = None; + play.destroy_delay = 0; + play.using = None; + play.last_progress = -1; + if let Some((pos, _)) = cracked { + self.guest_crack_gone(host, conn, pos); + } + } fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else { return; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..c68fbff7d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,10 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- shield: the host axes the guest's raised shield, then the guest the host's: it stays disabled + for 5 s on that player's own cooldown, then blocks again (#1316). +- deathmining: the host and the guest each die while breaking obsidian and let go on the death + screen: once respawned, the obsidian stays (#1315). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +176,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'shield', 'deathmining'] class Game: @@ -2297,6 +2301,130 @@ def check_flight(host, guest, out): +def own(game): + """The player's own state, as its client has it.""" + return game('state')['player'] + + +def server_player(host, game): + """The player's entry on the server: the guest's in the host's `lan status`, on the server + thread the host's too; the host's own world otherwise.""" + if game is host and not SERVER_THREAD: + return own(host) + name = GUEST_NAME if game is not host else host.player + return next(g for g in host.raw('lan', 'status')['guests'] if g['name'] == name) + + +def check_shield(host, guest, out): + """An axe disables a raised shield for 5 s (100 ticks), counted down once a tick on the + server: a vindicator's axe hits each player's shield, then the cooldown left falls by about 40 + over 40 ticks (#1316).""" + host('command', command='gamerule natural_health_regeneration false') + rates = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, y, z = (int(v // 1) for v in pos_of(host)) + z += dz + game('command', command='gamemode survival') + game('command', command='effect give @s minecraft:resistance 60 4 true') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 4} {y + 2} {z + 1} minecraft:air') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 4} {y - 1} {z + 1} minecraft:stone') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(10) + game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}') + game.raw('mouse', 'right', 'down') + game.wait(10) + host('command', command=f'summon minecraft:vindicator {x + 2.5} {y} {z + 0.5} ' + '{PersistenceRequired:1b,Rotation:[90f,0f]}') + host('command', command='item replace entity @e[type=minecraft:vindicator] weapon.mainhand ' + 'with minecraft:iron_axe') + first = None + for _ in range(60): + game.wait(5) + first = server_player(host, game).get('shield_cooldown', 0) + if first: + break + host('command', command='kill @e[type=minecraft:vindicator]') + game.raw('mouse', 'right', 'up') + assert first, f'{game.name}: the vindicator never disabled the shield' + start = server_player(host, game)['shield_cooldown'] + game.wait(40) + end = server_player(host, game)['shield_cooldown'] + rates[game.name] = {'first': first, 'start': start, 'end': end} + game.shot(out, 'shield') + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + game('command', command='effect clear @s') + finally: + host('command', command='kill @e[type=minecraft:vindicator]') + host('command', command='gamerule natural_health_regeneration true') + for name, r in rates.items(): + assert r['first'] <= 100, f'{name}: {rates}' + # Once a tick: 40 down over 40 ticks, give or take the ticks the two queries straddle. + assert 30 <= r['start'] - r['end'] <= 50, f'{name}: {rates}' + return rates + + +def respawn_when_ready(game): + """Press Respawn once the death screen lets it (DeathScreen's 20-tick delay, counted from when + the screen opens).""" + for _ in range(20): + try: + return game.raw('respawn') + except Failed as e: + if 'not active yet' not in str(e): + raise + game.wait(10) + return game.raw('respawn') + + +def check_death_mining(host, guest, out): + """A player who dies while breaking obsidian, and lets go of attack on the death screen, doesn't + break it once respawned: death forgets the digging (#1315).""" + host('command', command='gamerule keep_inventory true') + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, y, z = hx + 2, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s weapon.mainhand with minecraft:diamond_pickaxe') + game('command', command=f'setblock {x + 2} {y} {z} minecraft:obsidian') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(10) + game.raw('look-at', f'{x + 2.5:.2f}', f'{y + 0.5:.2f}', f'{z + 0.5:.2f}') + game.wait(5) + game.raw('mouse', 'left', 'down') + game.wait(10) + game('command', command='kill @s') + game.wait(10) + # The death screen lets go of the button (Minecraft.setScreen); let go again once back. + try: + game.raw('mouse', 'left', 'up') + except Failed: + pass + game.wait(10) + respawn_when_ready(game) + game.wait(2) + try: + game.raw('mouse', 'left', 'up') + except Failed: + pass + # Obsidian takes a diamond pickaxe about 190 ticks. + game.wait(240) + seen[game.name] = host.raw('block', x + 2, y, z).get('block') + game.shot(out, 'death-mining') + host('command', command=f'setblock {x + 2} {y} {z} minecraft:air') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + finally: + host('command', command='gamerule keep_inventory false') + for name, block in seen.items(): + assert block == 'minecraft:obsidian', f'{name}: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3203,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'shield': check_shield, 'deathmining': check_death_mining} def run(ctl, out, resources, checks): From 5c4600e4034ed5a5a0fc50c3d498dccbc8ab04cf Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:59:14 +0200 Subject: [PATCH 06/12] /setworldspawn moves the world spawn, not the player's respawn point SetWorldSpawnCommand sets the level's spawn and its angle; a player without a bed or anchor respawns there (it used to set the player's own spawn point, so other players and later deaths kept the old one). The angle is saved in level.dat's spawn (yaw, pitch), and a guest whose saved respawn point is the world spawn follows it when it moves. lan_e2e `worldspawn`: /setworldspawn 24 blocks east, then the host and the guest die and respawn there. Fixes #1310. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands.rs | 14 +++++- crates/horizon-client/src/lan/playerdata.rs | 7 ++- crates/horizon-client/src/save.rs | 13 +++++- tools/lan_e2e.py | 50 ++++++++++++++++++++- 4 files changed, 78 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index f174f98c1..f35354f74 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2322,7 +2322,19 @@ impl Game<'_> { Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), _ => [0.0, 0.0], }; - self.level.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + // LevelData.setRespawnData: the world's spawn (level.dat `spawn`). + let old = self.level.world_spawn.replace(pos); + self.level.world_spawn_angle = rot; + // A player whose respawn point is the world spawn (no bed, anchor or + // spawnpoint of its own) respawns at the new one. + let floor = |s: Vec3| [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32]; + if self.respawn_config.is_none() && self.spawn.map(floor) == old { + self.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + } let args = [ Text::literal(pos[0].to_string()), Text::literal(pos[1].to_string()), diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 8797f25a2..841f4da38 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -71,7 +71,12 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.game_mode = level.mode(); guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); - guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); + // A point that is the world spawn is none of the player's own: it + // respawns wherever the world spawn is then (`setworldspawn`). + guest.spawn = level + .spawn + .filter(|s| Some(s.map(|v| v.floor() as i32)) != level.world_spawn) + .map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 0cfe3c585..8787415d9 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2288,6 +2288,8 @@ pub struct Level { pub dimension: String, /// World spawn (`level.dat` `spawn`), distinct from a bed respawn point. pub world_spawn: Option<[i32; 3]>, + /// The world spawn's yaw and pitch (`setworldspawn`'s rotation). + pub world_spawn_angle: [f32; 2], pub difficulty: String, pub hardcore: bool, /// `difficulty_settings.locked` (LevelData.isDifficultyLocked). @@ -2365,6 +2367,11 @@ impl Level { ] }), }; + let angle = |k: &str| match data.get("spawn").and_then(|s| s.get(k)) { + Some(Tag::Float(b)) => f32::from_bits(*b), + _ => 0.0, + }; + level.world_spawn_angle = [angle("yaw"), angle("pitch")]; if let Some(d) = data.get("difficulty_settings") { level.difficulty = text(d.get("difficulty")).unwrap_or_else(|| "normal".into()); level.hardcore = n(d.get("hardcore")) != 0; @@ -2857,8 +2864,8 @@ impl Level { Tag::compound([ ("pos", Tag::IntArray(spawn.to_vec())), ("dimension", string("minecraft:overworld")), - ("yaw", Tag::Float(0f32.to_bits())), - ("pitch", Tag::Float(0f32.to_bits())), + ("yaw", Tag::Float(self.world_spawn_angle[0].to_bits())), + ("pitch", Tag::Float(self.world_spawn_angle[1].to_bits())), ]), ), ("difficulty_settings", difficulty), @@ -4126,6 +4133,7 @@ mod tests { xp_total: 30, dimension: "minecraft:the_nether".into(), world_spawn: Some([8, 64, 8]), + world_spawn_angle: [45.0, -10.0], spawn: Some([20.0, 70.0, 20.0]), difficulty_locked: true, flying: true, @@ -4160,6 +4168,7 @@ mod tests { ); assert_eq!(back.dimension, "minecraft:the_nether"); assert_eq!(back.world_spawn, Some([8, 64, 8])); + assert_eq!(back.world_spawn_angle, [45.0, -10.0]); assert_eq!(back.spawn, Some([20.0, 70.0, 20.0])); assert!(back.difficulty_locked); assert!(back.weather.raining); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..6f416306b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,8 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- worldspawn: the host moves the world spawn (`setworldspawn`): the host and the guest, with no bed, + respawn there (#1310). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +174,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn'] class Game: @@ -2297,6 +2299,49 @@ def check_flight(host, guest, out): +def respawn_when_ready(game): + """Press Respawn once the death screen lets it (DeathScreen's 20-tick delay, counted from when + the screen opens).""" + for _ in range(20): + try: + return game.raw('respawn') + except Failed as e: + if 'not active yet' not in str(e): + raise + game.wait(10) + return game.raw('respawn') + + +def check_world_spawn(host, guest, out): + """`setworldspawn` moves the world spawn: the host and the guest, with no bed of their own, + respawn there once killed (#1310).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + sx, sz = hx + 24, hz + host('command', command='gamerule respawn_radius 0') + host('command', command=f'fill {sx - 2} {hy - 1} {sz - 2} {sx + 2} {hy - 1} {sz + 2} minecraft:stone') + host('command', command=f'fill {sx - 2} {hy} {sz - 2} {sx + 2} {hy + 3} {sz + 2} minecraft:air') + seen = {} + try: + host('command', command=f'setworldspawn {sx} {hy} {sz}') + for game in (host, guest): + game('command', command='gamemode survival') + game('command', command='kill @s') + game.wait(20) + respawn_when_ready(game) + game.wait(60) + seen[game.name] = [round(v, 2) for v in pos_of(game)] + game.shot(out, 'world-spawn') + finally: + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='gamerule respawn_radius 10') + for game in (host, guest): + game('command', command=f'tp @s {hx + 0.5} {hy} {hz + 0.5}') + guest.wait(20) + for name, at in seen.items(): + assert abs(at[0] - (sx + 0.5)) < 1 and abs(at[2] - (sz + 0.5)) < 1, f'{name}: {seen}, spawn {sx} {sz}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3120,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'worldspawn': check_world_spawn} def run(ctl, out, resources, checks): From 65bd2d0d45e15710af70cad00f642ae80f48b86e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 04:59:19 +0200 Subject: [PATCH 07/12] Items push out of blocks; a server's client digs at the server's speed ItemEntity.tick: an item stuck inside a full block (one set on it) has no physics on the server and moves toward the closest free side (Entity.moveTowardsClosestSpace: north, south, west, east, up; 0.1 to 0.3 a tick), instead of staying in the block (#1252). A server's client (LAN guests, and the window on the server thread) digs at the same speed as the server: getDestroyProgress with the submerged mining speed, haste, fatigue and efficiency, not the plain tool speed, so it no longer finishes early under water and gets the block put back (#1254). lan_e2e: `drops` (a diamond under a block set on it comes out, in both views) and `underwater` (dirt by hand at eye height under water: about halfway at 35 ticks on client and server, broken by 105). Fixes #1252, #1254. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entities.rs | 78 ++++++++++++++++++++++-- crates/horizon-client/src/game.rs | 9 ++- crates/horizon-client/src/game/agent.rs | 2 + crates/horizon-client/src/game/remote.rs | 19 ++---- tests/test_remote_mining.py | 4 ++ tools/lan_e2e.py | 77 ++++++++++++++++++++++- 6 files changed, 167 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index cfbdb0636..65536d710 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -98,12 +98,73 @@ impl ItemEntity { lava_hurt, } } - /// Returns false when the item should be removed. + /// `ItemEntity.tick` on a server: an item whose box is inside a block + /// (one placed where it lay) has no physics this tick + /// (`level.noCollision(box.deflate(1.0E-7))`). + pub fn inside_block(&self, world: &World, collision: &BlockCollisionRegistry<'_>) -> bool { + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let inner = self.bounds().deflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); + !crate::collisions::no_collision_empty(&mut scene, inner) + } + /// `Entity.moveTowardsClosestSpace` from the middle of the item's box: + /// towards the nearest side of its block (north, south, west, east or + /// up) without a full collision cube, at `speed` (`nextFloat() * 0.2 + + /// 0.1`). + pub fn move_towards_closest_space(&mut self, world: &World, facts: &BlockFacts, speed: f32) { + let bounds = self.bounds(); + let at = Vec3::new( + self.position.x, + (bounds.min_position().y + bounds.max_position().y) / 2.0, + self.position.z, + ); + let pos = [ + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ]; + let delta = [ + at.x - f64::from(pos[0]), + at.y - f64::from(pos[1]), + at.z - f64::from(pos[2]), + ]; + // (axis, step): NORTH, SOUTH, WEST, EAST, UP. + let mut closest = (1, 1); + let mut nearest = f64::MAX; + for (axis, step) in [(2, -1), (2, 1), (0, -1), (0, 1), (1, 1)] { + let mut n = pos; + n[axis] += step; + if !facts.get(world.block(n[0], n[1], n[2])).full_collision { + let d = if step > 0 { + 1.0 - delta[axis] + } else { + delta[axis] + }; + if d < nearest { + nearest = d; + closest = (axis, step); + } + } + } + let push = f64::from(closest.1 as f32 * speed); + let v = self.velocity.scale(0.75); + self.velocity = match closest.0 { + 0 => Vec3::new(push, v.y, v.z), + 1 => Vec3::new(v.x, push, v.z), + _ => Vec3::new(v.x, v.y, push), + }; + } + /// Returns false when the item should be removed. `no_physics`: the item + /// moves through blocks this tick ([`ItemEntity::inside_block`]). pub fn tick( &mut self, world: &World, facts: &BlockFacts, collision: &BlockCollisionRegistry<'_>, + no_physics: bool, ) -> bool { self.ticks += 1; self.previous = self.position; @@ -140,15 +201,22 @@ impl ItemEntity { subject: None, }; let wanted = self.velocity; - let moved = scene - .resolve(self.bounds(), wanted, 0.0, self.on_ground) - .unwrap_or(Vec3::ZERO); + // Entity.move with noPhysics: straight through, the ground as it was. + let moved = if no_physics { + wanted + } else { + scene + .resolve(self.bounds(), wanted, 0.0, self.on_ground) + .unwrap_or(Vec3::ZERO) + }; self.position = Vec3::new( self.position.x + moved.x, self.position.y + moved.y, self.position.z + moved.z, ); - self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if !no_physics { + self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + } if moved.x != wanted.x { self.velocity.x = 0.0; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5da86dfaf..0b1ca23fd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2101,7 +2101,14 @@ impl Game<'_> { ) { continue; } - let alive = item.tick(&self.world, self.res.facts(), self.collision); + // ItemEntity.tick's noPhysics (servers only): out of a block + // placed on it, towards the closest open side (#1252). + let no_physics = merging && item.inside_block(&self.world, self.collision); + if no_physics { + let speed = self.world.random.next_float() * 0.2 + 0.1; + item.move_towards_closest_space(&self.world, self.res.facts(), speed); + } + let alive = item.tick(&self.world, self.res.facts(), self.collision, no_physics); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index ea686e711..15564dc3e 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -478,6 +478,8 @@ impl Game<'_> { "sleeping": self.sleeping, // The item in use: its slot and for how many ticks. "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), + // The block being dug: how far along, after how many ticks. + "mining": self.mining.as_ref().map(|m| json!({ "pos": m.pos, "progress": m.progress, "ticks": m.ticks })), // The arm swings started (LivingEntity.swing). "swings": self.swings_started, "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..563ab4170 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3469,22 +3469,13 @@ impl Game<'_> { return; } let facts = self.res.facts().get(state).clone(); - let held = self.held().cloned(); - let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name); - if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { - speed /= 5.0; - } - let harvest = !facts.requires_tool - || self - .res - .items() - .correct_for_drops(held.as_ref(), &facts.name); - let progress = if facts.hardness < 0.0 { - 0.0 - } else if facts.hardness == 0.0 { + // The server's own getDestroyProgress: under water, off the ground, + // with haste, fatigue and efficiency, so the client stops digging + // when the server is done too (#1254). + let progress = if facts.hardness == 0.0 { 1.0 } else { - speed / facts.hardness / if harvest { 30.0 } else { 100.0 } + self.destroy_progress(hit.pos) }; let same = self .remote diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 236b85c28..1a35b3865 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -79,6 +79,10 @@ impl Game { } fn pick(&self) -> Option { Some(self.hit) } fn held(&self) -> Option<&()> { None } + // Game::destroy_progress (hand.rs) for a harvestable block on the ground. + fn destroy_progress(&self, _: [i32; 3]) -> f32 { + self.res.speed / self.res.facts.hardness / 30.0 + } fn next_sequence(&mut self) -> i32 { self.sequence += 1; self.sequence } 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); } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c5a90150f..6bdc52905 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -131,6 +131,10 @@ address. The script then checks, from both sides, what a guest's game used to ge get off by sneaking; the other side sees the animal move. - lightning: a bolt summoned beside the host, then the guest: both sides get the bolt and flash the sky (on its server thread the host's window is a client of it too). +- drops: an item lies where the host, then the guest, places a block: it comes out of the block + on the server, and both sides see it outside (#1252). +- underwater: the host and the guest each dig dirt by hand standing under water: five times slower + than in the air on their own client as on the server, and it breaks (#1254). - flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: the guest, and on the server thread the host's window too, take what may fly from the server's abilities (ClientPacketListener.handlePlayerAbilities). @@ -172,7 +176,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'drops', 'underwater'] class Game: @@ -2297,6 +2301,74 @@ def check_flight(host, guest, out): +def check_drops(host, guest, out): + """A dropped item lying where a block is then placed comes out of it (#1252): the server moves + it towards the closest open side (ItemEntity.tick's noPhysics, Entity.moveTowardsClosestSpace), + and both sides see it outside the block. The host places one, then the guest.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -3), (guest, 3)): + x, y, z = hx + 3, hy, hz + dz + game('command', command=f'fill {x - 1} {y} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') + game('command', command=f'summon minecraft:item {x + 0.5} {y} {z + 0.5} ' + '{Item:{id:"minecraft:diamond",count:1},PickupDelay:32767}') + game.wait(20) + game('command', command=f'setblock {x} {y} {z} minecraft:stone') + game.wait(60) + for viewer in (host, guest): + near = [e['pos'] for e in viewer.raw('entities', 24, 'minecraft:item')['entities'] + if abs(e['pos'][0] - x - 0.5) < 2 and abs(e['pos'][2] - z - 0.5) < 2] + seen[f'{game.name} places, {viewer.name} sees'] = ([x, y, z], near) + game.shot(out, 'drops') + host('command', command='kill @e[type=minecraft:item]') + host('command', command=f'setblock {x} {y} {z} minecraft:air') + for name, (block, near) in seen.items(): + inside = [p for p in near if all(block[i] <= p[i] < block[i] + 1 for i in range(3))] + assert near and not inside, f'{name}: items {near} in block {block} (all: {seen})' + return seen + + +def check_underwater(host, guest, out): + """Digging dirt by hand underwater, standing on the bottom of a pool: five times slower than in + the air (SUBMERGED_MINING_SPEED), on the player's own client as on the server. Halfway through + the client is about halfway (it doesn't break the block early, which the server would put + back), and the block breaks (#1254). The dirt is at eye height, the player's head under water. + The host, then the guest.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, dz in ((host, -4), (guest, 4)): + x, y, z = hx + 3, hy, hz + dz + game('command', command='gamemode survival') + game('command', command='item replace entity @s weapon.mainhand with minecraft:air') + game('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:stone') + game('command', command=f'fill {x} {y} {z} {x} {y + 2} {z} minecraft:water') + game('command', command=f'setblock {x + 1} {y + 1} {z} minecraft:dirt') + game('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + game.wait(40) + game.raw('look-at', f'{x + 1.5:.2f}', f'{y + 1.5:.2f}', f'{z + 0.5:.2f}') + game.wait(5) + game.raw('mouse', 'left', 'down') + # Dirt by hand: 15 ticks in the air, 75 under water. + game.wait(35) + halfway = {'mining': game('state').get('mining'), 'client': game.raw('block', x + 1, y + 1, z).get('block'), + 'server': host.raw('block', x + 1, y + 1, z).get('block'), 'y': y + 1} + game.wait(70) + game.raw('mouse', 'left', 'up') + game.wait(10) + done = host.raw('block', x + 1, y + 1, z).get('block') + game.shot(out, 'underwater') + seen[game.name] = {'halfway': halfway, 'done': done} + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 2} {y - 1} {z + 1} minecraft:stone') + for name, s in seen.items(): + h = s['halfway'] + assert h['client'] == 'minecraft:dirt' == h['server'], f'{name} broke it early: {seen}' + assert h['mining'] and h['mining']['pos'][1] == h['y'] and 0.3 < h['mining']['progress'] < 0.7, f'{name} digs at the wrong speed: {seen}' + # Broken: air, or the pool's water flowing in. + assert s['done'] in ('minecraft:air', 'minecraft:water'), f'{name} never broke it: {seen}' + return seen + + def check_ladder(host, guest, out): """#1255: climbing down a ladder doesn't hurt where the guest lands.""" x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -3075,7 +3147,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts} + 'time': check_time, 'growth': check_growth, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, '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, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'drops': check_drops, 'underwater': check_underwater} def run(ctl, out, resources, checks): From feeefb3a33db6cc33c0798f535d9bdc0e7aeb306 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 05:38:46 +0200 Subject: [PATCH 08/12] Mobs: a punch shows smooth and slow, as on vanilla's client The server sends a knocked-back, pushed or jumping mob's move at once (Entity.needsSync), and the remote client walks every living entity along the server's positions with vanilla's SteppedInterpolationHandler: each position takes the type's update interval to reach, sped up while steps pile up. Before, the client waited for the next due update and then lerped there in fewer ticks, so a hit pig jumped away fast. tools/test_stepped_interpolation_parity.py drives vanilla's unmodified InterpolationData and the Rust port with the same packets and ticks (random cases and a punched pig's knockback); 135236 positions and rotations match bit for bit. Fixes #1374 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 1 + crates/horizon-client/src/game/lan.rs | 5 + .../horizon-client/src/game/lan_entities.rs | 1 + crates/horizon-client/src/game/remote.rs | 144 ++++++-- crates/horizon-client/src/lan/entity.rs | 39 +- crates/horizon-client/src/lan/hub.rs | 1 + crates/horizon-client/src/mobs.rs | 7 + crates/horizon-client/src/mobs/living.rs | 3 + crates/horizon-client/tests/lan_bot.rs | 1 + .../examples/stepped_interpolation_fixture.rs | 93 +++++ crates/horizon-world/src/lib.rs | 1 + .../src/stepped_interpolation.rs | 341 ++++++++++++++++++ .../VanillaSteppedInterpolationOracle.java | 148 ++++++++ tools/test_stepped_interpolation_parity.py | 103 ++++++ 14 files changed, 858 insertions(+), 30 deletions(-) create mode 100644 crates/horizon-world/examples/stepped_interpolation_fixture.rs create mode 100644 crates/horizon-world/src/stepped_interpolation.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java create mode 100644 tools/test_stepped_interpolation_parity.py diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 222e59229..6dd02893d 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2700,6 +2700,7 @@ impl Game<'_> { equipment: Vec::new(), attributes: Vec::new(), precise: false, + needs_sync: false, }) } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4e05ea600..e2c218a34 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -760,6 +760,7 @@ impl Game<'_> { (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; + e.needs_sync = m.needs_sync; mob_meta(m, hub, &mut e.meta); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); @@ -828,6 +829,10 @@ impl Game<'_> { } else { states.clear(); } + // ServerEntity.sendChanges clears needsSync once it has looked. + for m in &mut self.mobs { + m.needs_sync = false; + } let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 5f46f7c21..631498edd 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -39,6 +39,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> equipment: Vec::new(), attributes: Vec::new(), precise: false, + needs_sync: false, } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5461a4cd0..454773e38 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -40,7 +40,11 @@ use horizon_protocol::{ registry::{Builtin, DimensionType, Dynamic, ceil_log2}, text::{Language, format_java, plain}, }; -use horizon_world::{nbt::Tag, registry::BlockStateId}; +use horizon_world::{ + nbt::Tag, + registry::BlockStateId, + stepped_interpolation::{Path, PosRot, Start, SteppedInterpolation}, +}; use std::{ collections::{HashMap, VecDeque}, sync::Arc, @@ -85,6 +89,15 @@ struct Lerp { steps: u32, } +/// `SteppedInterpolationHandler.doInterpolate`'s `setPos` and `setRot` on a +/// mob: its yaw kept continuous (the same turn as vanilla's, without the +/// wrap that would spin it in the frame between ticks), its pitch clamped. +fn place_interpolated(m: &mut Mob, at: PosRot) { + m.position = Vec3::new(at.position[0], at.position[1], at.position[2]); + m.yaw += wrap_degrees(at.yaw - m.yaw); + m.head_pitch = (at.pitch % 360.0).clamp(-90.0, 90.0); +} + pub(super) struct Remote { pub session: Session, pub brand: String, @@ -123,6 +136,8 @@ pub(super) struct Remote { use_target: Option<[i32; 3]>, entities: HashMap, lerps: HashMap, + /// Living entities' `SteppedInterpolationHandler`s. + stepped: HashMap, /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. head_lerps: HashMap, /// Item entities waiting for their item data. @@ -380,6 +395,7 @@ impl Game<'_> { use_target: None, entities: HashMap::new(), lerps: HashMap::new(), + stepped: HashMap::new(), head_lerps: HashMap::new(), pending_items: HashMap::new(), health: (20.0, 20, 5.0), @@ -931,6 +947,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); + r.stepped.clear(); r.head_lerps.clear(); r.pending_items.clear(); // A new ClientLevel: a new chunk storage, centred on 0, 0. @@ -1322,6 +1339,9 @@ impl Game<'_> { mob.persistent = true; self.mobs.retain(|m| m.id != id as u32); self.mobs.push(mob); + if let Some(r) = self.remote.as_mut() { + r.stepped.remove(&id); + } } if let Some(r) = self.remote.as_mut() { if kind == "minecraft:item" { @@ -1336,23 +1356,77 @@ impl Game<'_> { ); } } + /// A move packet for entity `id`: to the end of `path` (None: a + /// rotation alone), turned to `rotation` if it has one. `far_snaps`: + /// an `EntityPositionSync`, which puts an entity more than 64 blocks + /// away there at once. fn move_entity( &mut self, id: i32, - position: [f64; 3], + path: Option, rotation: Option<(f32, f32)>, on_ground: bool, + far_snaps: bool, ) { let mob = self.mobs.iter_mut().find(|m| m.id == id as u32); + let tracked = self + .remote + .as_ref() + .and_then(|r| r.entities.get(&id)) + .map(|t| t.position); + let position = path + .as_ref() + .map(Path::end) + .or(tracked) + .or_else(|| { + mob.as_ref() + .map(|m| [m.position.x, m.position.y, m.position.z]) + }) + .unwrap_or([0.0; 3]); if let Some(r) = self.remote.as_mut() { if let Some(t) = r.entities.get_mut(&id) { t.position = position; } + if let Some(m) = mob { + // A living entity: LivingEntity.createInterpolationHandler's + // SteppedInterpolationHandler, over its type's update interval. + let entity = PosRot { + position: [m.position.x, m.position.y, m.position.z], + yaw: m.yaw, + pitch: m.head_pitch, + }; + let far = far_snaps && { + let d = [0, 1, 2].map(|i| position[i] - entity.position[i]); + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 4096.0 + }; + let handler = r.stepped.entry(id).or_insert_with(|| { + let interval = horizon_client::lan::tracking::settings(&m.kind.id).1; + SteppedInterpolation::new(interval as i32) + }); + let snap = if far { + handler.cancel(); + let (yaw, pitch) = rotation.unwrap_or((m.yaw, m.head_pitch)); + Some(PosRot { + position, + yaw, + pitch, + }) + } else { + match handler.interpolate_to(entity, path, rotation) { + Start::Snap(at) => Some(at), + Start::Interpolating | Start::Unchanged => None, + } + }; + if let Some(at) = snap { + place_interpolated(m, at); + m.previous = m.position; + } + m.on_ground = on_ground; + return; + } // AbstractInterpolationHandler.interpolateTo: without a rotation, - // the one it was heading for (or has). - let rotation = rotation - .or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)) - .or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch))); + // the one it was heading for. + let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)); r.lerps.insert( id, Lerp { @@ -1365,9 +1439,6 @@ impl Game<'_> { *p = position; } } - if let Some(m) = mob { - m.on_ground = on_ground; - } self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); self.turn_remote_projectile(id, rotation); } @@ -1384,6 +1455,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); + r.stepped.remove(&id); r.head_lerps.remove(&id); r.pending_items.remove(&id); } @@ -1743,17 +1815,36 @@ impl Game<'_> { .and_then(|r| r.entities.get(&m.id)) .map(|t| t.position); let Some(base) = base else { return Ok(()) }; - let position = m.delta.as_ref().map_or(base, |d| d.end(base)); + // VecDeltaCodec.decode: each step's position from the last. + let path = m.delta.as_ref().map(|d| match d { + play::VecDelta::Linear(_) => Path::Linear(d.end(base)), + play::VecDelta::Stepped(steps) => { + let mut at = base; + Path::Stepped( + steps + .iter() + .map(|(delta, ticks)| { + at = play::VecDelta::apply(at, *delta); + (at, *ticks) + }) + .collect(), + ) + } + }); let rotation = m.rotation.map(|(y, x)| { ( horizon_protocol::buf::unpack_degrees(y), horizon_protocol::buf::unpack_degrees(x), ) }); - self.move_entity(m.id, position, rotation, m.on_ground); + self.move_entity(m.id, path, rotation, m.on_ground, false); } C::EntityPositionSync(p) => { - self.move_entity(p.id, p.path.end(), Some((p.yaw, p.pitch)), p.on_ground) + let path = match p.path { + play::PositionPath::Linear(at) => Path::Linear(at), + play::PositionPath::Stepped(steps) => Path::Stepped(steps), + }; + self.move_entity(p.id, Some(path), Some((p.yaw, p.pitch)), p.on_ground, true) } C::TeleportEntity(p) => { let base = self @@ -1773,7 +1864,13 @@ impl Game<'_> { rel(play::relative::Y, 1), rel(play::relative::Z, 2), ]; - self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); + self.move_entity( + p.id, + Some(Path::Linear(position)), + Some((p.yaw, p.pitch)), + p.on_ground, + false, + ); } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw), @@ -3149,6 +3246,7 @@ impl Game<'_> { return; }; let mut lerps = std::mem::take(&mut r.lerps); + let stepped = &mut r.stepped; let head_lerps = &mut r.head_lerps; let players = &r.level_players; let mut using = Vec::new(); @@ -3179,22 +3277,12 @@ impl Game<'_> { // LivingEntity.updateSwingTime. m.anim.attack_anim_o = m.anim.attack_anim; horizon_client::mobs::ai::tick_swing(m); - // Entity.commonTick: LinearInterpolationHandler.interpolate. - if let Some(l) = lerps.get_mut(&(m.id as i32)) - && l.steps > 0 + // Entity.tick: the SteppedInterpolationHandler's step. + if let Some(at) = stepped + .get_mut(&(m.id as i32)) + .and_then(|h| h.interpolate()) { - let n = f64::from(l.steps); - m.position = Vec3::new( - m.position.x + (l.target[0] - m.position.x) / n, - m.position.y + (l.target[1] - m.position.y) / n, - m.position.z + (l.target[2] - m.position.z) / n, - ); - if let Some((yaw, pitch)) = l.rotation { - let alpha = 1.0 / l.steps as f32; - m.yaw += wrap_degrees(yaw - m.yaw) * alpha; - m.head_pitch += (pitch - m.head_pitch) * alpha; - } - l.steps -= 1; + place_interpolated(m, at); } // LivingEntity.aiStep: the head's own interpolation. if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32)) diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index c4e8052c0..86fea8b65 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -59,6 +59,8 @@ pub struct EntityState { /// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks /// touching a block): moves are sent as full position syncs. pub precise: bool, + /// `Entity.needsSync`: send its changes this tick, due or not. + pub needs_sync: bool, } impl EntityState { @@ -79,6 +81,7 @@ impl EntityState { self.equipment.clear(); self.attributes.clear(); self.precise = false; + self.needs_sync = false; } } @@ -322,7 +325,7 @@ impl ServerEntity { // SynchedEntityData.isDirty: once for every client. let dirty = e.meta != self.meta; let due = self.interval != 0 && self.tick.is_multiple_of(self.interval); - if due || dirty { + if due || dirty || e.needs_sync { let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1; let rotate = self.arrow @@ -398,7 +401,7 @@ impl ServerEntity { } else { None }; - if self.track_deltas { + if self.track_deltas || e.needs_sync { let diff: f64 = (0..3) .map(|k| (e.velocity[k] - self.velocity[k]).powi(2)) .sum(); @@ -855,6 +858,7 @@ mod tests { equipment: Vec::new(), attributes: Vec::new(), precise: false, + needs_sync: false, } } @@ -918,6 +922,37 @@ mod tests { assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_))); } + #[test] + fn a_knocked_back_mob_is_sent_at_once() { + let mut s = added(&state(0.0)); + changes(&mut s, &state(0.0)); + // Not due (tick 1 of 3), but LivingEntity.knockback set needsSync: + // its move and its new motion go out now. + let mut knocked = state(0.3); + knocked.velocity = [0.2, 0.3, 0.0]; + knocked.needs_sync = true; + let out = changes(&mut s, &knocked); + assert!( + matches!( + out[..], + [ + play::Clientbound::SetEntityMotion(_), + play::Clientbound::MoveEntityPos(_) + ] + ), + "{out:?}" + ); + // Then every third tick again. + assert!(changes(&mut s, &state(0.5)).is_empty()); + assert!(matches!( + changes(&mut s, &state(0.6))[..], + [ + play::Clientbound::SetEntityMotion(_), + play::Clientbound::MoveEntityPos(_) + ] + )); + } + #[test] fn fireballs_bundle_their_motion_with_their_power() { let mut e = state(0.0); diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index bf66f979b..060ec7193 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1547,6 +1547,7 @@ impl Hub { equipment, attributes, precise: false, + needs_sync: false, } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index db2ebeb60..76f622d9c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -792,6 +792,9 @@ pub struct Mob { pub on_ground: bool, pub horizontal_collision: bool, pub vertical_collision_below: bool, + /// `Entity.needsSync`: knocked back, pushed or jumped since its server + /// last sent it, so the next update goes out at once. + pub needs_sync: bool, pub health: f32, pub hurt_time: i32, pub invulnerable: i32, @@ -1361,8 +1364,10 @@ impl PendingPushes { } /// Adds the pending pushes aimed at `m` to its velocity, in push order. pub fn apply_mob_pushes(m: &mut Mob, pending: &mut PendingPushes) { + // Entity.push(x, y, z) sets needsSync. let mut add = |v: Vec3| { m.velocity = Vec3::new(m.velocity.x + v.x, m.velocity.y + v.y, m.velocity.z + v.z); + m.needs_sync = true; }; if !pending.list.is_empty() { pending.list.retain(|(id, v)| { @@ -1529,6 +1534,7 @@ impl Mob { on_ground: false, horizontal_collision: false, vertical_collision_below: false, + needs_sync: false, hurt_time: 0, invulnerable: 0, death_time: 0, @@ -1769,6 +1775,7 @@ impl Mob { if power <= 0.0 { return; } + self.needs_sync = true; while xd * xd + zd * zd < f64::from(1.0e-5_f32) { xd = (self.random.next_double() - self.random.next_double()) * 0.01; zd = (self.random.next_double() - self.random.next_double()) * 0.01; diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index ebbfabf6b..d5b3c7091 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -832,6 +832,9 @@ impl Mob { }; } pub fn jump_from_ground(&mut self, w: &MobWorld) { + // LivingEntity.jumpFromGround (and the rabbit's and cubes' own, + // which call it or do the same): needsSync. + self.needs_sync = true; if self.species() == super::Species::Rabbit { super::rabbit::jump(self, w); return; diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index bd22d6e0a..4f5f17a3b 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -433,6 +433,7 @@ fn guests_see_each_other_and_the_world_entities() { equipment: Vec::new(), attributes: Vec::new(), precise: false, + needs_sync: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-world/examples/stepped_interpolation_fixture.rs b/crates/horizon-world/examples/stepped_interpolation_fixture.rs new file mode 100644 index 000000000..d2228d8b5 --- /dev/null +++ b/crates/horizon-world/examples/stepped_interpolation_fixture.rs @@ -0,0 +1,93 @@ +//! The Rust side of tools/test_stepped_interpolation_parity.py: replays the +//! harness's events (VanillaSteppedInterpolationOracle's input format) on +//! `SteppedInterpolation` and writes the entity after each one. +use horizon_world::stepped_interpolation::{Path, PosRot, Start, SteppedInterpolation}; +use std::fmt::Write as _; + +/// `Entity.setRot`: yaw and pitch wrapped, pitch clamped (`setXRot`). +fn set_rot(entity: &mut PosRot, yaw: f32, pitch: f32) { + entity.yaw = yaw % 360.0; + entity.pitch = (pitch % 360.0 % 360.0).clamp(-90.0, 90.0); +} + +fn main() { + let args: Vec = std::env::args().collect(); + let input = std::fs::read_to_string(&args[1]).expect("input"); + let mut out = String::new(); + let mut handler = SteppedInterpolation::new(0); + let mut entity = PosRot::default(); + for line in input.lines() { + let f: Vec<&str> = line.split_whitespace().collect(); + let num = |i: usize| f[i].parse::().expect("number"); + let what = match f[0] { + "case" => { + handler = SteppedInterpolation::new(f[1].parse().expect("steps")); + entity = PosRot { + position: [num(2), num(3), num(4)], + yaw: f[5].parse().expect("yaw"), + pitch: f[6].parse().expect("pitch"), + }; + "c" + } + "move" => { + let mut i = 2; + let path = match f[1] { + "L" => { + i += 3; + Some(Path::Linear([num(2), num(3), num(4)])) + } + "S" => { + let n: usize = f[2].parse().expect("count"); + i = 3; + let mut steps = Vec::new(); + for _ in 0..n { + steps.push(( + [num(i), num(i + 1), num(i + 2)], + f[i + 3].parse().expect("ticks"), + )); + i += 4; + } + Some(Path::Stepped(steps)) + } + _ => None, + }; + let rotation = (f[i] == "R").then(|| { + ( + f[i + 1].parse().expect("yaw"), + f[i + 2].parse().expect("pitch"), + ) + }); + match handler.interpolate_to(entity, path, rotation) { + Start::Snap(at) => { + entity.position = at.position; + set_rot(&mut entity, at.yaw, at.pitch); + "s" + } + Start::Unchanged => "k", + Start::Interpolating => "i", + } + } + "tick" => match handler.interpolate() { + Some(at) => { + entity.position = at.position; + set_rot(&mut entity, at.yaw, at.pitch); + "t" + } + None => "n", + }, + other => panic!("unknown event {other}"), + }; + let p = entity.position; + writeln!( + out, + "{what} {:x} {:x} {:x} {:x} {:x}", + p[0].to_bits(), + p[1].to_bits(), + p[2].to_bits(), + entity.yaw.to_bits(), + entity.pitch.to_bits() + ) + .expect("write"); + } + std::fs::write(&args[2], out).expect("output"); +} diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index 819262d46..b6d05ecf6 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -137,6 +137,7 @@ pub mod player_equipment; pub mod living_use_flags; pub mod status_effect; +pub mod stepped_interpolation; pub mod synced_values; pub mod inventory_use; diff --git a/crates/horizon-world/src/stepped_interpolation.rs b/crates/horizon-world/src/stepped_interpolation.rs new file mode 100644 index 000000000..a7157d90a --- /dev/null +++ b/crates/horizon-world/src/stepped_interpolation.rs @@ -0,0 +1,341 @@ +//! How a client moves a living entity it doesn't simulate along the +//! positions its server sends (vanilla `SteppedInterpolationHandler`, which +//! `LivingEntity.createInterpolationHandler` gives every living entity on a +//! client): each position is a step the entity walks to in the type's update +//! interval (3 ticks for most mobs), one after the other, sped up while +//! steps pile up. A punched mob's first move, sent at once (`needsSync`), +//! thus takes three ticks to show, and the rest follow it. + +use std::collections::VecDeque; + +/// A position and rotation (`PositionAndRotation`). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct PosRot { + pub position: [f64; 3], + pub yaw: f32, + pub pitch: f32, +} + +impl PosRot { + /// `PositionAndRotation.is`: the same rotation and `Vec3.equals` + /// position (`Double.compare`, so -0.0 is not 0.0). + fn is(&self, position: [f64; 3], yaw: f32, pitch: f32) -> bool { + self.yaw == yaw && self.pitch == pitch && same_position(self.position, position) + } +} + +/// `Vec3.equals`. +fn same_position(a: [f64; 3], b: [f64; 3]) -> bool { + (0..3).all(|i| a[i].to_bits() == b[i].to_bits()) +} + +/// `PositionPath`: where a move packet puts an entity, either straight +/// there or through the positions the server stepped it through, each +/// with the ticks it took. +#[derive(Clone, Debug, PartialEq)] +pub enum Path { + Linear([f64; 3]), + Stepped(Vec<([f64; 3], i32)>), +} + +impl Path { + pub fn end(&self) -> [f64; 3] { + match self { + Path::Linear(p) => *p, + Path::Stepped(steps) => steps.last().map_or([0.0; 3], |s| s.0), + } + } +} + +/// What the client does with the entity when a packet arrives. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Start { + /// Moves on to it over the coming ticks. + Interpolating, + /// Already headed there: nothing changes. + Unchanged, + /// Is put there at once (`snapTo`): types with no update interval. + Snap(PosRot), +} + +/// `SteppedInterpolationHandler` and its `InterpolationData`. +#[derive(Clone, Debug)] +pub struct SteppedInterpolation { + /// `AbstractInterpolationHandler.interpolationSteps`: the type's + /// `updateInterval`. + steps: i32, + /// The data's own position and rotation: where the last packet said. + target: PosRot, + /// `lastStepPosRot`: where the step being walked started. + last: PosRot, + remaining: VecDeque<(PosRot, i32)>, + current_step_ticks: f32, + remaining_ticks: f32, + speed: f32, +} + +/// `Mth.wrapDegrees(float)`. +fn wrap_degrees(degrees: f32) -> f32 { + let mut wrapped = degrees % 360.0; + if wrapped >= 180.0 { + wrapped -= 360.0; + } + if wrapped < -180.0 { + wrapped += 360.0; + } + wrapped +} + +/// `Mth.lerp(float, float, float)`. +fn lerp(a: f32, from: f32, to: f32) -> f32 { + from + a * (to - from) +} + +/// `Mth.rotLerp`. +fn rot_lerp(a: f32, from: f32, to: f32) -> f32 { + from + a * wrap_degrees(to - from) +} + +impl SteppedInterpolation { + /// The handler of an entity type whose update interval is `steps` ticks. + pub fn new(steps: i32) -> Self { + Self { + steps, + target: PosRot::default(), + last: PosRot::default(), + remaining: VecDeque::new(), + current_step_ticks: 0.0, + remaining_ticks: 0.0, + speed: 1.0, + } + } + /// `hasActiveInterpolation`. + pub fn active(&self) -> bool { + !self.remaining.is_empty() + } + /// Where the entity is headed: the last packet's position and rotation + /// while interpolating (`AbstractInterpolationHandler.interpolateTo`'s + /// `current`), else where it is. + pub fn heading(&self, entity: PosRot) -> PosRot { + if self.active() { self.target } else { entity } + } + /// `AbstractInterpolationHandler.interpolateTo(path, yRot, xRot, + /// hasRotation)` for an entity at `entity`: a packet without a position + /// (`path` None) keeps the one it is headed for, one without a rotation + /// the rotation. + pub fn interpolate_to( + &mut self, + entity: PosRot, + path: Option, + rotation: Option<(f32, f32)>, + ) -> Start { + let current = self.heading(entity); + let path = path.unwrap_or(Path::Linear(current.position)); + let (yaw, pitch) = rotation.unwrap_or((current.yaw, current.pitch)); + let end = path.end(); + if self.steps == 0 { + self.cancel(); + return Start::Snap(PosRot { + position: end, + yaw, + pitch, + }); + } + if self.active() && self.target.is(end, yaw, pitch) { + return Start::Unchanged; + } + // SteppedInterpolationHandler.startInterpolating. + if !self.active() { + self.last = entity; + self.current_step_ticks = 1.0; + } + if same_position(end, self.target.position) { + self.add_step( + PosRot { + position: end, + yaw, + pitch, + }, + self.steps, + ); + } else { + self.add_steps(&path, yaw, pitch); + } + self.target = PosRot { + position: end, + yaw, + pitch, + }; + Start::Interpolating + } + /// `cancel` (`InterpolationData.reset`). + pub fn cancel(&mut self) { + self.remaining.clear(); + self.remaining_ticks = 0.0; + self.speed = 1.0; + } + /// `AbstractInterpolationHandler.interpolate`, once a client tick: where + /// the entity is put, or None when there is nothing to walk (and the + /// handler resets). The client moves the entity only this way, so the + /// target never needs the deltas `adjustInterpolationTargetFromDeltas` + /// would add. + pub fn interpolate(&mut self) -> Option { + if !self.active() { + self.cancel(); + return None; + } + // doInterpolate: getNewPositionAndRotation, then advance by the + // level's relative tick speed (1 at the normal tick rate). + let at = self.new_position(); + self.advance(1.0); + Some(at) + } + /// `InterpolationData.addStep`. + fn add_step(&mut self, step: PosRot, ticks: i32) { + self.remaining.push_back((step, ticks)); + self.remaining_ticks += ticks as f32; + } + /// `InterpolationData.addSteps`: a stepped path's steps take their own + /// ticks, turning by the share of the path each one ends. + fn add_steps(&mut self, path: &Path, yaw: f32, pitch: f32) { + match path { + Path::Linear(p) => self.add_step( + PosRot { + position: *p, + yaw, + pitch, + }, + self.steps, + ), + Path::Stepped(steps) => { + if yaw == self.target.yaw && pitch == self.target.pitch { + for (p, ticks) in steps { + self.add_step( + PosRot { + position: *p, + yaw, + pitch, + }, + *ticks, + ); + } + return; + } + let total: i32 = steps.iter().map(|s| s.1).sum(); + let mut offset = 0; + let (from_yaw, from_pitch) = (self.target.yaw, self.target.pitch); + for (p, ticks) in steps { + offset += ticks; + let a = offset as f32 / total as f32; + let step = PosRot { + position: *p, + yaw: rot_lerp(a, from_yaw, yaw), + pitch: lerp(a, from_pitch, pitch), + }; + self.add_step(step, *ticks); + } + } + } + } + /// `InterpolationData.getNewPositionAndRotation`. + fn new_position(&mut self) -> PosRot { + while let Some(&(step, ticks)) = self.remaining.front() { + if self.current_step_ticks < ticks as f32 { + let a = self.current_step_ticks / ticks as f32; + let t = f64::from(a); + let (from, to) = (self.last.position, step.position); + return PosRot { + position: [0, 1, 2].map(|i| from[i] + (to[i] - from[i]) * t), + yaw: rot_lerp(a, self.last.yaw, step.yaw), + pitch: lerp(a, self.last.pitch, step.pitch), + }; + } + self.current_step_ticks -= ticks as f32; + self.last = step; + self.remaining.pop_front(); + } + self.target + } + /// `InterpolationData.advance`: faster while more than one update's + /// worth of steps waits. + fn advance(&mut self, ticks: f32) { + let steps = self.steps as f32; + let target_speed = (self.remaining_ticks / steps).max(1.0); + self.speed = lerp(1.0 / steps, self.speed, target_speed); + let moved = if ticks * self.speed < self.remaining_ticks { + ticks * self.speed + } else { + self.speed = 1.0; + self.remaining_ticks + }; + self.current_step_ticks += moved; + self.remaining_ticks -= moved; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(x: f64) -> PosRot { + PosRot { + position: [x, 0.0, 0.0], + yaw: 0.0, + pitch: 0.0, + } + } + + #[test] + fn a_position_takes_the_update_interval_to_reach() { + let mut h = SteppedInterpolation::new(3); + let mut entity = at(0.0); + h.interpolate_to(entity, Some(Path::Linear([0.3, 0.0, 0.0])), None); + let mut seen = Vec::new(); + while let Some(p) = h.interpolate() { + entity = p; + seen.push((p.position[0] * 1000.0).round() / 1000.0); + } + assert_eq!(seen, [0.1, 0.2, 0.3]); + assert!(!h.active()); + assert_eq!(entity.position[0], 0.3); + } + + #[test] + fn steps_that_pile_up_are_walked_faster() { + let mut h = SteppedInterpolation::new(3); + let mut entity = at(0.0); + let mut ticks = 0; + for k in 1..=4 { + h.interpolate_to(entity, Some(Path::Linear([f64::from(k), 0.0, 0.0])), None); + if let Some(p) = h.interpolate() { + entity = p; + } + ticks += 1; + } + while let Some(p) = h.interpolate() { + entity = p; + ticks += 1; + } + // Four packets a tick apart: 12 ticks of steps, walked in fewer. + assert!(ticks < 12, "{ticks}"); + assert_eq!(entity.position[0], 4.0); + } + + #[test] + fn no_update_interval_snaps() { + let mut h = SteppedInterpolation::new(0); + let start = h.interpolate_to( + at(0.0), + Some(Path::Linear([2.0, 0.0, 0.0])), + Some((90.0, 0.0)), + ); + assert_eq!( + start, + Start::Snap(PosRot { + position: [2.0, 0.0, 0.0], + yaw: 90.0, + pitch: 0.0 + }) + ); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java new file mode 100644 index 000000000..b3edd6e48 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java @@ -0,0 +1,148 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import net.minecraft.core.PositionAndRotation; +import net.minecraft.world.entity.PositionPath; +import net.minecraft.world.entity.PositionStep; +import net.minecraft.world.phys.Vec3; + +/** + * How a client walks a living entity along the positions its server sends: the unmodified + * {@code SteppedInterpolationHandler.InterpolationData} (setStartingPoint, addStep, addSteps, + * getNewPositionAndRotation, advance, reset), driven the way + * {@code AbstractInterpolationHandler.interpolateTo} / {@code interpolate} and + * {@code SteppedInterpolationHandler.startInterpolating} / {@code doInterpolate} drive it, with the + * entity's own {@code setPos} / {@code setRot}. The handler's entity hooks are out of scope: the + * entity moves only by its interpolation (no deltas to adjust) at the normal tick rate. + * + *

Input (args[0]), one event a line: {@code case STEPS X Y Z YAW PITCH} (a fresh entity there + * with a handler of that many interpolation steps), {@code move L X Y Z} or {@code move S N + * (X Y Z TICKS)xN} or {@code move N} (no position), then {@code R YAW PITCH} or {@code -} (no + * rotation), and {@code tick}. Output (args[1]): the entity after every event. + */ +public final class VanillaSteppedInterpolationOracle { + private static Method method(Class owner, String name, Class... types) throws Exception { + Method m = owner.getDeclaredMethod(name, types); + m.setAccessible(true); + return m; + } + + private static String hex(double v) { + return Long.toHexString(Double.doubleToRawLongBits(v)); + } + + private static String hex(float v) { + return Integer.toHexString(Float.floatToRawIntBits(v)); + } + + public static void main(String[] args) throws Exception { + Class dataClass = Class.forName("net.minecraft.world.entity.SteppedInterpolationHandler$InterpolationData"); + Constructor create = dataClass.getDeclaredConstructor(); + create.setAccessible(true); + Method advance = method(dataClass, "advance", float.class, int.class); + Method addStep = method(dataClass, "addStep", Vec3.class, float.class, float.class, int.class); + Method addSteps = method(dataClass, "addSteps", PositionPath.class, float.class, float.class, int.class); + Method setStartingPoint = method(dataClass, "setStartingPoint", Vec3.class, float.class, float.class); + Method next = method(dataClass, "getNewPositionAndRotation"); + Method reset = method(dataClass, "reset"); + Field remaining = dataClass.getDeclaredField("remainingSteps"); + remaining.setAccessible(true); + + Object data = null; + int steps = 0; + Vec3 pos = Vec3.ZERO; + float yRot = 0; + float xRot = 0; + try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])))) { + for (String line : Files.readAllLines(Path.of(args[0]))) { + String[] f = line.trim().split(" "); + int i = 1; + String what; + switch (f[0]) { + case "case" -> { + data = create.newInstance(); + steps = Integer.parseInt(f[1]); + pos = new Vec3(Double.parseDouble(f[2]), Double.parseDouble(f[3]), Double.parseDouble(f[4])); + yRot = Float.parseFloat(f[5]); + xRot = Float.parseFloat(f[6]); + what = "c"; + } + case "move" -> { + PositionPath path = null; + switch (f[i++]) { + case "L" -> { + path = PositionPath.of(new Vec3(Double.parseDouble(f[i]), Double.parseDouble(f[i + 1]), Double.parseDouble(f[i + 2]))); + i += 3; + } + case "S" -> { + int n = Integer.parseInt(f[i++]); + List list = new ArrayList<>(); + for (int k = 0; k < n; k++) { + list.add(new PositionStep(new Vec3(Double.parseDouble(f[i]), Double.parseDouble(f[i + 1]), Double.parseDouble(f[i + 2])), Integer.parseInt(f[i + 3]))); + i += 4; + } + path = PositionPath.stepped(List.copyOf(list)); + } + default -> { + } + } + boolean hasRotation = f[i].equals("R"); + float y = hasRotation ? Float.parseFloat(f[i + 1]) : 0; + float x = hasRotation ? Float.parseFloat(f[i + 2]) : 0; + boolean active = !((List) remaining.get(data)).isEmpty(); + PositionAndRotation.Mutable target = (PositionAndRotation.Mutable) data; + // AbstractInterpolationHandler.interpolateTo(path, yRot, xRot, hasRotation). + PositionAndRotation current = active ? target : PositionAndRotation.of(pos, yRot, xRot); + if (path == null) path = PositionPath.of(current.position()); + if (!hasRotation) { + y = current.yRot(); + x = current.xRot(); + } + Vec3 end = path.endPosition(); + if (steps == 0) { + // snapTo, then cancel. + pos = end; + yRot = y % 360.0F; + xRot = Math.clamp(x % 360.0F % 360.0F, -90.0F, 90.0F); + reset.invoke(data); + what = "s"; + } else if (active && target.is(end, y, x)) { + what = "k"; + } else { + // SteppedInterpolationHandler.startInterpolating. + if (!active) setStartingPoint.invoke(data, pos, yRot, xRot); + if (Objects.equals(end, target.position())) addStep.invoke(data, end, y, x, steps); + else addSteps.invoke(data, path, y, x, steps); + target.set(end, y, x); + what = "i"; + } + } + case "tick" -> { + // AbstractInterpolationHandler.interpolate. + if (((List) remaining.get(data)).isEmpty()) { + reset.invoke(data); + what = "n"; + } else { + PositionAndRotation t = (PositionAndRotation) next.invoke(data); + pos = t.position(); + yRot = t.yRot() % 360.0F; + xRot = Math.clamp(t.xRot() % 360.0F % 360.0F, -90.0F, 90.0F); + advance.invoke(data, 1.0F, steps); + what = "t"; + } + } + default -> throw new IllegalArgumentException(line); + } + out.println(what + " " + hex(pos.x) + " " + hex(pos.y) + " " + hex(pos.z) + " " + hex(yRot) + " " + hex(xRot)); + } + } + } +} diff --git a/tools/test_stepped_interpolation_parity.py b/tools/test_stepped_interpolation_parity.py new file mode 100644 index 000000000..998d5a4ba --- /dev/null +++ b/tools/test_stepped_interpolation_parity.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +"""Compare how a client walks a living entity along its server's positions with vanilla. + +Vanilla's unmodified SteppedInterpolationHandler.InterpolationData (VanillaSteppedInterpolationOracle +drives it as the handler does) and horizon-world's SteppedInterpolation replay the same packets and +client ticks: move packets with and without a position or rotation, straight or stepped paths, +repeats of the one the entity is headed for, packets a tick apart that pile up and others after it +stopped, for update intervals of 1 to 3 ticks, plus a punched pig's knockback as the server sends it +(its first move at once, `needsSync`, then every update interval). The entity's position and rotation +after every event must match bit for bit. The handler's entity hooks (deltas, passengers) are out of +scope. +""" +import os +import random +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + +# A pig punched on flat ground, its positions on the server tick by tick (knockback 0.4 along x). +KNOCKBACK = [(0.0, 0.0), (0.3032, 0.3608), (0.4638, 0.636), (0.6049, 0.8273), (0.7279, 0.9363), (0.8345, 0.9648), + (0.926, 0.9143), (1.0037, 0.7864), (1.0688, 0.5827), (1.1223, 0.3046), (1.1654, 0.0), (1.1147, 0.0), + (0.9968, 0.0), (0.8418, 0.0), (0.6664, 0.0)] + + +def position(rng, p): + return [round(v + rng.uniform(-0.6, 0.6), rng.choice([2, 4, 17])) for v in p] + + +def rotation(rng): + return [round(rng.uniform(-400, 400), rng.choice([0, 1, 3])), round(rng.uniform(-120, 120), rng.choice([0, 2]))] + + +def cases(count, seed): + rng = random.Random(seed) + lines = [] + for interval in (1, 2, 3): + # The knockback: a packet for the hit tick's move, then every interval (each phase). + for phase in range(interval): + lines.append(f'case {interval} 10.5 64.0 0.5 90.0 0.0') + for k in range(1, len(KNOCKBACK)): + if k == 1 or (k + phase) % interval == 0: + x, y = KNOCKBACK[k] + lines.append(f'move L {10.5 + x!r} {64 + y!r} 0.5 -') + lines.append('tick') + lines += ['tick'] * 6 + for _ in range(count): + p = [rng.uniform(-100, 100), rng.uniform(-64, 300), rng.uniform(-100, 100)] + yaw, pitch = rotation(rng) + lines.append(f'case {rng.choice([1, 2, 3, 3, 3])} {p[0]!r} {p[1]!r} {p[2]!r} {yaw!r} {pitch!r}') + last = None + for _ in range(rng.randrange(1, 40)): + if rng.random() < 0.45: + lines.append('tick') + continue + if last is not None and rng.random() < 0.15: + line = last # the same packet again + else: + if rng.random() < 0.1: + line = 'move N' + elif rng.random() < 0.2: + n = rng.randrange(1, 5) + steps = [] + for _ in range(n): + p = position(rng, p) + steps.append(f'{p[0]!r} {p[1]!r} {p[2]!r} {rng.randrange(1, 4)}') + line = f'move S {n} ' + ' '.join(steps) + else: + p = position(rng, p) if rng.random() < 0.9 else p + line = f'move L {p[0]!r} {p[1]!r} {p[2]!r}' + rot = rotation(rng) if rng.random() < 0.6 else None + line += f' R {rot[0]!r} {rot[1]!r}' if rot else ' -' + last = line + lines.append(line) + lines += ['tick'] * rng.choice([0, 1, 1, 2, 3, 6]) + return lines + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / 'stepped-interpolation-parity' + build.mkdir(parents=True, exist_ok=True) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + events = build / 'events.txt' + events.write_text('\n'.join(cases(3000, 1374)) + '\n', encoding='utf-8') + classpath = os.pathsep.join(map(str, [jars['client'], *libraries])) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSteppedInterpolationOracle.java' + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', classpath, '-d', str(classes), str(oracle)], check=True) + subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + classpath, + 'dev.horizonlab.parity.VanillaSteppedInterpolationOracle', str(events), str(build / 'vanilla.txt')], + check=True) + subprocess.run(['cargo', 'run', '--quiet', '--release', '-p', 'horizon-world', '--example', + 'stepped_interpolation_fixture', '--', str(events), str(build / 'rust.txt')], cwd=lab.ROOT, check=True) + matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') + print(f'Stepped interpolation parity passed: {matched} entity positions and rotations match vanilla') + + +if __name__ == '__main__': + main() From 144741b7c7f165353dc4c34ae0e9ebad0707cbb6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 06:39:22 +0200 Subject: [PATCH 09/12] Screen overlays: one texture sample, as on main The vignette, drawn over every frame, went from one texture sample to up to four texel loads and per-pixel address arithmetic: +0.85 ms of GPU a frame on an HD 620 (integer modulo, removed in the commit before), still +0.4 ms after it. - A blurred sprite gets a one-texel border in the atlas, copied from its opposite edges: the hardware's bilinear sample of the atlas with the entity group's linear sampler is then GL_LINEAR with repeat, edges included. Clamp-to-edge keeps the sample point half a texel inside the sprite, which is what the hardware's clamp does for both filters. - Each sampling has its own pipeline, the shader specialised by override constants: a repeat sprite runs main's arithmetic and one sample, nearest or linear; only clamp adds a clamp. The sampling moves from the vertices to the quad, so the vertex layout is main's again. - A black vignette changes no pixel (it darkens by texture x colour), and is no longer drawn: in daylight its brightness fades to 0 within half a minute, so most frames outdoors skip it, which main never could. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 92 ++++++++++++--------- crates/horizon-client/src/hud.rs | 54 +++++++++++- crates/horizon-client/src/screen.wgsl | 56 ++++++------- crates/horizon-client/src/screen_effects.rs | 29 +++++-- 4 files changed, 156 insertions(+), 75 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 3aa4ace2a..f1cc3393d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -357,8 +357,9 @@ pub struct Renderer { border_group: wgpu::BindGroup, border_uniform: wgpu::Buffer, border_vertices: wgpu::Buffer, - /// Screen effects: alpha-blended and vignette (`dst * (1 - src)`) pipelines. - screen_pipelines: [wgpu::RenderPipeline; 2], + /// Screen effects: alpha-blended, then vignette (`dst * (1 - src)`) + /// pipelines, each for every sampling (index `blend * 4 + sampling`). + screen_pipelines: [wgpu::RenderPipeline; 8], screen_buffer: wgpu::Buffer, screen_capacity: u64, entity_group: wgpu::BindGroup, @@ -1983,7 +1984,7 @@ impl Renderer { source: wgpu::ShaderSource::Wgsl(include_str!("screen.wgsl").into()), }); let screen_attributes = - wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4,4=>Uint32]; + wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Float32x4,3=>Float32x4]; let screen_vertex = [Some(wgpu::VertexBufferLayout { array_stride: std::mem::size_of::() as u64, step_mode: wgpu::VertexStepMode::Vertex, @@ -2001,37 +2002,52 @@ impl Renderer { operation: wgpu::BlendOperation::Add, }, }; - let screen_pipelines = - [("fs_screen", alpha_blend), ("fs_vignette", vignette_blend)].map(|(entry, blend)| { - device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("Screen effects"), - layout: Some(&entity_layout), - vertex: wgpu::VertexState { - module: &screen_shader, - entry_point: Some("vs_screen"), - compilation_options: Default::default(), - buffers: &screen_vertex, - }, - primitive: wgpu::PrimitiveState { - cull_mode: None, - ..Default::default() - }, - depth_stencil: None, - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &screen_shader, - entry_point: Some(entry), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format: config.format.remove_srgb_suffix(), - blend: Some(blend), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }) - }); + // One per blend and `.png.mcmeta` sampling (screen_effects::SAMPLE_*): + // the shader is specialised, so a pixel pays for none of the others. + let screen_pipelines: [wgpu::RenderPipeline; 8] = std::array::from_fn(|i| { + let (entry, blend) = if i & 4 == 0 { + ("fs_screen", alpha_blend) + } else { + ("fs_vignette", vignette_blend) + }; + let on = |bit: u32| f64::from(u8::from(i as u32 & bit != 0)); + let constants = [ + ("BLUR", on(crate::screen_effects::SAMPLE_BLUR)), + ("CLAMP", on(crate::screen_effects::SAMPLE_CLAMP)), + ]; + let compilation_options = wgpu::PipelineCompilationOptions { + constants: &constants, + ..Default::default() + }; + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Screen effects"), + layout: Some(&entity_layout), + vertex: wgpu::VertexState { + module: &screen_shader, + entry_point: Some("vs_screen"), + compilation_options: compilation_options.clone(), + buffers: &screen_vertex, + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &screen_shader, + entry_point: Some(entry), + compilation_options, + targets: &[Some(wgpu::ColorTargetState { + format: config.format.remove_srgb_suffix(), + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }); let screen_capacity = 64; let screen_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Screen effect vertices"), @@ -3911,11 +3927,11 @@ impl Renderer { pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); pass.set_vertex_buffer(0, self.screen_buffer.slice(..)); for (i, quad) in frame.screen.iter().enumerate() { - let pipeline = match quad.blend { - crate::screen_effects::Blend::Alpha => &self.screen_pipelines[0], - crate::screen_effects::Blend::Vignette => &self.screen_pipelines[1], + let blend = match quad.blend { + crate::screen_effects::Blend::Alpha => 0, + crate::screen_effects::Blend::Vignette => 4, }; - pass.set_pipeline(pipeline); + pass.set_pipeline(&self.screen_pipelines[blend + (quad.sampling & 3) as usize]); pass.draw_indexed(0..6, (i * 4) as i32, 0..1); } } diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 43ae29c74..dbd44266a 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -104,6 +104,20 @@ fn walk(dir: &Path, out: &mut Vec) { } /// A packed atlas image: sprite name, size and RGBA pixels. type PackedImage = (String, u32, u32, Vec); +/// `image` inside a one-texel border copied from its opposite edges, the +/// texels repeat addressing reads past each edge. +fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage { + let (bw, bh) = (w + 2, h + 2); + let mut out = Vec::with_capacity((bw * bh * 4) as usize); + for y in 0..bh { + let row = (y + h - 1) % h; + for x in 0..bw { + let at = ((row * w + (x + w - 1) % w) * 4) as usize; + out.extend_from_slice(&data[at..at + 4]); + } + } + (name.clone(), bw, bh, out) +} /// Sprites the atlas definitions (`atlases/*.json`) add beyond the texture /// files already packed: generated ones (`paletted_permutations` such as the /// armour trim sprites, `unstitch` regions) and files listed under another id. @@ -326,6 +340,16 @@ impl HudAtlas { if full { Self::slots(&mut images, crate::trims::slot_size(root)); } + // Blurred sprites are sampled linearly in the atlas (screen.wgsl): a + // border wrapped from their own edges keeps the filter off their + // neighbours, as repeat addressing of their own texture would. + let mut bordered = std::collections::HashSet::new(); + for image in &mut images { + if flags.get(&image.0).is_some_and(|f: &TextureFlags| f.blur) { + *image = wrap_border(image); + bordered.insert(image.0.clone()); + } + } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); let width = 4096u32; let mut placements = Vec::with_capacity(images.len()); @@ -350,6 +374,8 @@ impl HudAtlas { let dst = (((py + row) * width + px) * 4) as usize; pixels[dst..dst + (w * 4) as usize].copy_from_slice(src); } + let b = u32::from(bordered.contains(name)); + let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); sprites.insert( name.clone(), Rect { @@ -357,8 +383,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w: *w, - h: *h, + w, + h, }, ); } @@ -1246,6 +1272,30 @@ impl HudRenderer { mod tests { use super::*; + #[test] + fn a_wrapped_border_repeats_the_opposite_edges() { + // 2x2 texels a b / c d, one byte each in red. + let image = ( + "x".to_owned(), + 2, + 2, + [1u8, 2, 3, 4] + .iter() + .flat_map(|&v| [v, 0, 0, 255]) + .collect(), + ); + let (_, w, h, data) = wrap_border(&image); + assert_eq!((w, h), (4, 4)); + let red: Vec = data.chunks(4).map(|t| t[0]).collect(); + #[rustfmt::skip] + assert_eq!(red, [ + 4, 3, 4, 3, + 2, 1, 2, 1, + 4, 3, 4, 3, + 2, 1, 2, 1, + ]); + } + #[test] fn the_fonts_only_atlas_measures_text_like_the_full_one() { // A synthetic default font: two 8x8 glyphs, 3 and 5 pixels wide. diff --git a/crates/horizon-client/src/screen.wgsl b/crates/horizon-client/src/screen.wgsl index f32274bc8..e70aeb896 100644 --- a/crates/horizon-client/src/screen.wgsl +++ b/crates/horizon-client/src/screen.wgsl @@ -3,51 +3,49 @@ // with the sampler vanilla gives it (ReloadableTexture.setSampler: linear // when `blur`, clamp-to-edge when `clamp`, else nearest and repeat). @group(0) @binding(1) var atlas: texture_2d; +// The block sprites' sampler (nearest), and the entity group's lightmap +// sampler (linear) for `blur`. A blurred sprite has a one-texel border in the +// atlas, wrapped as repeat reads it (hud.rs), so the hardware's bilinear +// sample is GL_LINEAR with repeat; clamp-to-edge keeps the sample point half +// a texel inside. Each sampling has its own pipeline (gfx.rs), so a pixel +// costs what it did with nearest and repeat only: one sample. +@group(0) @binding(2) var nearest_sampler: sampler; +@group(0) @binding(4) var linear_sampler: sampler; +override BLUR: bool = false; +override CLAMP: bool = false; struct Out { @builtin(position) clip: vec4, @location(0) uv: vec2, @location(1) @interpolate(flat) rect: vec4, @location(2) color: vec4, - @location(3) @interpolate(flat) sampling: u32, + // With clamp-to-edge, the sprite's first and last texel centres. + @location(3) @interpolate(flat) edges: vec4, } @vertex fn vs_screen(@location(0) pos: vec2, @location(1) uv: vec2, - @location(2) rect: vec4, @location(3) color: vec4, - @location(4) sampling: u32) -> Out { + @location(2) rect: vec4, @location(3) color: vec4) -> Out { var out: Out; out.clip = vec4(pos, 0.0, 1.0); out.uv = uv; out.rect = rect; out.color = color; - out.sampling = sampling; + let half = 0.5 / vec2(textureDimensions(atlas)); + out.edges = vec4(rect.xy + half, rect.zw - half); return out; } -const SAMPLE_BLUR: u32 = 1u; -const SAMPLE_CLAMP: u32 = 2u; -// A texel of the sprite, addressed by repeat or clamp-to-edge. With repeat, `p` is at most one -// texel outside the sprite (`sample` reduces the coordinate first), so wrapping is a select: no -// integer division, which Intel GPUs emulate (it cost 0.85 ms a frame on the vignette on an HD 620). -fn texel(origin: vec2, size: vec2, p: vec2, clamp_edge: bool) -> vec4 { - var q = select(select(p, p - size, p >= size), p + size, p < vec2(0)); - if clamp_edge { q = clamp(p, vec2(0), size - 1); } - return textureLoad(atlas, origin + q, 0); -} fn sample(in: Out) -> vec4 { - let dims = vec2(textureDimensions(atlas)); - let origin = vec2(round(in.rect.xy * dims)); - let size = max(vec2(round((in.rect.zw - in.rect.xy) * dims)), vec2(1)); - let clamp_edge = (in.sampling & SAMPLE_CLAMP) != 0u; - // Repeat: one period of the sprite, so every texel read is at most one outside it. - let p = select(fract(in.uv), in.uv, clamp_edge) * vec2(size); - if (in.sampling & SAMPLE_BLUR) == 0u { - return texel(origin, size, vec2(floor(p)), clamp_edge) * in.color; + var f = in.uv; + if !CLAMP { + // Repeat: one period of the sprite. + f = fract(f); } - // GL_LINEAR: the four texels around the sample point, weighted. - let c = p - 0.5; - let i = vec2(floor(c)); - let t = c - floor(c); - let a = mix(texel(origin, size, i, clamp_edge), texel(origin, size, i + vec2(1, 0), clamp_edge), t.x); - let b = mix(texel(origin, size, i + vec2(0, 1), clamp_edge), texel(origin, size, i + vec2(1, 1), clamp_edge), t.x); - return mix(a, b, t.y) * in.color; + var uv = in.rect.xy + f * (in.rect.zw - in.rect.xy); + if CLAMP { + uv = clamp(uv, in.edges.xy, in.edges.zw); + } + if BLUR { + return textureSampleLevel(atlas, linear_sampler, uv, 0.0) * in.color; + } + return textureSampleLevel(atlas, nearest_sampler, uv, 0.0) * in.color; } @fragment fn fs_screen(in: Out) -> @location(0) vec4 { let c = sample(in); diff --git a/crates/horizon-client/src/screen_effects.rs b/crates/horizon-client/src/screen_effects.rs index 48f468d4d..269a534e7 100644 --- a/crates/horizon-client/src/screen_effects.rs +++ b/crates/horizon-client/src/screen_effects.rs @@ -27,8 +27,6 @@ pub struct ScreenVertex { /// Atlas rectangle (u0, v0, u1, v1) of the sprite. pub rect: [f32; 4], pub color: [f32; 4], - /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. - pub sampling: u32, } /// Linear filtering (`TextureMetadataSection.blur`), else nearest. pub const SAMPLE_BLUR: u32 = 1; @@ -43,6 +41,8 @@ pub fn sampling(flags: TextureFlags) -> u32 { pub struct ScreenQuad { pub vertices: [ScreenVertex; 4], pub blend: Blend, + /// How the sprite is sampled: [`SAMPLE_BLUR`] and [`SAMPLE_CLAMP`]. + pub sampling: u32, } /// What the camera sees this frame. @@ -124,9 +124,9 @@ impl ScreenEffects { uv: uv[i], rect, color, - sampling, }), blend: Blend::Alpha, + sampling, }; let full = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]; // ScreenEffectRenderer.submitBlockSprite: u1/v1 at (-1, -1), colour 0xFF191919. @@ -187,10 +187,10 @@ impl ScreenEffects { uv: [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]][i], rect, color, - sampling, } }), blend, + sampling, }; let rgba = |c: u32| { let [a, r, g, b] = c.to_be_bytes(); @@ -213,6 +213,12 @@ impl ScreenEffects { } else { Blend::Alpha }; + // The vignette darkens by texture × colour: black (in + // daylight its brightness fades to 0 within half a + // minute) leaves every pixel as it was. + if blend == Blend::Vignette && color & 0x00ff_ffff == 0 { + continue; + } if let Some(rect) = sprite(texture) { out.push(gui(rect, rgba(*color), blend, texture_sampling(texture))); } @@ -283,7 +289,18 @@ mod tests { let quads = e.build(&input); assert_eq!(quads.len(), 1); assert_eq!(quads[0].blend, Blend::Vignette); - assert_eq!(quads[0].vertices[0].sampling, 0); + assert_eq!(quads[0].sampling, 0); + // A black vignette (faded out in daylight) changes no pixel: no quad. + // Below 1/255 the colour's channels are 0; a border warning tints it. + for (brightness, warning, drawn) in [(0.003, 0.0, 0), (0.004, 0.0, 1), (0.0, 0.5, 1)] { + let overlays = [crate::hud_overlays::vignette(320, 240, brightness, warning)]; + let input = ScreenInputs { + block_overlay: None, + gui_overlays: &overlays, + ..input + }; + assert_eq!(e.build(&input).len(), drawn, "{brightness} {warning}"); + } } #[test] fn standalone_textures_sample_by_their_metadata() { @@ -323,7 +340,7 @@ mod tests { on_fire: false, gui_overlays: &[crate::hud_overlays::vignette(320, 240, 1.0, 0.0)], }); - let sampling: Vec<_> = quads.iter().map(|q| q.vertices[0].sampling).collect(); + let sampling: Vec<_> = quads.iter().map(|q| q.sampling).collect(); assert_eq!(sampling, [0, SAMPLE_CLAMP, SAMPLE_BLUR]); } #[test] From 5c9f11b9546e4067ba9fc406290024a3428e64fc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 07:58:53 +0200 Subject: [PATCH 10/12] Benchmark: a 1080p set next to 720p perf_bench ran every game in a 1280x720 window only. It now runs the standard set at 1280x720 and 1920x1080 (--sizes picks others), each size its own reports: