From 9e21868dfa012b3a46d3242d03e56845fb6fb5c5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 13:46:45 +0100 Subject: [PATCH 01/26] Potions keep their potion across the connection A server's client (single player on the server thread, LAN guests, a dedicated server's players) saw every potion as an "Uncraftable Potion" in the water colour: the server never wrote `minecraft:potion_contents` and the client read past it. A potion taken from the creative menu also reached the server without its potion, so it splashed as water. PotionContents now goes as vanilla's stream codec writes it: the potion by its `minecraft:potion` id and the custom colour, with the custom effects and name kept as their bytes. The server writes it for every stack it sends, the client reads it into the item's components, and a creative pick and the server's read of it keep the potion too. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 7 ++ crates/horizon-client/src/game/remote.rs | 24 +++++ crates/horizon-client/src/lan/guest.rs | 34 +++++++ crates/horizon-protocol/src/item.rs | 90 +++++++++++++++++++ crates/horizon-protocol/src/item/skip.rs | 8 +- 5 files changed, 158 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..4964bc687 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1231,6 +1231,13 @@ impl Game<'_> { } } } + if let Some(Component::Potion { + potion: Some(id), .. + }) = s.component(component::POTION_CONTENTS) + && let Some(potion) = host.hub.registry_name("minecraft:potion", *id) + { + out = out.with_potion(potion); + } Some(out) } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5a71b13a8..c723400a8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -672,6 +672,16 @@ impl Game<'_> { ("mob_factor", Tag::Float(v[5].to_bits())), ]), Component::Profile(p) => profile_tag(p), + // PotionContents' NBT: the potion by name and the custom colour. + Component::Potion { potion, color, .. } => { + let potion = potion.and_then(|id| r.builtin.get("minecraft:potion")?.name(id)); + Tag::compound( + potion + .map(|name| ("potion", Tag::String(name.into()))) + .into_iter() + .chain(color.map(|c| ("custom_color", Tag::Int(c)))), + ) + } // ItemStackTemplate.CODEC: id, count and components. Component::Stacks(stacks) => Tag::List( stacks @@ -733,6 +743,20 @@ impl Game<'_> { fn to_network(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(self.item_id(&s.item), s.count as i32); + // A creative pick keeps its potion (PotionContents by its builtin id). + if let Some(id) = s.potion().and_then(|p| { + let potions = self.remote.as_ref()?.builtin.get("minecraft:potion")?; + potions.id(&horizon_world::datafix::dynamic::namespaced(p)) + }) { + stack.added.push(( + horizon_protocol::item::component::POTION_CONTENTS, + horizon_protocol::item::Component::Potion { + potion: Some(id), + color: None, + rest: Vec::new(), + }, + )); + } if s.damage > 0 { stack.added.push(( horizon_protocol::item::component::DAMAGE, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 440b58284..bbab454d7 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -521,6 +521,22 @@ fn network_stack( horizon_protocol::item::Component::Int(i32::from(mode)), )); } + // PotionContents: the potion by its `minecraft:potion` id. + if let Some(id) = (d.potion.as_deref()).and_then(|potion| { + synced_id( + "minecraft:potion", + &horizon_world::datafix::dynamic::namespaced(potion), + ) + }) { + stack.added.push(( + horizon_protocol::item::component::POTION_CONTENTS, + horizon_protocol::item::Component::Potion { + potion: Some(id), + color: None, + rest: Vec::new(), + }, + )); + } // A loaded crossbow's ammunition. if !d.charged.is_empty() { let charged = d @@ -573,6 +589,24 @@ mod tests { use super::*; use horizon_protocol::item::{Component, component}; + #[test] + fn potions_go_as_potion_registry_ids() { + let synced_id = |registry: &str, name: &str| match (registry, name) { + ("minecraft:potion", "minecraft:swiftness") => Some(14), + _ => None, + }; + let potion = ItemStack::new("minecraft:splash_potion", 1).with_potion("swiftness"); + let stack = stack_to_network(|_| 7, synced_id, &Some(potion)).unwrap(); + assert_eq!( + stack.component(component::POTION_CONTENTS), + Some(&Component::Potion { + potion: Some(14), + color: None, + rest: Vec::new(), + }) + ); + } + #[test] fn trims_go_as_synced_registry_references() { let mut chestplate = ItemStack::new("minecraft:diamond_chestplate", 1); diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 6b6b845f8..2c04b5c61 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -35,6 +35,7 @@ pub mod component { pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; pub const CHARGED_PROJECTILES: i32 = 51; + pub const POTION_CONTENTS: i32 = 53; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; pub const TRIM: i32 = 58; @@ -65,6 +66,13 @@ pub enum Component { Lore(Vec), Enchantments(Vec<(i32, i32)>), AttackRange([f32; 6]), + /// `PotionContents`: the potion's `minecraft:potion` id and the custom + /// colour; the custom effects and name stay their encoded bytes. + Potion { + potion: Option, + color: Option, + rest: Vec, + }, Profile(Profile), CustomModelData { floats: Vec, @@ -162,6 +170,22 @@ impl Component { .collect::>()?, ) } + POTION_CONTENTS => { + let potion = if r.bool()? { Some(r.varint()?) } else { None }; + let color = if r.bool()? { Some(r.i32()?) } else { None }; + let start = r.position(); + skip::potion_effects_and_name(r)?; + // No custom effects and no name: an empty tail. + let rest = match r.since(start) { + [0, 0] => Vec::new(), + bytes => bytes.to_vec(), + }; + Self::Potion { + potion, + color, + rest, + } + } ATTACK_RANGE => { let mut values = [0.0f32; 6]; for v in &mut values { @@ -283,6 +307,27 @@ impl Component { } } Self::AttackRange(values) => values.iter().for_each(|v| w.f32(*v)), + Self::Potion { + potion, + color, + rest, + } => { + w.bool(potion.is_some()); + if let Some(id) = potion { + w.varint(*id); + } + w.bool(color.is_some()); + if let Some(color) = color { + w.i32(*color); + } + // An empty tail is no custom effects and no name. + if rest.is_empty() { + w.varint(0); + w.bool(false); + } else { + w.bytes(rest); + } + } Self::Profile(p) => { w.u8(0); w.bool(p.name.is_some()); @@ -532,6 +577,51 @@ mod tests { assert_eq!(r.remaining(), 0); } + #[test] + fn potion_contents_round_trip() { + let mut arrow = Stack::new(7, 3); + arrow.added.push(( + component::POTION_CONTENTS, + Component::Potion { + potion: Some(31), + color: None, + rest: Vec::new(), + }, + )); + round::, Slot>(Some(arrow)); + // A custom colour, one custom effect (speed II for 600 ticks, shown, + // no hidden effect) and a custom name survive as they came. + let mut w = Writer::new(); + w.bool(false); + w.bool(true); + w.i32(0x00FF_8800); + w.varint(1); + for v in [1, 1, 600] { + w.varint(v); + } + for b in [false, true, true, false] { + w.bool(b); + } + w.bool(true); + w.string("Tea"); + let mut r = Reader::new(&w.data); + let read = Component::read(component::POTION_CONTENTS, &mut r).unwrap(); + assert_eq!(r.remaining(), 0); + let Component::Potion { + potion, + color, + rest, + } = &read + else { + panic!("{read:?}"); + }; + assert_eq!((*potion, *color), (None, Some(0x00FF_8800))); + assert!(!rest.is_empty()); + let mut again = Writer::new(); + read.write(component::POTION_CONTENTS, &mut again); + assert_eq!(again.data, w.data); + } + #[test] fn stacks_round_trip() { round::, Slot>(None); diff --git a/crates/horizon-protocol/src/item/skip.rs b/crates/horizon-protocol/src/item/skip.rs index 152d0f0f1..aa436cc31 100644 --- a/crates/horizon-protocol/src/item/skip.rs +++ b/crates/horizon-protocol/src/item/skip.rs @@ -87,7 +87,6 @@ pub(super) fn component(kind: i32, r: &mut Reader) -> Result<()> { } // BundleContents: templates. 52 => list(r, template), - 53 => potion_contents(r), // SuspiciousStewEffects: effect, duration. 55 => list(r, |r| { varint(r)?; @@ -410,10 +409,9 @@ fn kinetic_weapon(r: &mut Reader) -> Result<()> { optional(r, sound)?; optional(r, sound) } -/// PotionContents: potion, customColor, customEffects, customName. -fn potion_contents(r: &mut Reader) -> Result<()> { - optional(r, varint)?; - optional(r, i32)?; +/// PotionContents' customEffects and customName (`Component::read` reads +/// the potion and colour before them). +pub(super) fn potion_effects_and_name(r: &mut Reader) -> Result<()> { list(r, mob_effect)?; optional(r, string) } From df626cf2f381ff11ff72a2e7d3793e7078291cca Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:15:28 +0100 Subject: [PATCH 02/26] A tool that changes a block ends the click on a server's client On a server's client (single player on the server thread, LAN guests), a shovel making a path, an axe stripping, a hoe tilling or honeycomb waxing did not end the right click: the client went on to the other hand, so an off-hand torch was predicted as placed and its hand swung instead of the tool's (#1289). Vanilla's client runs `Item.useOn` itself: its SUCCESS swings that hand and `Minecraft.startUseItem` returns before the off hand. The client now does the same when its prediction of the tool's use succeeds. Fixes #1289 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index c1ef53122..8edfd77a2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4000,8 +4000,14 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); - } else if let Some(stack) = held.as_ref() { - self.predict_item_on_block(stack, &hit); + } else if let Some(stack) = held.as_ref() + && self.predict_item_on_block(stack, &hit) + { + // Item.useOn succeeded here (InteractionResult.SUCCESS): + // this hand swings and the click ends, so the other hand + // (a shield, a torch) is never tried. + self.with_hand(hand, Game::swing_arm); + return true; } if held_block { let placed = if reacts { @@ -4031,7 +4037,8 @@ impl Game<'_> { /// `playSound(player, ...)`: the server sends them to the others only): /// honeycomb waxing copper, and an axe, hoe or shovel transforming a /// block (stripping, scraping, removing wax, tilling, making a path). - fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) { + /// Whether the item's use succeeded, which ends the click. + fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) -> bool { let at = [ f64::from(hit.pos[0]) + 0.5, f64::from(hit.pos[1]) + 0.5, @@ -4050,11 +4057,15 @@ impl Game<'_> { self.audio .play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0); } + waxes } else if let Some((_, sound, _, _, particle)) = self.block_transform(stack, hit.pos, hit.face) { self.transform_particle(&particle, hit.pos); self.audio.play(&sound, Some(at), 1.0, 1.0); + true + } else { + false } } From 68deac8533c0a7072785712940b643f11c34c039 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:38:44 +0100 Subject: [PATCH 03/26] Server clients see mobs' aggression and arm swings Mob.DATA_MOB_FLAGS_ID now carries the aggressive bit (with its default 0, so it goes back off) and every client mob reads no AI, left-handed and aggressive from it: a vindicator draws its axe, skeletons their bow, piglins and illagers their attack poses on the server thread, LAN guests and dedicated servers. Mobs' swings (LivingEntity.swing) go out as ClientboundSwingAnimationPacket. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 24 +++++++++++++++---- crates/horizon-client/src/game/remote.rs | 9 ------- .../src/game/remote_mob_data.rs | 21 ++++++++++++++++ 3 files changed, 40 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8460f54e6..97b4d2ba7 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -55,8 +55,8 @@ pub(super) struct LanHost { pub play: HashMap, /// Blocks broken this tick (their sound is a level event for the guests). pub broken: Vec<[f64; 3]>, - /// Hurt and death state of the mobs guests see. - mob_state: HashMap>, + /// Hurt time, death and swing time (while swinging) of the mobs guests see. + mob_state: HashMap)>>, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). @@ -168,11 +168,15 @@ fn mob_meta( meta.push((9, serializer::FLOAT, Value::Float(health))); } defaults.push((9, serializer::FLOAT, Value::Float(1.0))); - // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2. - let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1; + // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what + // draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised + // weapon). + let flags = + i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1 | i8::from(m.ai.aggressive) << 2; if flags != 0 { meta.push((15, serializer::BYTE, Value::Byte(flags))); } + defaults.push((15, serializer::BYTE, Value::Byte(0))); // AgeableMob.DATA_BABY_ID (and Zombie's, Piglin's). if let Some(index) = baby_index(kind) { if m.is_baby() { @@ -1193,7 +1197,17 @@ impl Game<'_> { if dead && !old.is_some_and(|o| o.1) { host.hub.entity_event(m.id as i32, 3, at); } - seen.insert(m.id, (m.hurt_time, dead)); + // LivingEntity.swing on a server (a melee hit, a thrown potion): + // ClientboundSwingAnimationPacket for the players around. A swing + // started since the last flush, or restarted (its time went back). + let swing = m.ai.swinging.then_some(m.ai.swing_time); + if let Some(time) = swing + && !dead + && old.and_then(|o| o.2).is_none_or(|before| time < before) + { + host.hub.swing(m.id as i32, 0, at, None); + } + seen.insert(m.id, (m.hurt_time, dead, swing)); } host.mob_state.insert(self.dim, seen); } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 044e43835..11d2b367c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1994,15 +1994,6 @@ impl Game<'_> { } } } - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) - && m.species() == horizon_client::mobs::Species::Rabbit - { - for (index, _, value) in &p.values { - if let (15, Value::Byte(flags)) = (index, value) { - m.no_ai = flags & 1 != 0; - } - } - } self.remote_mob_data(p.id, &p.values); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Creeper diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 5573d0f87..64c092142 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -23,6 +23,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { // LivingEntity.DATA_HEALTH_ID: the boss bars and the death // animation follow it. (9, Value::Float(health)) => m.health = *health, + // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4. + // Mob.isAggressive draws the illagers' and skeletons' attack + // poses and the vindicator's axe. + (15, Value::Byte(flags)) => { + m.no_ai = flags & 1 != 0; + m.extra.left_handed = flags & 2 != 0; + m.ai.aggressive = flags & 4 != 0; + } (i, Value::Bool(b)) if Some(i) == baby => m.extra.age = if *b { -1 } else { 0 }, _ => {} } @@ -178,6 +186,19 @@ mod tests { assert_eq!(m.fire_ticks, 0); } + #[test] + fn mob_flags_turn_aggression_on_and_off() { + let Some(mut m) = mob("minecraft:vindicator") else { + return; + }; + apply(&mut m, &[(15, s::BYTE, Value::Byte(4 | 2))]); + assert!(m.ai.aggressive && m.extra.left_handed && !m.no_ai); + assert!(horizon_client::mobs::illager::shows_item(&m)); + apply(&mut m, &[(15, s::BYTE, Value::Byte(0))]); + assert!(!m.ai.aggressive && !m.extra.left_handed); + assert!(!horizon_client::mobs::illager::shows_item(&m)); + } + #[test] fn a_villager_takes_its_type_profession_and_level() { let Some(mut m) = mob("minecraft:villager") else { From f56785c2f512eef6eff83687455cbee97ecbcd11 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 13:16:16 +0100 Subject: [PATCH 04/26] Keep a chunk's scheduled ticks when it unloads before the next tick attach_save_data took a chunk's ticks only from the tick scheduler, which registers new chunks once a tick. A chunk loaded and unloaded again in between was saved with its block and fluid ticks cleared, though its own saved list still held them. --- crates/horizon-client/src/game/persist.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index d3afbf6ce..45ef8801f 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -76,15 +76,14 @@ impl Game<'_> { let pos = ChunkPos::new(chunk.x, chunk.z); let time = self.world.game_time; let mut extras: ChunkExtras = chunk.saved.as_deref().cloned().unwrap_or_default(); + // A chunk the scheduler hasn't registered yet (one loaded and + // unloaded again before the next tick) still holds its saved ticks: + // `register_chunk_ticks` empties that list once it takes them. if let Some(t) = self.block_ticks.blocks.chunk(pos) { extras.block_ticks = t.pack(time); - } else { - extras.block_ticks.clear(); } if let Some(t) = self.block_ticks.fluids.chunk(pos) { extras.fluid_ticks = t.pack(time); - } else { - extras.fluid_ticks.clear(); } extras.last_update = time; // TheEndGatewayBlockEntity saves its Age (the server copy's). From e181b17e17a88f6c39fbb16dd4b81440d8e738e1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 13:16:16 +0100 Subject: [PATCH 05/26] Register new chunks' ticks before post-processing them postprocess_chunks ran before tick_blocks registered the chunks that arrived since the last tick, so the fluid and block ticks their marks schedule went to chunks the scheduler did not know and were dropped. Vanilla registers a chunk's tick containers before postProcessGeneration. --- crates/horizon-client/src/game/postprocess.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/game/postprocess.rs b/crates/horizon-client/src/game/postprocess.rs index e896a77ab..77cba6832 100644 --- a/crates/horizon-client/src/game/postprocess.rs +++ b/crates/horizon-client/src/game/postprocess.rs @@ -27,6 +27,11 @@ impl Game<'_> { if ready.is_empty() { return Ok(()); } + // The ticks the marks schedule go to the chunks' containers, which a + // chunk that arrived since the last tick doesn't have yet + // (`LevelChunk.registerTickContainerInLevel` comes before + // `postProcessGeneration`). + self.sync_tick_chunks(); for key in ready { let Some(chunk) = self.world.chunks.get_mut(&key) else { continue; From dbafda06ed699a4e6e2653abd2aaa620fcfb1859 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 13:38:10 +0100 Subject: [PATCH 06/26] Surface: specialise the material rule per gradient band and surface side Each chunk's compiled rule is specialised once for every band of y that its vertical gradients bound, and for blocks below and at or above the preliminary surface when the rule asks for it. Conditions those facts decide are folded away, so a deep stone block evaluates only the rules that can apply there (ore veins, the underground rules) instead of walking the whole surface tree. Conditions only read the position and the world, so the blocks are the same. Surface stage, one thread, seed 1234: 2.45 -> 2.08 ms per chunk. --- .../src/worldgen/material_condition.rs | 75 +++++++++ .../src/worldgen/material_condition/rule.rs | 159 +++++++++++++++++- .../src/worldgen/material_stage.rs | 13 +- 3 files changed, 244 insertions(+), 3 deletions(-) diff --git a/crates/horizon-world/src/worldgen/material_condition.rs b/crates/horizon-world/src/worldgen/material_condition.rs index 6433b09a4..d0b6c4290 100644 --- a/crates/horizon-world/src/worldgen/material_condition.rs +++ b/crates/horizon-world/src/worldgen/material_condition.rs @@ -23,6 +23,7 @@ use horizon_core::{ pub use library::MaterialRuleLibrary; pub use noise::MaterialNoiseSources; use rule::CompiledRule; +pub use rule::SurfaceVariants; pub use rule::{MaterialRule, MaterialRuleError}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -299,7 +300,81 @@ enum Kind { }, Not(Box>), } +/// What a specialised rule may assume about every position it is applied to +/// (`CompiledRule::specialize`): its y lies in `low..=high`, and whether it is +/// at or above the column's preliminary surface level, when known. +#[derive(Clone, Copy, Debug)] +pub struct Facts { + pub low: i32, + pub high: i32, + pub above_surface: Option, +} +impl Clone for Kind +where + R::Positional: Clone, +{ + fn clone(&self) -> Self { + match self { + Self::Simple(condition) => Self::Simple(condition.clone()), + Self::Biome(names) => Self::Biome(names.clone()), + Self::Constant(value) => Self::Constant(*value), + Self::Noise { sampler, min, max } => Self::Noise { + sampler: *sampler, + min: *min, + max: *max, + }, + Self::Gradient { low, high, random } => Self::Gradient { + low: *low, + high: *high, + random: random.clone(), + }, + Self::Not(child) => Self::Not(child.clone()), + } + } +} +impl Clone for Compiled +where + R::Positional: Clone, +{ + fn clone(&self) -> Self { + Self { + kind: self.kind.clone(), + revision: self.revision, + result: self.result, + } + } +} impl Compiled { + /// The value `facts` decide for this condition at every position they + /// cover. Conditions read the position and the world, never change them, + /// so one decided in advance gives what testing it would. + fn decided(&self, facts: Facts) -> Option { + match &self.kind { + Kind::Constant(value) => Some(*value), + Kind::Simple(MaterialCondition::AbovePreliminarySurface) => facts.above_surface, + Kind::Gradient { low, high, .. } => { + if facts.high <= *low { + Some(true) + } else if facts.low >= *high { + Some(false) + } else { + None + } + } + Kind::Not(child) => child.decided(facts).map(|value| !value), + _ => None, + } + } + /// The vertical gradients' bounds, and whether the preliminary surface + /// is asked for. + fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) { + match &self.kind { + Kind::Gradient { low, high, .. } => gradients.push((*low, *high)), + Kind::Simple(MaterialCondition::AbovePreliminarySurface) => *surface = true, + Kind::Not(child) => child.inputs(gradients, surface), + _ => {} + } + } fn constant_result(&self) -> Option { match &self.kind { Kind::Constant(value) => Some(*value), diff --git a/crates/horizon-world/src/worldgen/material_condition/rule.rs b/crates/horizon-world/src/worldgen/material_condition/rule.rs index cf4fc8547..f3c2ae60d 100644 --- a/crates/horizon-world/src/worldgen/material_condition/rule.rs +++ b/crates/horizon-world/src/worldgen/material_condition/rule.rs @@ -1,5 +1,7 @@ //! Compiled material rule composition, sharing the condition worker's context. -use super::{Compiled, Context, MaterialCondition, MaterialConditions, MaterialSurfaceQueries}; +use super::{ + Compiled, Context, Facts, MaterialCondition, MaterialConditions, MaterialSurfaceQueries, +}; use crate::{registry::BlockStateId, worldgen::DecodeError}; use horizon_core::{ density::DensitySampler, @@ -209,6 +211,161 @@ impl CompiledRule { } } } +impl CompiledRule +where + R::Positional: Clone, +{ + /// This rule where `facts` hold: conditions they decide are folded away, + /// with what can no longer produce a block, and a sequence stops at its + /// first child that always produces one. For every position the facts + /// cover it gives the block the whole rule gives. + fn specialize(&self, facts: Facts) -> Self { + match self { + Self::Empty => Self::Empty, + Self::Block(block) => Self::Block(*block), + Self::Bandlands => Self::Bandlands, + Self::OreVein { + blocks, + raw_ore_chance, + densities, + random, + } => Self::OreVein { + blocks: *blocks, + raw_ore_chance: *raw_ore_chance, + densities: *densities, + random: random.clone(), + }, + Self::Condition { condition, rule } => match condition.decided(facts) { + Some(false) => Self::Empty, + Some(true) => rule.specialize(facts), + None => match rule.specialize(facts) { + Self::Empty => Self::Empty, + rule => Self::Condition { + condition: condition.clone(), + rule: Box::new(rule), + }, + }, + }, + Self::Sequence(children) => { + let mut result = Vec::new(); + for child in children { + let child = child.specialize(facts); + if matches!(child, Self::Empty) { + continue; + } + let last = child.always_produces(); + result.push(child); + if last { + break; + } + } + match result.len() { + 0 => Self::Empty, + 1 => result.pop().unwrap(), + _ => Self::Sequence(result), + } + } + } + } + /// Whether applying this rule never gives `None` (only an error). + fn always_produces(&self) -> bool { + match self { + Self::Block(_) | Self::Bandlands => true, + Self::Sequence(children) => children.iter().any(Self::always_produces), + Self::Empty | Self::OreVein { .. } | Self::Condition { .. } => false, + } + } + fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) { + match self { + Self::Condition { condition, rule } => { + condition.inputs(gradients, surface); + rule.inputs(gradients, surface); + } + Self::Sequence(children) => { + for child in children { + child.inputs(gradients, surface); + } + } + _ => {} + } + } +} +/// A rule specialised (`CompiledRule::specialize`) for each band of y between +/// its vertical gradients' bounds, and below and at or above the preliminary +/// surface when the rule asks for it: most blocks of a column, deep stone, +/// then evaluate only the few rules that can apply there. +pub struct SurfaceVariants { + /// The first y of each band after the first, ascending. + starts: Vec, + /// The rule index per band (two per band, below then above the surface, + /// when `surface`). + rules: Vec, + pub surface: bool, +} +impl SurfaceVariants { + /// The rule for a block at `y`, `above` the preliminary surface (ignored + /// unless `surface`). + #[inline] + pub fn rule(&self, y: i32, above: bool) -> usize { + let band = self.starts.partition_point(|&start| start <= y); + if self.surface { + self.rules[band * 2 + usize::from(above)] + } else { + self.rules[band] + } + } +} +impl MaterialConditions +where + R::Positional: Clone, +{ + /// Add the specialised variants of rule `index` (`SurfaceVariants`). + pub fn surface_variants(&mut self, index: usize) -> Result { + let rule = self + .rules + .get(index) + .ok_or(MaterialRuleError::UnknownRule)?; + let (mut gradients, mut surface) = (Vec::new(), false); + rule.inputs(&mut gradients, &mut surface); + // A gradient is true at and below `low`, random between, false at + // and above `high`: it is decided within each band these bound. + let mut starts: Vec = gradients + .iter() + .flat_map(|&(low, high)| [low.saturating_add(1), high]) + .collect(); + starts.sort_unstable(); + starts.dedup(); + let mut variants = Vec::new(); + for band in 0..=starts.len() { + let low = if band == 0 { + i32::MIN + } else { + starts[band - 1] + }; + let high = starts.get(band).map_or(i32::MAX, |&next| next - 1); + let sides: &[Option] = if surface { + &[Some(false), Some(true)] + } else { + &[None] + }; + for &above_surface in sides { + let facts = Facts { + low, + high, + above_surface, + }; + variants.push(self.rules[index].specialize(facts)); + } + } + let first = self.rules.len(); + self.rules.extend(variants); + Ok(SurfaceVariants { + starts, + rules: (first..self.rules.len()).collect(), + surface, + }) + } +} impl MaterialConditions { /// Compile all children in order, even after an unconditional block rule. /// Failed compilation never adds a partial rule to this worker. diff --git a/crates/horizon-world/src/worldgen/material_stage.rs b/crates/horizon-world/src/worldgen/material_stage.rs index 0763c4e63..fd51d3716 100644 --- a/crates/horizon-world/src/worldgen/material_stage.rs +++ b/crates/horizon-world/src/worldgen/material_stage.rs @@ -196,7 +196,10 @@ pub fn build_surface, extensions: &MaterialExtensions, -) -> Result<(), SurfaceError> { +) -> Result<(), SurfaceError> +where + R::Positional: Clone, +{ let min = chunk.min_y(); let max = min + chunk.height() - 1; if inputs.write_min_y < min @@ -240,9 +243,13 @@ fn build_columns, write_min_y: i32, write_max_y: i32, -) -> Result<(), SurfaceError> { +) -> Result<(), SurfaceError> +where + R::Positional: Clone, +{ let min = chunk.min_y(); let rule = worker.add_rule(rule)?; + let variants = worker.surface_variants(rule)?; let cx = chunk.position().x.wrapping_shl(4); let cz = chunk.position().z.wrapping_shl(4); for lx in 0..16 { @@ -321,6 +328,8 @@ fn build_columns= write_min_y && y <= write_max_y { + let above = variants.surface && y >= worker.minimum_surface_level()?; + let rule = variants.rule(y, above); if let Some(state) = worker.try_apply(rule, BlockPos::new(x, y, z))? { column.set_block(y, state)?; } From a2fccf0205c133ef871bb9a781dddac1cce52a6c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 14:52:17 +0100 Subject: [PATCH 07/26] Flint and steel lights nether portals only in the Overworld and the Nether BaseFireBlock.inPortalDimension: a frame lit in the End stays a fire. The world code's fire placement already checked it; the flint-and-steel path (Game::try_light_portal) didn't, so a portal could be lit and used in the End in every mode. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..36926afde 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7879,8 +7879,12 @@ impl Game<'_> { (0..width).all(|i| frame([left[0] + d[0] * i, left[1] + height, left[2] + d[2] * i])); ((3..=21).contains(&height) && top_ok).then_some((left, width, height)) } - /// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal. + /// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal, + /// only in the Overworld and the Nether (`inPortalDimension`). fn try_light_portal(&mut self, at: [i32; 3]) -> Result { + if !matches!(self.dim, Dim::Overworld | Dim::Nether) { + return Ok(false); + } for x_axis in [true, false] { if let Some((origin, width, height)) = self.portal_shape(at, x_axis) { let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; From ed7d88b2135e81b19238c3ffb39ede17b838aee6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:13:12 +0100 Subject: [PATCH 08/26] Close container menus when the player moves out of reach Container.stillValidBlockEntity also checks the player's block interaction range plus a 4-block buffer. Guest menus now close in the tick once out of reach and ignore clicks while invalid, and the in-frame single player menu closes the same way. --- .../src/game/block_entity_ticks.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 26 ++++++++++++++ .../horizon-client/src/game/lan_stations.rs | 10 +----- crates/horizon-client/src/game/storage.rs | 36 +++++++++++++++++++ crates/horizon-client/src/lan/containers.rs | 6 ++++ crates/horizon-client/src/lan/guest.rs | 17 +++++++++ crates/horizon-client/src/lan/menu.rs | 13 +++++++ 7 files changed, 100 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index 094aed6ef..389807d9b 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -15,6 +15,7 @@ use horizon_world::registry::BlockStateId; impl Game<'_> { pub(super) fn tick_block_entities(&mut self) -> Result<()> { self.tick_mount_menu(); + self.tick_container_reach(); self.load_entity_types(); if !self.world.block_entities.has_states() { let states = self.ticking_states(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..c6d1b5302 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -812,6 +812,31 @@ impl Game<'_> { } } + /// `ServerPlayer.tick`'s `stillValid`: a guest's block container closes + /// once the guest is out of reach of its block (a removed block closes it + /// in the hub's `sync_containers`). + fn lan_containers_tick(&mut self, host: &mut LanHost) { + let far: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g)) + .filter(|g| { + g.menu.as_ref().is_some_and(|m| { + m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos) + }) + }) + .map(|g| g.conn) + .collect(); + for conn in far { + self.guest_container_closed(host, conn); + host.hub.close_container(conn); + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) { + self.guest_carried_back(host, gi); + } + } + } + /// A packet from a guest that the hub does not handle itself. pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { @@ -1680,6 +1705,7 @@ impl Game<'_> { pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); self.lan_stations_tick(host); + self.lan_containers_tick(host); self.tick_lan_mount_menus(host); self.announce_guest_advancements(host); let conns: Vec = host diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 2efcfc705..49a90b7b9 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -665,13 +665,5 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec { /// its block interaction range (4.5, creative 5) and a 4-block buffer of the /// block's box. pub(super) fn within_reach(g: &horizon_client::lan::guest::Guest, pos: [i32; 3]) -> bool { - let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; - let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; - (0..3) - .map(|k| { - let lo = f64::from(pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach + g.within_block_range(pos, 4.0) } diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 9b28ce26b..9132c02a8 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -127,6 +127,42 @@ impl Game<'_> { None => vec![own], } } + /// `Container.stillValidBlockEntity`: the open block container closes once + /// the player's eyes are out of reach of any of its blocks (a 4-block buffer). + pub(super) fn tick_container_reach(&mut self) { + // A server's menu ends when the server closes it. + if self.remote.is_some() { + return; + } + let Some(eye) = self.eye_position() else { + return; + }; + if self + .container + .is_none_or(|k| k.1 == super::minecarts::CART_KEY_Y) + { + return; + } + let range = self.reach() + 4.0; + let near = self.container_parts().iter().all(|((x, y, z), _)| { + let d = [*x, *y, *z] + .iter() + .zip(eye) + .map(|(&lo, e)| { + (f64::from(lo) - e) + .max(e - f64::from(lo) - 1.0) + .max(0.0) + .powi(2) + }) + .sum::(); + d < range * range + }); + if !near { + self.close_container(); + self.screen = super::Screen::Playing; + self.capture(true); + } + } /// The number of slots of the open container. pub(super) fn container_size(&self) -> usize { self.container_parts().iter().map(|p| p.1).sum() diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index d43cb5c27..d30d3a494 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -343,6 +343,12 @@ impl Hub { if !window_ok || self.guests[i].spectator() { return Vec::new(); } + // A menu that is no longer valid takes no clicks. + if let Some(m) = self.guests[i].menu.as_ref().filter(|_| in_menu) + && !m.slots.still_valid(world, &self.guests[i], m.pos) + { + return Vec::new(); + } let source = self.guests[i].menu.as_ref().map(|m| m.slots); let mut drag = if in_menu { self.guests[i].menu.as_mut().and_then(|m| m.drag.take()) diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 440b58284..dc10096e3 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -404,6 +404,23 @@ impl Guest { pub fn eye_height(&self) -> f64 { if self.sneaking { 1.27 } else { 1.62 } } + /// `Player.isWithinBlockInteractionRange(pos, buffer)`: the eyes within the + /// block interaction range (4.5, creative 5) plus `buffer` of the block's box. + pub fn within_block_range(&self, pos: [i32; 3], buffer: f64) -> bool { + let eye = [ + self.position[0], + self.position[1] + self.eye_height(), + self.position[2], + ]; + let reach = if self.creative() { 5.0 } else { 4.5 } + buffer; + (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach + } /// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting /// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar, /// 45 off hand. diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index de9fb9608..b3f72da7e 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -64,6 +64,19 @@ impl Slots { .iter() .all(|k| world.block_entities.contains_key(k)) } + /// `Container.stillValid` for the guest: the block entities are there + /// and the guest is within reach of each (`stillValidBlockEntity`). The + /// ender chest's block is `at` (`PlayerEnderChestContainer.activeChest`). + pub fn still_valid(self, world: &World, guest: &Guest, at: Option<(i32, i32, i32)>) -> bool { + let blocks = match self { + Slots::Ender => at.into_iter().collect(), + _ => self.halves(), + }; + self.valid(world) + && blocks + .iter() + .all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0)) + } /// Container slot `n`. pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option { if self == Slots::Ender { From 18ec4145c46400864f921987ed4d601fd1979f04 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:19:31 +0100 Subject: [PATCH 09/26] Close crafting tables that are removed or out of reach CraftingMenu.stillValid needs the block to still be a crafting table and the player within reach of it. The table's position is now kept with the open grid, so the menu closes in the tick (giving its grid back) and a stale click no longer crafts, in single player and for LAN guests. --- crates/horizon-client/src/game.rs | 34 +++++++++ .../src/game/block_entity_ticks.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 16 +++-- .../horizon-client/src/game/lan_crafting.rs | 69 +++++++++++++++---- 4 files changed, 102 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..7a208ecfe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1168,6 +1168,8 @@ struct Game<'a> { carried: Option, craft_grid: Vec>, craft_size: usize, + /// The crafting table the 3x3 grid belongs to (`CraftingMenu.access`). + craft_table: Option<[i32; 3]>, /// A quick craft drag over inventory slots: (button, game slots so far). inv_drag: Option<(i32, Vec)>, /// `AbstractContainerScreen`'s quick craft and skip-release state. @@ -2897,6 +2899,35 @@ impl Game<'_> { } Ok(()) } + /// `CraftingMenu.stillValid`: the open crafting table closes once its + /// block is gone or the player's eyes are out of reach (a 4-block buffer). + pub(super) fn tick_craft_table(&mut self) { + // A server's menu ends when the server closes it. + if self.remote.is_some() || self.craft_size != 3 { + return; + } + let (Some(pos), Some(eye)) = (self.craft_table, self.eye_position()) else { + return; + }; + let table = &*self + .res + .facts() + .get(self.world.block(pos[0], pos[1], pos[2])) + .name + == "minecraft:crafting_table"; + let range = self.reach() + 4.0; + let d = (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::(); + if !table || d >= range * range { + self.close_container(); + self.screen = Screen::Playing; + self.capture(true); + } + } /// Menus opened by PlayerEffect::OpenMenu. fn open_menu(&mut self, pos: [i32; 3]) { let name = self @@ -2916,6 +2947,7 @@ impl Game<'_> { } if &*name == "minecraft:crafting_table" { self.craft_size = 3; + self.craft_table = Some(pos); } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); self.container_opener_event(key, true); @@ -5425,6 +5457,7 @@ impl Game<'_> { } } self.craft_size = 2; + self.craft_table = None; if let Some(key) = self.container.take() { self.container_opener_event(key, false); self.post_block_game_event( @@ -11746,6 +11779,7 @@ impl<'a> Game<'a> { carried: None, craft_grid: vec![None; 9], craft_size: 2, + craft_table: None, inv_drag: None, tweaks: Default::default(), inv_clicks: Default::default(), diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index 094aed6ef..dd3a95250 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -15,6 +15,7 @@ use horizon_world::registry::BlockStateId; impl Game<'_> { pub(super) fn tick_block_entities(&mut self) -> Result<()> { self.tick_mount_menu(); + self.tick_craft_table(); self.load_entity_types(); if !self.world.block_entities.has_states() { let states = self.ticking_states(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..d0d7bd7df 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -117,6 +117,7 @@ pub(super) struct GuestSwap { host_command_block: Option, host_mount_menu: super::mount_menu::MountMenu, craft_size: usize, + craft_table: Option<[i32; 3]>, craft_grid: Vec>, container: Option<(i32, i32, i32)>, mining: Option, @@ -307,6 +308,7 @@ impl Game<'_> { // The host's crafting grid stays theirs; a crafting table the guest // opens shows as the 3x3 size. let craft_size = std::mem::replace(&mut self.craft_size, 2); + let craft_table = self.craft_table.take(); let craft_grid = std::mem::replace(&mut self.craft_grid, vec![None; 9]); let container = self.container.take(); let mining = std::mem::replace(&mut self.mining, play.mining.take()); @@ -390,6 +392,7 @@ impl Game<'_> { host_command_block, host_mount_menu, craft_size, + craft_table, craft_grid, container, mining, @@ -445,6 +448,7 @@ impl Game<'_> { host_command_block, host_mount_menu, craft_size, + craft_table, craft_grid, container, mining, @@ -495,7 +499,10 @@ impl Game<'_> { // What the action opened: handed to the guest instead of the host. let opened = self.container.take(); - let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; + let guest_table = std::mem::replace(&mut self.craft_table, craft_table); + let opened_table = (std::mem::replace(&mut self.craft_size, craft_size) == 3) + .then_some(guest_table) + .flatten(); self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); let bed = std::mem::replace(&mut self.sleeping, sleeping); @@ -671,8 +678,8 @@ impl Game<'_> { if let Some(key) = guest_lectern { self.lan_open_lectern(host, conn, key); } - if opened_table { - self.lan_open_crafting(host, conn); + if let Some(pos) = opened_table { + self.lan_open_crafting(host, conn, pos); } if let Some(mob) = guest_mount { self.lan_open_mount(host, conn, mob); @@ -1238,7 +1245,7 @@ impl Game<'_> { /// cursor goes back into their inventory (`placeItemBackInInventory`, /// dropped only if it doesn't fit), and their client's cursor empties /// with the inventory it is sent. - fn guest_carried_back(&mut self, host: &mut LanHost, gi: usize) { + pub(super) fn guest_carried_back(&mut self, host: &mut LanHost, gi: usize) { if let Some(c) = host.hub.guests[gi].carried.take() { self.lan_place_back(host, gi, vec![c]); host.hub.send_inventory(gi); @@ -1680,6 +1687,7 @@ impl Game<'_> { pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); self.lan_stations_tick(host); + self.lan_tables_tick(host); self.tick_lan_mount_menus(host); self.announce_guest_advancements(host); let conns: Vec = host diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index cb3b0a2c9..dd51b2843 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -19,8 +19,8 @@ use horizon_protocol::packets::play::{self, Clientbound as C}; pub(super) struct GuestCrafting { /// The inventory menu; its grid lives in the hub's guest. inventory: Option>, - /// The open crafting table: its window, state id and menu. - table: Option<(i32, i32, Box)>, + /// The open crafting table: its window, state id, menu and block. + table: Option<(i32, i32, Box, [i32; 3])>, /// The open furnace's or brewing stand's window and menu (`AbstractFurnaceMenu`, /// `BrewingStandMenu`); its slots live in the block entity and the hub's /// container menu keeps the client in sync. @@ -383,17 +383,17 @@ impl Game<'_> { host.hub.send_inventory(gi); placed } else { - let Some((window, state, mut menu)) = host + let Some((window, state, mut menu, pos)) = host .play .get_mut(&conn) - .and_then(|play| play.crafting.table.take_if(|(w, _, _)| *w == p.container)) + .and_then(|play| play.crafting.table.take_if(|(w, ..)| *w == p.container)) else { return; }; let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { menu.place_recipe(env, &id, p.use_max, creative, None) }); - host.play.entry(conn).or_default().crafting.table = Some((window, state, menu)); + host.play.entry(conn).or_default().crafting.table = Some((window, state, menu, pos)); self.lan_send_table_content(host, conn); placed }; @@ -403,7 +403,7 @@ impl Game<'_> { } /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). - pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { + pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { self.lan_crafting_closed(host, conn, None); self.lan_station_closed(host, conn, None); // The container it replaces loses its opener. @@ -413,7 +413,7 @@ impl Game<'_> { return; }; let menu = Box::new(Menu::new(Kind::Crafting)); - host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu)); + host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu, pos)); self.lan_send_table_content(host, conn); } @@ -427,31 +427,72 @@ impl Game<'_> { let Some(play) = host.play.get_mut(&conn) else { return false; }; - let Some((window, state, mut menu)) = play + let Some((window, state, mut menu, pos)) = play .crafting .table - .take_if(|(window, _, _)| *window == p.container) + .take_if(|(window, ..)| *window == p.container) else { return false; }; + // A table that is no longer valid takes no clicks (handleContainerClick). if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) && !host.hub.guests[gi].spectator() + && self.lan_table_valid(&host.hub.guests[gi], pos) { self.guest_menu_op(host, gi, &mut menu, |menu, env| { let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); }); } - host.play.entry(conn).or_default().crafting.table = Some((window, state, menu)); + host.play.entry(conn).or_default().crafting.table = Some((window, state, menu, pos)); self.lan_send_table_content(host, conn); true } + /// `CraftingMenu.stillValid`: the block is still a crafting table and the + /// guest is within reach of it. + fn lan_table_valid(&self, g: &Guest, pos: [i32; 3]) -> bool { + let name = &self + .res + .facts() + .get(self.world.block(pos[0], pos[1], pos[2])) + .name; + &**name == "minecraft:crafting_table" && super::lan_stations::within_reach(g, pos) + } + + /// `ServerPlayer.tick`'s `stillValid`: a guest's crafting table closes + /// once it is gone or out of reach, giving its grid back. + pub(super) fn lan_tables_tick(&mut self, host: &mut LanHost) { + let invalid: Vec<(u32, i32)> = host + .play + .iter() + .filter_map(|(c, p)| p.crafting.table.as_ref().map(|t| (*c, t.0, t.3))) + .filter(|&(c, _, pos)| { + host.hub + .guests + .iter() + .find(|g| g.conn == c) + .is_some_and(|g| host.hub.here(g) && !self.lan_table_valid(g, pos)) + }) + .map(|(c, window, _)| (c, window)) + .collect(); + for (conn, window) in invalid { + self.lan_crafting_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) { + self.guest_carried_back(host, gi); + } + } + } + /// The whole crafting table menu for the client (`sendAllDataToRemote`). fn lan_send_table_content(&mut self, host: &mut LanHost, conn: u32) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; - let Some((window, state, menu)) = host + let Some((window, state, menu, _)) = host .play .get_mut(&conn) .and_then(|p| p.crafting.table.as_mut()) @@ -499,9 +540,9 @@ impl Game<'_> { } else { match crafting .table - .take_if(|(w, _, _)| window.is_none_or(|window| *w == window)) + .take_if(|(w, ..)| window.is_none_or(|window| *w == window)) { - Some((_, _, menu)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(), + Some((_, _, menu, _)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(), None => return false, } }; @@ -527,7 +568,7 @@ impl Game<'_> { let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; if let Some(play) = play { - if let Some((_, _, menu)) = play.crafting.table { + if let Some((_, _, menu, _)) = play.crafting.table { grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); } // A workstation's inputs too. From 467277ef6d70de648f45ce6c66409b28644d796e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:21:53 +0100 Subject: [PATCH 10/26] Update comparators when a guest changes a chest through its menu A container click from a server-thread or LAN player wrote the slots but never called BlockEntity.setChanged, so comparators kept the old output. Notify the block entity when the click changed the container's slots. --- crates/horizon-client/src/game/lan_actions.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..8da418271 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1075,7 +1075,20 @@ impl Game<'_> { } S::ContainerClick(p) => { let rules = ItemRules(self.res.items()); + let slots = host.hub.guests[gi] + .menu + .as_ref() + .filter(|m| m.window == p.container) + .map(|m| m.slots); + let before = slots.and_then(|s| s.read(&self.world, &host.hub.guests[gi])); let drops = host.hub.container_click(conn, &p, &mut self.world, &rules); + // A click that changed the container's slots: BlockEntity.setChanged, + // so comparators read it again (a double chest's other half follows). + if let Some(Slots::Block(key) | Slots::Double(key, _)) = slots + && slots.and_then(|s| s.read(&self.world, &host.hub.guests[gi])) != before + { + self.container_changed(key); + } self.drop_guest_items(host, gi, drops); } S::ContainerClose(p) => { From 3843a9a4aae425fa4ec4f759dc9e4e37a5c44abc Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:27:51 +0100 Subject: [PATCH 11/26] Use the team-formatted player name in chat Chat, /say, /me and /tell now name the sender the way Player.getDisplayName does: the team prefix, the name and the suffix in the team colour. On a server the hub gets the scoreboard's teams each tick; in-frame the existing player_display_name is used. --- crates/horizon-client/src/game/chat.rs | 2 +- crates/horizon-client/src/game/commands.rs | 8 +++---- crates/horizon-client/src/game/scoreboard.rs | 1 + crates/horizon-client/src/lan/hub.rs | 22 ++++++++++++++++++++ crates/horizon-client/src/lan/hub/chat.rs | 12 +++++------ 5 files changed, 34 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index ec85732ae..9fd3157c4 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -586,7 +586,7 @@ impl Game<'_> { } else { let line = Text::translate( "chat.type.text", - &[Text::literal(PLAYER_NAME), Text::literal(message)], + &[self.player_display_name(), Text::literal(message)], ); let focused = self.screen == Screen::Chat; let heard = self.mods.running().then(|| line.plain()); diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 19a16e261..b84f13e4a 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -214,7 +214,7 @@ impl Game<'_> { } /// Player.getDisplayName: the name (team-formatted), suggesting a /// `/tell`, showing the player on hover, inserting the name. - fn player_display_name(&self) -> Text { + pub(super) fn player_display_name(&self) -> Text { let name = self.acting_player_name().to_owned(); let Some(uuid) = self.lan_acting_uuid else { return self.target_name(Target::Player); @@ -2809,7 +2809,7 @@ impl Game<'_> { let name = match self.command_source.map(|s| s.entity) { Some(Some(t)) => self.target_name(t), Some(None) => Text::literal("Server"), - None => Text::literal(self.acting_player_name()), + None => self.player_display_name(), }; let line = match id { "say" => Text::translate("chat.type.announcement", &[name, message]), @@ -2819,14 +2819,14 @@ impl Game<'_> { // Whispering to yourself: the incoming and outgoing lines. let out = Text::translate( "commands.message.display.outgoing", - &[Text::literal(self.acting_player_name()), message.clone()], + &[self.player_display_name(), message.clone()], ) .with_color(text::GRAY) .italic(); self.system_message(out); Text::translate( "commands.message.display.incoming", - &[Text::literal(self.acting_player_name()), message], + &[self.player_display_name(), message], ) .with_color(text::GRAY) .italic() diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 227a09a6c..81c03e288 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -332,6 +332,7 @@ impl Game<'_> { return; } self.load_scoreboard(); + host.hub.teams.clone_from(&self.score.board.teams); let view = horizon_client::lan::scoreboard::View::of(&self.score.board); for g in host.hub.guests.iter_mut().filter(|g| g.placed) { if g.scoreboard != view { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c2a395899..fd2381596 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -149,6 +149,9 @@ pub struct Hub { pub singleplayer_owner: Option, /// Who rides what, set by the game before each tick. pub riding: super::entity::Riding, + /// The scoreboard's teams, set by the game each tick, for players' + /// display names. + pub teams: Vec, last_clock: i64, last_rate: f32, ticking: (f32, bool), @@ -206,6 +209,24 @@ pub fn display_name(uuid: u128, name: &str) -> Tag { ]) } +impl Hub { + /// Player.getDisplayName: the name formatted for the player's team + /// (PlayerTeam.formatNameForTeam), suggesting `/tell NAME `, showing the + /// player on hover and inserting the name. + pub fn player_display_name(&self, uuid: u128, name: &str) -> Tag { + let Some(team) = self.teams.iter().find(|t| t.players.contains(name)) else { + return display_name(uuid, name); + }; + let mut c = team.formatted_name_comp(&crate::scoreboard::literal(name)); + c["click_event"] = + serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}); + c["hover_event"] = serde_json::json!({"action": "show_entity", "id": "minecraft:player", + "uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}); + c["insertion"] = name.into(); + crate::scoreboard::component_tag(&c) + } +} + /// A yellow translation of player names (`multiplayer.player.joined`). fn yellow_names(key: &str, names: Vec) -> Tag { Tag::compound([ @@ -315,6 +336,7 @@ impl Hub { entity_types: Default::default(), entities: Default::default(), entity_out: Vec::new(), + teams: Vec::new(), } } diff --git a/crates/horizon-client/src/lan/hub/chat.rs b/crates/horizon-client/src/lan/hub/chat.rs index 7e75c84c5..bdc7c3fb2 100644 --- a/crates/horizon-client/src/lan/hub/chat.rs +++ b/crates/horizon-client/src/lan/hub/chat.rs @@ -2,7 +2,7 @@ //! handle it: chat sessions validated against the services' keys, signed //! messages checked link by link, the acknowledged window, and messages //! relayed with each connection's numbering and signature cache. -use super::{HostEvent, Hub, display_name}; +use super::{HostEvent, Hub}; use horizon_protocol::{ packets::play::{self, Clientbound as C}, secure_chat::{self, Body, Chain, ChatSession, DecodeError, ProfileKey, Signature, Unpacked}, @@ -214,7 +214,7 @@ impl Hub { } let bound = play::ChatTypeBound { chat_type: self.chat_type, - name: display_name(uuid, &name), + name: self.player_display_name(uuid, &name), target: None, }; let line = format!("<{name}> {}", message.content); @@ -427,7 +427,7 @@ impl Hub { let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone()); let bound = play::ChatTypeBound { chat_type: self.chat_type_id(chat_type), - name: display_name(uuid, &name), + name: self.player_display_name(uuid, &name), target: None, }; let line = match chat_type { @@ -467,15 +467,15 @@ impl Hub { self.chat_type_id("msg_command_incoming"), ); for &t in targets { - let target = display_name(self.guests[t].uuid, &self.guests[t].name); + let target = self.player_display_name(self.guests[t].uuid, &self.guests[t].name); let out = play::ChatTypeBound { chat_type: outgoing, - name: display_name(uuid, &name), + name: self.player_display_name(uuid, &name), target: Some(target), }; let inc = play::ChatTypeBound { chat_type: incoming, - name: display_name(uuid, &name), + name: self.player_display_name(uuid, &name), target: None, }; match &message { From 13e83e4e63e13752978d552980b997573013fea4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:36:01 +0100 Subject: [PATCH 12/26] Read saved attribute bases for every mob LivingEntity.readAdditionalSaveData applies the attributes list for any living entity, then sets the health (the max health when none is saved). Only horses read max_health and movement_speed, so a summoned cow kept its type defaults. Read max_health, movement_speed and attack_damage for all mobs before the health; horses still read jump_strength. --- crates/horizon-client/src/entity_nbt.rs | 26 +++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index bf0764a6b..00576ea02 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -617,9 +617,23 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.head_pitch = pitch; m.on_ground = flag(tag, "OnGround"); m.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0); - if let Some(h) = float(tag.get("Health")) { - m.health = h as f32; + // LivingEntity.readAdditionalSaveData: the saved attribute bases, then + // the health, the max health when there is none. + if let Some(Tag::List(attrs)) = tag.get("attributes") { + for a in attrs { + let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else { + continue; + }; + let v = f64::from_bits(*bits); + match id.as_str() { + "minecraft:max_health" => m.attrs.max_health = v as f32, + "minecraft:movement_speed" => m.attrs.speed = v, + "minecraft:attack_damage" => m.attrs.attack_damage = v as f32, + _ => {} + } + } } + m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. if let Some(eq) = tag.get("equipment") { @@ -735,12 +749,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else { continue; }; - let v = f64::from_bits(*bits); - match id.as_str() { - "minecraft:max_health" => m.attrs.max_health = v as f32, - "minecraft:movement_speed" => m.attrs.speed = v, - "minecraft:jump_strength" => m.extra.vector[0] = v, - _ => {} + if id == "minecraft:jump_strength" { + m.extra.vector[0] = f64::from_bits(*bits); } } } From 0481dbdb81e49134f42dccafb58474504466a440 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:10:56 +0100 Subject: [PATCH 13/26] Make hardcore players spectators when they respawn A hardcore death offered another survival life. Vanilla's death screen says Spectate in hardcore, and the server makes the respawned player a spectator (ServerGamePacketListenerImpl.handleClientCommand). Do the same on the server and in the in-frame world, and add a harness that compares a hardcore respawn on a dedicated server with vanilla's. --- crates/horizon-client/src/game/agent.rs | 8 +- crates/horizon-client/src/game/lan_actions.rs | 5 + crates/horizon-client/src/game/screens.rs | 27 +++- .../horizonlab/parity/LocatorBarClient.java | 6 +- tools/test_hardcore_respawn_parity.py | 139 ++++++++++++++++++ 5 files changed, 177 insertions(+), 8 deletions(-) create mode 100644 tools/test_hardcore_respawn_parity.py diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index f6b68aa74..b85710146 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1598,8 +1598,12 @@ impl Game<'_> { if self.screen != Screen::Dead { return Err("respawn needs the death screen".into()); } - let label = - horizon_client::text::Text::translate("deathScreen.respawn", &[]).plain(); + let key = if self.level.hardcore { + "deathScreen.spectate" + } else { + "deathScreen.respawn" + }; + let label = horizon_client::text::Text::translate(key, &[]).plain(); let w = widgets::find(&widgets::last(), &label)?; if !w.enabled { // DeathScreen enables its buttons after 20 ticks. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..2942bea7d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1649,6 +1649,11 @@ impl Game<'_> { border: &self.border, }; host.hub.respawn(i, spawn, &ctx); + // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's + // respawned player only watches. + if self.level.hardcore { + host.hub.set_game_mode(conn, SPECTATOR); + } if let Some(config) = elsewhere { self.respawn_trip(conn, config); } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index cf1f3269f..5fa040665 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -2,6 +2,7 @@ use super::{Game, Screen}; use horizon_client::{ Result, + command::args::GameMode, hud::{HudBatch, rgba}, text::{self, Text}, ui, @@ -81,9 +82,15 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { (x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"), ] } -fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] { +/// DeathScreen.init: a hardcore player can only spectate. +fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8); 2] { + let respawn = if hardcore { + "deathScreen.spectate" + } else { + "deathScreen.respawn" + }; [ - (w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0), + (w / 2.0 - 100.0, h / 4.0 + 72.0, respawn, 0), ( w / 2.0 - 100.0, h / 4.0 + 96.0, @@ -223,7 +230,12 @@ impl Game<'_> { ), ); } - let title = Text::translate("deathScreen.title", &[]); + let title = if self.level.hardcore { + "deathScreen.title.hardcore" + } else { + "deathScreen.title" + }; + let title = Text::translate(title, &[]); let tw = atlas.font.width_text(&title); ui::text_scaled( batch, @@ -258,7 +270,7 @@ impl Game<'_> { .ui .died_at .is_none_or(|t| t.elapsed().as_millis() >= 1000); - for (x, y, key, _) in death_buttons(w, h) { + for (x, y, key, _) in death_buttons(w, h, self.level.hardcore) { let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0); ui::button( batch, @@ -286,7 +298,7 @@ impl Game<'_> { .as_ref() .map_or([1, 1], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let hit = death_buttons(b.width, b.height) + let hit = death_buttons(b.width, b.height, self.level.hardcore) .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); @@ -330,6 +342,11 @@ impl Game<'_> { Some(1) => self.close_world()?, _ => {} } + // ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's + // respawned player only watches. + if hit == Some(0) && self.remote.is_none() && self.level.hardcore { + self.set_mode(GameMode::Spectator); + } if hit.is_some() { self.audio.play_button_click(); } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index 76a951894..3bed808f6 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -84,7 +84,9 @@ import net.minecraft.world.phys.Vec3; * still), {@code sync NAME} (runs {@code time query gametime}, whose reply is * not recorded, and prints {@code synced NAME} once it is back: the server has * handled everything this player sent before, and everything the server sent - * this player before the reply has been recorded), {@code quit NAME}, {@code + * this player before the reply has been recorded), {@code respawn NAME} (the + * death screen's button, ServerboundClientCommandPacket PERFORM_RESPAWN), + * {@code quit NAME}, {@code * players on|off} (whether each player also records the other players added * to and removed from its level, and its own respawns into a dimension), * {@code chat on|off} (whether the system chat each player receives is @@ -130,6 +132,8 @@ public final class LocatorBarClient { players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } case "still" -> players.get(w[1]).still(); + case "respawn" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket( + net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN)); case "sync" -> { try { players.get(w[1]).sync(); diff --git a/tools/test_hardcore_respawn_parity.py b/tools/test_hardcore_respawn_parity.py new file mode 100644 index 000000000..6e0669534 --- /dev/null +++ b/tools/test_hardcore_respawn_parity.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Respawning in a hardcore world on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one hardcore +flat world vanilla generated first, with Alice an operator in survival. LocatorBarClient (a player made of +vanilla's protocol code) joins, runs /kill on itself and presses the death screen's button +(ServerboundClientCommandPacket PERFORM_RESPAWN). Vanilla's ServerGamePacketListenerImpl.handleClientCommand +respawns the player, then makes it a spectator because the server is hardcore. The game mode changes and respawns +Alice is sent in the death and respawn steps are compared exactly. +""" +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base, test_locator_bar_parity as locator + from .test_dedicated_server_parity import Server +except ImportError: + import lab + import test_rust_parity as base + import test_locator_bar_parity as locator + from test_dedicated_server_parity import Server + +NAME = 'hardcore-respawn-parity' +# server_dir and generate_world write these server.properties. +locator.PROPERTIES = dict(locator.PROPERTIES, hardcore='true', gamemode='survival') +SCRIPT = [ + ('death', ['cmd Alice kill @s']), + ('respawn', ['respawn Alice']), +] +STEP_SECONDS = 4.0 +SHOWN = ('gamemode', 'respawn') + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = locator.server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('state on') + tell('step joins') + tell('join Alice') + server.wait_for(r'Alice joined the game', timeout=120) + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +def shown(lines): + """Alice's game mode changes and respawns in the death and respawn steps.""" + keep = [] + for line in lines: + parts = line.split(' ', 3) + if len(parts) >= 3 and parts[1] in ('step=death', 'step=respawn') and parts[2] in SHOWN: + keep.append(line) + return keep + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = locator.generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if 'Alice step=respawn gamemode 3' not in vanilla: + raise AssertionError(f'vanilla did not make the respawned player a spectator: the script did not run ' + f'(see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='A player dying and respawning in a hardcore world on a dedicated server: the respawn and the game ' + 'mode it is sent (spectator).')) + print(f'hardcore respawn: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From f48cfb79661b9181ed62435e5009f1cd2bfc0543 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:48:47 +0100 Subject: [PATCH 14/26] Let /ride mount and dismount mob riders /ride now looks up a mob's vehicle as well as the player's, so mobs can mount mobs, get the already-riding and loop errors, and dismount to the vehicle's dismount spot. execute on vehicle uses the same lookup. The command_exec corpus gets a mob riding group. --- .../src/game/commands/execute.rs | 5 +- .../src/game/commands/world_cmds.rs | 88 +++++++++++++++---- tools/command_exec_corpus.py | 26 ++++++ 3 files changed, 100 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 463cd542e..3f7e4c2a0 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -606,10 +606,7 @@ impl Game<'_> { .collect(), _ => Vec::new(), }, - Some("vehicle") => match entity { - Target::Player => self.riding.map(Target::Mob).into_iter().collect(), - _ => Vec::new(), - }, + Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(), Some("controller") | Some("passengers") => match entity { Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => { vec![Target::Player] diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 2f3792a57..c8bd220be 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -1074,15 +1074,15 @@ impl Game<'_> { }; let name = self.target_name(target); if id == "ride.dismount" { - let vehicle = match target { - Target::Player => self.riding.map(Target::Mob), - _ => None, - }; - let Some(v) = vehicle else { + let Some(v) = self.ride_vehicle(target) else { return Err(err("commands.ride.not_riding", &[&name.plain()])); }; let vehicle_name = self.target_name(v); - self.dismount_mount(); + match target { + Target::Player => self.dismount_mount(), + Target::Mob(rider) => self.dismount_mob(rider), + _ => {} + } self.feedback(Text::translate( "commands.ride.dismount.success", &[name, vehicle_name], @@ -1094,11 +1094,8 @@ impl Game<'_> { return Ok(0); }; let vehicle_name = self.target_name(vehicle); - if target == Target::Player && self.riding.is_some() { - let current = self - .riding - .map(Target::Mob) - .map_or_else(Text::empty, |v| self.target_name(v)); + if let Some(current) = self.ride_vehicle(target) { + let current = self.target_name(current); return Err(err( "commands.ride.already_riding", &[&name.plain(), ¤t.plain()], @@ -1107,22 +1104,42 @@ impl Game<'_> { if vehicle == Target::Player { return Err(err("commands.ride.mount.failure.cant_ride_players", &[])); } - if target == vehicle { - return Err(err("commands.ride.mount.failure.loop", &[])); + // getSelfAndPassengers: the vehicle is the target or rides it. + let mut up = Some(vehicle); + while let Some(v) = up { + if v == target { + return Err(err("commands.ride.mount.failure.loop", &[])); + } + up = self.ride_vehicle(v); } - // The player can ride mobs that carry a rider. + // Players and mobs can ride mobs. let Target::Mob(mob_id) = vehicle else { return Err(err( "commands.ride.mount.failure.generic", &[&name.plain(), &vehicle_name.plain()], )); }; - if target != Target::Player || !self.mobs.iter().any(|m| m.id == mob_id && m.alive()) { + let rider = match target { + Target::Mob(id) => Some(id), + _ => None, + }; + if !(target == Target::Player || rider.is_some()) + || !self.mobs.iter().any(|m| m.id == mob_id && m.alive()) + { return Err(err( "commands.ride.mount.failure.generic", &[&name.plain(), &vehicle_name.plain()], )); } + if let Some(rider) = rider { + // Entity.startRiding. + self.mount_mob(rider, mob_id); + self.feedback(Text::translate( + "commands.ride.mount.success", + &[name, vehicle_name], + )); + return Ok(1); + } if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) { m.extra.flag = false; m.extra.counter = 0; @@ -1138,6 +1155,47 @@ impl Game<'_> { Ok(1) } + /// Entity.getVehicle: the player's mount, or a mob's. + pub(super) fn ride_vehicle(&self, t: Target) -> Option { + let id = match t { + Target::Player => return self.riding.map(Target::Mob), + Target::Mob(id) => self.mobs.iter().find(|m| m.id == id)?.extra.mount?, + _ => return None, + }; + Some(if self.boats.iter().any(|b| b.id == id) { + Target::Boat(id) + } else { + Target::Mob(id) + }) + } + /// LivingEntity.stopRiding for a mob: off its vehicle + /// (Entity.removePassenger), then to where the vehicle lets it out + /// (LivingEntity.dismountVehicle). + fn dismount_mob(&mut self, rider: u32) { + let Some(i) = self.mobs.iter().position(|m| m.id == rider) else { + return; + }; + let Some(v) = self.mobs[i].extra.mount.take() else { + return; + }; + let (width, yaw) = (f64::from(self.mobs[i].width()), self.mobs[i].yaw); + let at = if let Some(b) = self.boats.iter().position(|b| b.id == v) { + self.boat_dismount_target(b, width, yaw) + } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == v) { + m.extra.rider = None; + // Entity.getDismountLocationForPassenger: on top of the vehicle. + let p = m.position; + horizon_core::geometry::Vec3::new(p.x, p.y + f64::from(m.height()), p.z) + } else { + self.mobs[i].position + }; + let m = &mut self.mobs[i]; + m.extra.passenger = false; + m.extra.boarding_cooldown = 60; + m.position = at; + m.previous = at; + } + // ---- /spreadplayers ----------------------------------------------------------------------- pub(super) fn cmd_spreadplayers(&mut self, ctx: &Context) -> R { diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 0e376e260..ba03fc817 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -327,6 +327,31 @@ def riding_teleport(): '/tp @s 8.5 230 8.5 0 0') +def mob_riding(): + """Mobs mount and dismount mobs with /ride, NBT passengers included (#1520).""" + rider, vehicle = '@e[tag=ride_r,limit=1]', '@e[tag=ride_v,limit=1]' + return [ + *setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"]}', + '/summon minecraft:pig 6.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_r"]}'), + cmd(f'/ride {rider} dismount'), + cmd(f'/ride {rider} mount @s'), + cmd(f'/ride {rider} mount {rider}'), + cmd(f'/ride {rider} mount {vehicle}'), + cmd(f'/ride {rider} mount {vehicle}'), + cmd(f'/ride {vehicle} mount {rider}'), + cmd('/execute as @e[tag=ride_r] on vehicle run say carrying'), + cmd(f'/ride {rider} dismount'), + cmd(f'/data get entity {rider} Pos'), + cmd('/execute as @e[tag=ride_r] on vehicle run say still carrying'), + *setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'), + *setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"],' + 'Passengers:[{id:"minecraft:pig",NoAI:1b,NoGravity:1b,Tags:["ride_r"]}]}'), + cmd(f'/ride {rider} dismount'), + cmd(f'/data get entity {rider} Pos'), + *setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'), + ] + + def scores(): return [ cmd('/scoreboard objectives add harness dummy'), @@ -1017,6 +1042,7 @@ def groups(): ('blocks and border', world_blocks()), ('entities', entities()), ('riding teleport', riding_teleport()), + ('mob riding', mob_riding()), ('scores, teams and bossbars', scores()), ('execute', execute()), ('levels', levels()), From 436c2fefb47d16e33b0e13ad2218dc731ec43afe Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:40:05 +0100 Subject: [PATCH 15/26] Freeze server-thread players in powder snow With the server thread, the host's copy of a player never set isInPowderSnow from the blocks along its moves and never ran LivingEntity.aiStep's freezing, so a frozen player took no freezing damage and the client's own damage was overwritten. Record powder snow's FREEZE on the server path and run the freezing countdown and its damage every 40 ticks there. The guest's freeze-immune armor now comes from its worn armor, as for the local player. --- crates/horizon-client/src/game.rs | 24 ++++++++++-------- crates/horizon-client/src/game/lan_actions.rs | 2 ++ crates/horizon-client/src/motion.rs | 25 ++++++++++++++++--- 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..4e4865c7a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1844,6 +1844,19 @@ impl Game<'_> { /// (decreaseAirSupply), the wings, leather boots on powder snow /// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA. + /// `LivingEntity.canFreeze`'s armor half: any worn piece in + /// `freeze_immune_wearables`. + pub(crate) fn wears_freeze_immune(&self) -> bool { + let immune = self + .res + .items() + .item_tags + .get("minecraft:freeze_immune_wearables"); + self.armor + .iter() + .flatten() + .any(|s| immune.is_some_and(|t| t.contains(&*s.item))) + } pub(crate) fn sync_player_body(&mut self) { let glider = self.glider_worn(); let item_use_speed = self @@ -1863,16 +1876,7 @@ impl Game<'_> { let leather_boots = self.armor[3] .as_ref() .is_some_and(|s| &*s.item == "minecraft:leather_boots"); - let immune = self - .res - .items() - .item_tags - .get("minecraft:freeze_immune_wearables"); - let freeze_immune = self - .armor - .iter() - .flatten() - .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); + let freeze_immune = self.wears_freeze_immune(); let Some(player) = self.player.as_mut() else { return; }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..10307dca3 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1942,6 +1942,7 @@ impl Game<'_> { let events = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; + let freeze_immune = game.wears_freeze_immune(); let Some(player) = game.player.as_mut() else { return (Vec::new(), None); }; @@ -2005,6 +2006,7 @@ impl Game<'_> { // Entity.applyEffectsFromBlocks along those moves: magma, cactus, // lit campfires and grown sweet berry bushes hurt (#1305). w.player.shift_key_down = sneaking; + w.player.freeze_immune = freeze_immune; let _ = w.server_block_damage(start); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 560cadc80..e7809055d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1083,11 +1083,26 @@ impl MotionWorld<'_, '_, '_> { } /// 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. + /// magma, cactus, lit campfires and grown sweet berry bushes, and powder + /// snow's FREEZE, then `LivingEntity.aiStep`'s freezing and its damage. + /// 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) + // Entity.baseTick + self.player.was_in_powder_snow = self.player.in_powder_snow; + self.player.in_powder_snow = false; + self.effects_from_blocks(true)?; + // LivingEntity.aiStep "freezing" (server). + if !self.player.in_powder_snow || !self.player.can_freeze() { + self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0); + } + if self.player.health.tick_count % 40 == 0 + && self.player.is_fully_frozen() + && self.player.can_freeze() + { + self.freeze_damage()?; + } + Ok(()) } fn effects_from_blocks(&mut self, damage_only: bool) -> Result<()> { use horizon_world::entity_move::MovementRecord; @@ -1191,7 +1206,7 @@ impl MotionWorld<'_, '_, '_> { groups += 1; last_step = step; } - if groups == 1 { + if groups == 1 && !damage_only { // A later group finds the fire already out. self.player.powder_snow_entered.push(p); } @@ -1316,6 +1331,8 @@ impl MotionWorld<'_, '_, '_> { "minecraft:sweet_berry_bush" if damage_only => { self.sweet_berry_bush_damage(state)?; } + // PowderSnowBlock.entityInside's FREEZE. + "minecraft:powder_snow" if damage_only => entered.push((step, p)), _ => {} } if damage_only { From 10efca9e6cd922ff7b9a4a3cc3f5a467e97f52f2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:40:29 +0100 Subject: [PATCH 16/26] Discard a dead player's ender pearl when the rule says so With ender_pearls_vanish_on_death on, a pearl thrown just before death kept flying and pulled the respawned player back to it. Vanilla's ThrownEnderpearl.tick discards the pearl instead of ticking it while its owner is dead. Add a harness that throws a pearl, dies and respawns on a dedicated server and compares the teleports with vanilla's. --- crates/horizon-client/src/game/creatures.rs | 19 +++ .../horizonlab/parity/LocatorBarClient.java | 15 +- tools/test_pearl_death_parity.py | 142 ++++++++++++++++++ 3 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 tools/test_pearl_death_parity.py diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0bb7bbe85..ff07e9011 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1694,7 +1694,26 @@ impl Game<'_> { targets: targets_guests, }; let guest_entities = self.lan_guest_entities(); + // ThrownEnderpearl.tick: a dead player's pearl is discarded in + // place of its tick while ender_pearls_vanish_on_death is on. + let vanish = self.ui.rules.bool("ender_pearls_vanish_on_death"); + let host_dead = self.player_view().is_some_and(|p| !p.alive); + let dead_guests: Vec = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| g.dead) + .map(|g| g.conn) + .collect() + }); projectiles.retain_mut(|p| { + if vanish + && matches!(p.kind, ProjectileKind::EnderPearl) + && p.owner == Some(Who::Player) + && p.guest.map_or(host_dead, |c| dead_guests.contains(&c)) + { + return false; + } let mob_shot = !matches!(p.owner, Some(Who::Player)); // A player's arrows, snowballs and eggs meet every player; a // guest's flies from that guest (Projectile.getOwner), not diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index 76a951894..818746336 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -84,7 +84,10 @@ import net.minecraft.world.phys.Vec3; * still), {@code sync NAME} (runs {@code time query gametime}, whose reply is * not recorded, and prints {@code synced NAME} once it is back: the server has * handled everything this player sent before, and everything the server sent - * this player before the reply has been recorded), {@code quit NAME}, {@code + * this player before the reply has been recorded), {@code respawn NAME} (the + * death screen's button, ServerboundClientCommandPacket PERFORM_RESPAWN), + * {@code use NAME PITCH} (the main hand's item used looking that way, + * ServerboundUseItemPacket), {@code quit NAME}, {@code * players on|off} (whether each player also records the other players added * to and removed from its level, and its own respawns into a dimension), * {@code chat on|off} (whether the system chat each player receives is @@ -130,6 +133,9 @@ public final class LocatorBarClient { players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } case "still" -> players.get(w[1]).still(); + case "respawn" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket( + net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN)); + case "use" -> players.get(w[1]).use(Float.parseFloat(w[2])); case "sync" -> { try { players.get(w[1]).sync(); @@ -250,6 +256,13 @@ public final class LocatorBarClient { } } + private int sequence; + + void use(float pitch) throws Exception { + send(new net.minecraft.network.protocol.game.ServerboundUseItemPacket( + net.minecraft.world.InteractionHand.MAIN_HAND, ++sequence, position.yRot(), pitch)); + } + void still() throws Exception { PositionMoveRotation at = position; // A tick of its own: the server takes one position per client tick (receivedPositionThisTick). diff --git a/tools/test_pearl_death_parity.py b/tools/test_pearl_death_parity.py new file mode 100644 index 000000000..a6795c749 --- /dev/null +++ b/tools/test_pearl_death_parity.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""An ender pearl in flight when its thrower dies, on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world +vanilla generated first, with Alice an operator in survival. LocatorBarClient (a player made of vanilla's protocol +code) throws an ender pearl straight up (ServerboundUseItemPacket), runs /kill on itself while the pearl flies, +presses the death screen's button (PERFORM_RESPAWN) and waits for the pearl to come down, with the rule +ender_pearls_vanish_on_death true: ThrownEnderpearl.tick discards a dead owner's pearl, so the respawned player is +never teleported. The teleports, game mode changes and respawns Alice is sent from the throw on are compared +exactly. +""" +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base, test_locator_bar_parity as locator + from .test_dedicated_server_parity import Server +except ImportError: + import lab + import test_rust_parity as base + import test_locator_bar_parity as locator + from test_dedicated_server_parity import Server + +NAME = 'pearl-death-parity' +# server_dir and generate_world write these server.properties. +locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival') +STEP_SECONDS = 4.0 +SHOWN = ('teleport', 'gamemode', 'respawn') + + +SCRIPT = [ + ('setup', ['cmd Alice gamerule ender_pearls_vanish_on_death true', 'cmd Alice give @s minecraft:ender_pearl']), + # Straight up: it comes down about four seconds later, near where it was thrown. + ('throw', ['use Alice -90', 'cmd Alice kill @s']), + ('respawn', ['respawn Alice']), + ('landed', []), +] + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = locator.server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('state on') + tell('step joins') + tell('join Alice') + server.wait_for(r'Alice joined the game', timeout=120) + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +def shown(lines): + """Alice's teleports, game mode changes and respawns from the throws on.""" + steps = {f'step={step}' for step, _ in SCRIPT if step != 'setup'} + return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 and parts[1] in steps + and parts[2] in SHOWN] + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = locator.generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + killed = any(l.startswith('Alice step=throw killed') for l in vanilla_all) + if not killed or 'Alice step=respawn respawn minecraft:overworld' not in vanilla: + raise AssertionError(f'vanilla did not kill and respawn Alice: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='An ender pearl in flight when its thrower dies and respawns on a dedicated server, with ' + 'ender_pearls_vanish_on_death true: the pearl vanishes and never teleports the player.')) + print(f'pearl death: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From 0c017678eb50c5819f0e2948f3f8432093e027ac Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:44:16 +0100 Subject: [PATCH 17/26] Keep shulker boxes out of shulker boxes on the server ShulkerBoxSlot.mayPlace refuses items that cannot fit inside container items, which BlockItem says of every shulker box. The server's menus for guests treated a shulker box's slots like a chest's, so with the server thread a shulker box could be clicked, shift-clicked or swapped into another. Apply the slot rule when the open menu is a shulker box. --- crates/horizon-client/src/lan/containers.rs | 9 +++++++++ crates/horizon-client/src/lan/menu.rs | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index d43cb5c27..3dc085a6d 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -344,6 +344,14 @@ impl Hub { return Vec::new(); } let source = self.guests[i].menu.as_ref().map(|m| m.slots); + let shulker_box = self + .sync + .builtin + .get("minecraft:menu") + .and_then(|m| m.id("minecraft:shulker_box")); + let shulker = in_menu + && shulker_box.is_some() + && self.guests[i].menu.as_ref().map(|m| m.kind) == shulker_box; let mut drag = if in_menu { self.guests[i].menu.as_mut().and_then(|m| m.drag.take()) } else { @@ -357,6 +365,7 @@ impl Hub { let mut view = View { guest, container: items.as_deref_mut(), + shulker, }; let (drops, changed) = menu::click( &mut view, diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index de9fb9608..fefcb1933 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -111,6 +111,8 @@ pub struct View<'a> { pub guest: &'a mut Guest, /// The container's slots, or None for the inventory menu. pub container: Option<&'a mut [Option]>, + /// The container is a shulker box (`ShulkerBoxSlot`). + pub shulker: bool, } impl View<'_> { @@ -153,6 +155,14 @@ impl View<'_> { if self.container.is_none() && (5..=8).contains(&i) { return rules.armor_index(&stack.item) == Some(i - 5); } + // ShulkerBoxSlot.mayPlace: Item.canFitInsideContainerItems, false + // for shulker boxes. + if self.shulker + && self.container.as_ref().is_some_and(|c| i < c.len()) + && stack.item.ends_with("shulker_box") + { + return false; + } self.enabled(i) } fn slot_max(&self, i: usize, stack: &ItemStack, rules: &dyn Rules) -> u32 { @@ -704,6 +714,7 @@ mod tests { let mut view = View { guest: &mut g, container: Some(&mut chest), + shulker: false, }; view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1)); // Left click with the bundle: the stone goes in. From 5bfc649edd18aaf9738dc428bc24ae9e991cf87d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:52:29 +0100 Subject: [PATCH 18/26] Drop the cursor stack of a dead player A stack held on the inventory cursor at death stayed there through the respawn, even with keep_inventory off. In vanilla the dead player is removed 20 ticks after dying (or when it respawns sooner), and Player.remove's inventoryMenu.removed drops what the cursor held where the player died. Do the same for server players and the in-frame player, and add a harness that dies with a cursor stack on a dedicated server and compares with vanilla. --- crates/horizon-client/src/game.rs | 20 ++- crates/horizon-client/src/game/chat.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 27 +++- crates/horizon-client/src/lan/guest.rs | 3 + .../horizonlab/parity/LocatorBarClient.java | 10 +- tools/test_cursor_death_parity.py | 143 ++++++++++++++++++ 6 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 tools/test_cursor_death_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..667eff52a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2173,6 +2173,11 @@ impl Game<'_> { // Player.drop: the drop statistics. self.stats.add("dropped", &thrown.item, thrown.count as i32); self.stats.custom("drop", 1); + self.throw_from_eyes(thrown, eye); + } + /// `Player.createItemStackToDrop`: an item entity thrown from the eyes + /// along the view direction. + fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) { let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -4335,7 +4340,8 @@ impl Game<'_> { // Out of the world. let _ = player.set_health(0.0, false); } - if player.health.dead_or_dying() && self.screen != Screen::Dead { + let dead = player.health.dead_or_dying(); + if dead && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. let feet = [player.position.x, player.position.y, player.position.z]; let at = [feet[0], feet[1] + 1.32, feet[2]]; @@ -4369,6 +4375,18 @@ impl Game<'_> { } self.screen = Screen::Dead; self.capture(false); + self.ui.death_time = 0; + } else if dead { + // LivingEntity.tickDeath: 20 ticks after dying the player is + // removed, and Player.remove's inventoryMenu.removed drops what + // the cursor held. + self.ui.death_time += 1; + if self.ui.death_time >= 20 + && let Some(stack) = self.carried.take() + && let Some(eye) = self.eye_position() + { + self.throw_from_eyes(stack, eye); + } } self.tick_world(running) } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index ec85732ae..15e34bbb6 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -99,6 +99,8 @@ pub struct UiState { /// Death screen cause and when the player died (buttons wait 20 ticks). pub death_text: Option, pub died_at: Option, + /// `LivingEntity.deathTime` of the window's player: ticks since it died. + pub death_time: u32, } impl Game<'_> { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..de6ae51dc 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1234,6 +1234,24 @@ impl Game<'_> { Some(out) } + /// `LivingEntity.tickDeath`: 20 ticks after dying the player is removed, + /// and `Player.remove`'s `inventoryMenu.removed` drops what the cursor + /// held (`dropOrPlaceInInventory` for a removed player). Respawning + /// sooner removes it too. + fn guest_tick_death(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.death_time += 1; + if g.death_time >= 20 { + self.guest_drop_carried(host, gi); + } + } + + fn guest_drop_carried(&mut self, host: &mut LanHost, gi: usize) { + if let Some(c) = host.hub.guests[gi].carried.take() { + self.drop_guest_items(host, gi, vec![c]); + } + } + /// `AbstractContainerMenu.removed`: what a closing player held on the /// cursor goes back into their inventory (`placeItemBackInInventory`, /// dropped only if it doesn't fit), and their client's cursor empties @@ -1573,6 +1591,8 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } + // PlayerList.respawn removes the dead player (Player.remove). + self.guest_drop_carried(host, i); // PlayerList.respawn: a server's player comes back in its respawn // point's level: the Overworld, where the world spawn and beds are, // or another one's anchor or forced point, which its block resolves @@ -1613,6 +1633,7 @@ impl Game<'_> { } let g = &mut host.hub.guests[i]; g.dead = false; + g.death_time = 0; g.health = 20.0; g.food = 20; g.saturation = 5.0; @@ -1694,7 +1715,11 @@ impl Game<'_> { continue; }; self.guest_sleep_tick(host, gi); - if host.hub.guests[gi].dead || self.on_server_trip(conn) { + if host.hub.guests[gi].dead { + self.guest_tick_death(host, gi); + continue; + } + if self.on_server_trip(conn) { continue; } let play = host.play.entry(conn).or_default(); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 440b58284..70510a5b4 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -223,6 +223,8 @@ pub struct Guest { /// Whether the guest was on the ground before the first of `moves`. pub moves_from_ground: bool, pub dead: bool, + /// `LivingEntity.deathTime`: ticks since the guest died. + pub death_time: u32, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, /// The level the player is in (`ServerPlayer.level().dimension()`): the @@ -349,6 +351,7 @@ impl Guest { moves: Vec::new(), moves_from_ground: false, dead: false, + death_time: 0, placed: false, dimension: "minecraft:overworld".into(), menu: None, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index 76a951894..e4aeef25e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -84,7 +84,10 @@ import net.minecraft.world.phys.Vec3; * still), {@code sync NAME} (runs {@code time query gametime}, whose reply is * not recorded, and prints {@code synced NAME} once it is back: the server has * handled everything this player sent before, and everything the server sent - * this player before the reply has been recorded), {@code quit NAME}, {@code + * this player before the reply has been recorded), {@code respawn NAME} (the + * death screen's button, ServerboundClientCommandPacket PERFORM_RESPAWN), + * {@code pickup NAME SLOT} (a left click on that slot of the player's + * inventory menu, claiming nothing), {@code quit NAME}, {@code * players on|off} (whether each player also records the other players added * to and removed from its level, and its own respawns into a dimension), * {@code chat on|off} (whether the system chat each player receives is @@ -130,6 +133,11 @@ public final class LocatorBarClient { players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } case "still" -> players.get(w[1]).still(); + case "respawn" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket( + net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN)); + case "pickup" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundContainerClickPacket( + 0, 0, Short.parseShort(w[2]), (byte) 0, net.minecraft.world.inventory.ContainerInput.PICKUP, + new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(), net.minecraft.network.HashedStack.EMPTY)); case "sync" -> { try { players.get(w[1]).sync(); diff --git a/tools/test_cursor_death_parity.py b/tools/test_cursor_death_parity.py new file mode 100644 index 000000000..8da944350 --- /dev/null +++ b/tools/test_cursor_death_parity.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""What a player holds on the cursor when they die, on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world +vanilla generated first, with Alice an operator in survival and keep_inventory off. LocatorBarClient (a player made +of vanilla's protocol code) is given seven diamonds, picks them up onto its inventory menu's cursor (a PICKUP click) +ten blocks from the spawn, runs /kill on itself, waits on the death screen and respawns (PERFORM_RESPAWN). Twenty +ticks after dying vanilla removes the dead player (LivingEntity.tickDeath), and Player.remove's +inventoryMenu.removed drops the cursor's stack where it died. Alice then asks whether an item lies around the death +site; the reply, and the inventory slots, respawns and teleports she is sent from the death on, are compared +exactly. +""" +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base, test_locator_bar_parity as locator + from .test_dedicated_server_parity import Server +except ImportError: + import lab + import test_rust_parity as base + import test_locator_bar_parity as locator + from test_dedicated_server_parity import Server + +NAME = 'cursor-death-parity' +# server_dir and generate_world write these server.properties. +locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival') +SCRIPT = [ + ('setup', ['cmd Alice gamerule keep_inventory false', 'cmd Alice clear @s', + 'cmd Alice give @s minecraft:diamond 7', 'cmd Alice tp @s 10.5 -60 0.5']), + # Hotbar slot 0 is the inventory menu's slot 36. + ('pickup', ['pickup Alice 36']), + ('death', ['cmd Alice kill @s']), + ('respawn', ['respawn Alice']), + ('check', ['chat Alice on', + 'cmd Alice execute if entity @e[type=minecraft:item,x=10.5,y=-60,z=0.5,distance=..4]']), +] +STEP_SECONDS = 4.0 +SHOWN = ('slot', 'inventory', 'respawn', 'teleport', 'chat') + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = locator.server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('state on') + tell('step joins') + tell('join Alice') + server.wait_for(r'Alice joined the game', timeout=120) + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action.replace('chat Alice', 'chat')) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +def shown(lines): + """Alice's slots, respawns, teleports and chat from the death on.""" + steps = {'step=death', 'step=respawn', 'step=check'} + return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 and parts[1] in steps + and parts[2] in SHOWN] + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = locator.generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if not any(l.startswith('Alice step=check chat') for l in vanilla): + raise AssertionError(f'vanilla answered no check command: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='A player dying with a stack on the inventory menu cursor (keep_inventory off) and respawning on a ' + 'dedicated server: the stack is dropped where it died, not kept.')) + print(f'cursor death: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From 6d3cd330d1f9b24b560c19c1701f39b1ed9b87cd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:25:02 +0100 Subject: [PATCH 19/26] One isWithinBlockInteractionRange for guests, the in-frame player, stations, lecterns and signs The reach test was written out four times (stations, lecterns, the in-frame container check and the guest's); they now share lan::guest::within_block_range. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/lan_stations.rs | 20 ++------------ crates/horizon-client/src/game/sign_edit.rs | 2 +- crates/horizon-client/src/game/storage.rs | 14 ++-------- crates/horizon-client/src/lan/guest.rs | 26 ++++++++++++------- 4 files changed, 21 insertions(+), 41 deletions(-) diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 49a90b7b9..418ed9c2a 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -588,7 +588,7 @@ impl Game<'_> { let [x, y, z] = gs.pos; let name = &self.res.facts().get(self.world.block(x, y, z)).name; let block = StationKind::from_block(name) == Some(gs.kind); - if !(block && within_reach(g, gs.pos)) { + if !(block && g.within_block_range(gs.pos, 4.0)) { let window = gs.window; self.lan_station_closed(host, conn, Some(window)); host.hub.send_to( @@ -631,16 +631,7 @@ impl Game<'_> { Some(BlockEntity::Lectern(l)) if l.book.is_some() ); // Container.stillValidBlockEntity: the interaction range and its buffer. - let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; - let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; - let pos = [key.0, key.1, key.2]; - let near = (0..3) - .map(|k| { - let lo = f64::from(pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach; + let near = g.within_block_range([key.0, key.1, key.2], 4.0); if has_book && near { self.lan_send_lectern(host, conn, false); } else { @@ -660,10 +651,3 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec { .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) .unwrap_or_default() } - -/// `Player.isWithinBlockInteractionRange(pos, 4)`: the guest's eyes within -/// its block interaction range (4.5, creative 5) and a 4-block buffer of the -/// block's box. -pub(super) fn within_reach(g: &horizon_client::lan::guest::Guest, pos: [i32; 3]) -> bool { - g.within_block_range(pos, 4.0) -} diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 5a26e3e69..5efc3dd0b 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -78,7 +78,7 @@ impl Game<'_> { let Some(g) = host.hub.guest(conn) else { return; }; - let near = super::lan_stations::within_reach(g, p.pos); + let near = g.within_block_range(p.pos, 4.0); let Some(play) = host.play.get_mut(&conn) else { return; }; diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 9132c02a8..de7dfd6e7 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -144,18 +144,8 @@ impl Game<'_> { return; } let range = self.reach() + 4.0; - let near = self.container_parts().iter().all(|((x, y, z), _)| { - let d = [*x, *y, *z] - .iter() - .zip(eye) - .map(|(&lo, e)| { - (f64::from(lo) - e) - .max(e - f64::from(lo) - 1.0) - .max(0.0) - .powi(2) - }) - .sum::(); - d < range * range + let near = self.container_parts().iter().all(|&((x, y, z), _)| { + horizon_client::lan::guest::within_block_range(eye, range, [x, y, z]) }); if !near { self.close_container(); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index dc10096e3..57fa7c636 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -404,22 +404,16 @@ impl Guest { pub fn eye_height(&self) -> f64 { if self.sneaking { 1.27 } else { 1.62 } } - /// `Player.isWithinBlockInteractionRange(pos, buffer)`: the eyes within the - /// block interaction range (4.5, creative 5) plus `buffer` of the block's box. + /// `Player.isWithinBlockInteractionRange(pos, buffer)` for the guest: + /// its block interaction range is 4.5, 5 in creative. pub fn within_block_range(&self, pos: [i32; 3], buffer: f64) -> bool { let eye = [ self.position[0], self.position[1] + self.eye_height(), self.position[2], ]; - let reach = if self.creative() { 5.0 } else { 4.5 } + buffer; - (0..3) - .map(|k| { - let lo = f64::from(pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach + let range = if self.creative() { 5.0 } else { 4.5 }; + within_block_range(eye, range + buffer, pos) } /// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting /// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar, @@ -585,6 +579,18 @@ fn network_stack( Some(stack) } +/// `Player.isWithinBlockInteractionRange`: `eye` closer than `range` to the +/// box of the block at `pos` (`AABB.distanceToSqr`). +pub fn within_block_range(eye: [f64; 3], range: f64, pos: [i32; 3]) -> bool { + (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < range * range +} + #[cfg(test)] mod tests { use super::*; From 65d3edfc3a1fc391f99dd091e41d031857a61583 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:26:03 +0100 Subject: [PATCH 20/26] Launcher: find the client jar of a Modrinth App mod loader profile (#1783) The Modrinth App keeps a Fabric or Quilt profile's vanilla client jar as `versions/-/-.jar`; a player who only played such a profile has no `versions//`, and Prepare said Minecraft was not found. Those jars are now candidates too, checked against the pinned sha1 like the rest. Co-Authored-By: Claude Opus 5.5 --- launcher/src/sources.rs | 18 ++++++++++++++++++ launcher/src/sources_tests.rs | 23 +++++++++++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/launcher/src/sources.rs b/launcher/src/sources.rs index b27b8417b..50953067e 100644 --- a/launcher/src/sources.rs +++ b/launcher/src/sources.rs @@ -191,6 +191,24 @@ fn client_jars(base: &Path, version: &str) -> Vec { jars.push(jar); } } + jars.extend(loader_jars(base, version)); + jars +} + +/// The client jars the Modrinth App keeps for a mod loader's profile: `versions/-/`, +/// the vanilla jar under the loader's name, when only a Fabric or Quilt profile of the version +/// was ever played (#1783). The jar is checked against the pin like the others. +fn loader_jars(base: &Path, version: &str) -> Vec { + let prefix = format!("{version}-"); + let mut jars: Vec = fs::read_dir(base.join("versions")) + .into_iter() + .flatten() + .flatten() + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| name.starts_with(&prefix)) + .map(|name| format!("versions/{name}/{name}.jar")) + .collect(); + jars.sort(); jars } diff --git a/launcher/src/sources_tests.rs b/launcher/src/sources_tests.rs index 6d882f032..396f50881 100644 --- a/launcher/src/sources_tests.rs +++ b/launcher/src/sources_tests.rs @@ -289,6 +289,29 @@ fn the_modrinth_app_atlauncher_and_gdlauncher_are_found() { } } +/// A Modrinth App that only ever played a Fabric profile of 26.3 keeps the vanilla client jar +/// under the loader's name (#1783); a profile of another version beside it is not taken. +#[test] +fn a_modrinth_loader_profile_has_the_client_jar() { + let s = Scratch::new("modrinth-fabric"); + s.write( + "ModrinthApp/meta/versions/26.3.1-0.18.1/26.3.1-0.18.1.jar", + b"other", + ); + let jar = "versions/26.3-0.18.1/26.3-0.18.1.jar"; + let dir = s.launcher("ModrinthApp", "meta", jar); + s.write( + "ModrinthApp/meta/versions/26.3-0.18.1/26.3-0.18.1.json", + br#"{"id":"26.3-0.18.1","inheritsFrom":"26.3"}"#, + ); + let profile = dir.join("profiles/Fabric 26.3"); + fs::create_dir_all(&profile).unwrap(); + let linked = s.0.join("linked"); + let got = resolve_with(&profile, &[], &linked, &Mojang::new(MANIFEST)).unwrap(); + assert_eq!(got, linked); + assert_linked(&linked, &dir.join("meta"), jar); +} + #[test] fn an_instance_folder_may_be_chosen() { let s = Scratch::new("instance"); From 50727eb5c3d389628549c9237bbcca76029c3b79 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:26:43 +0100 Subject: [PATCH 21/26] Harnesses: one scaffold for one-player dedicated server scripts test_hardcore_respawn_parity.py copied test_locator_bar_parity.py's build and run code; both now share locator.sides, and one-player scripts run through locator.one_player. Co-Authored-By: Claude Opus 5.5 --- tools/test_hardcore_respawn_parity.py | 114 +++----------------------- tools/test_locator_bar_parity.py | 76 ++++++++++++++++- 2 files changed, 84 insertions(+), 106 deletions(-) diff --git a/tools/test_hardcore_respawn_parity.py b/tools/test_hardcore_respawn_parity.py index 6e0669534..8c7a5394d 100644 --- a/tools/test_hardcore_respawn_parity.py +++ b/tools/test_hardcore_respawn_parity.py @@ -8,23 +8,12 @@ vanilla's protocol code) joins, runs /kill on itself and presses the death scree respawns the player, then makes it a spectator because the server is hardcore. The game mode changes and respawns Alice is sent in the death and respawn steps are compared exactly. """ -import json -import os -from pathlib import Path -import platform -import shutil -import subprocess import sys -import time try: - from . import lab, test_rust_parity as base, test_locator_bar_parity as locator - from .test_dedicated_server_parity import Server + from . import test_locator_bar_parity as locator except ImportError: - import lab - import test_rust_parity as base import test_locator_bar_parity as locator - from test_dedicated_server_parity import Server NAME = 'hardcore-respawn-parity' # server_dir and generate_world write these server.properties. @@ -33,103 +22,24 @@ SCRIPT = [ ('death', ['cmd Alice kill @s']), ('respawn', ['respawn Alice']), ] -STEP_SECONDS = 4.0 -SHOWN = ('gamemode', 'respawn') - - -def run_side(label, server_command, client_command, build, world): - directory = build / label - port = locator.server_dir(directory, world) - out = build / f'{label}.txt' - out.unlink(missing_ok=True) - server = Server(server_command, directory, label) - try: - server.wait_for(r'Done \(') - with (build / f'{label}-client.log').open('w') as log: - client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], - cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, - text=True) - - def tell(line): - client.stdin.write(line + '\n') - client.stdin.flush() - try: - tell('players on') - tell('state on') - tell('step joins') - tell('join Alice') - server.wait_for(r'Alice joined the game', timeout=120) - time.sleep(STEP_SECONDS) - for step, actions in SCRIPT: - tell(f'step {step}') - for action in actions: - tell(action) - time.sleep(STEP_SECONDS) - tell('end') - client.wait(timeout=60) - finally: - if client.poll() is None: - client.kill() - finally: - server.stop() - if not out.exists(): - raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') - return out.read_text(encoding='utf-8').splitlines() def shown(lines): """Alice's game mode changes and respawns in the death and respawn steps.""" - keep = [] - for line in lines: - parts = line.split(' ', 3) - if len(parts) >= 3 and parts[1] in ('step=death', 'step=respawn') and parts[2] in SHOWN: - keep.append(line) - return keep + return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 + and parts[1] in ('step=death', 'step=respawn') and parts[2] in ('gamemode', 'respawn')] + + +def check(vanilla, _): + if 'Alice step=respawn gamemode 3' not in vanilla: + return 'vanilla did not make the respawned player a spectator' + return None def main(): - lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME - build.mkdir(parents=True, exist_ok=True) - report = build / 'report.json' - report.unlink(missing_ok=True) - oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' - classes = build / 'classes' - shutil.rmtree(classes, ignore_errors=True) - classes.mkdir() - dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) - subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', - lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], - cwd=lab.ROOT, check=True, capture_output=True) - subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, - check=True, capture_output=True) - metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], - cwd=lab.ROOT, text=True)) - binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') - vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] - horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] - client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] - - world = locator.generate_world(vanilla_server, build) - vanilla_all = run_side('vanilla', vanilla_server, client, build, world) - horizon_all = run_side('horizon', horizon_server, client, build, world) - errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] - vanilla, horizon = shown(vanilla_all), shown(horizon_all) - if errors or vanilla != horizon: - import difflib - diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) - raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' - + '\n'.join(errors[:10]) + '\n' + diff[:6000]) - if 'Alice step=respawn gamemode 3' not in vanilla: - raise AssertionError(f'vanilla did not make the respawned player a spectator: the script did not run ' - f'(see {build})') - lab.write_json(report, dict( - schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), - java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], - lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), - scope='A player dying and respawning in a hardcore world on a dedicated server: the respawn and the game ' - 'mode it is sent (spectator).')) - print(f'hardcore respawn: {len(vanilla)} lines identical') + lines = locator.one_player(NAME, SCRIPT, shown, check, 'A player dying and respawning in a hardcore world on a ' + 'dedicated server: the respawn and the game mode it is sent (spectator).') + print(f'hardcore respawn: {len(lines)} lines identical') if __name__ == '__main__': diff --git a/tools/test_locator_bar_parity.py b/tools/test_locator_bar_parity.py index bc7d21750..985b87a35 100644 --- a/tools/test_locator_bar_parity.py +++ b/tools/test_locator_bar_parity.py @@ -205,12 +205,13 @@ def run_side(label, server_command, client_command, build, world): return out.read_text(encoding='utf-8').splitlines() -def main(): +def sides(name): + """The vanilla and Horizon dedicated servers and the LocatorBarClient that joins them, built for harness + `name`: (lock, build directory, vanilla server, Horizon server, client) commands.""" lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME + build = lab.LOCAL / name build.mkdir(parents=True, exist_ok=True) - report = build / 'report.json' - report.unlink(missing_ok=True) + (build / 'report.json').unlink(missing_ok=True) oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' classes = build / 'classes' shutil.rmtree(classes, ignore_errors=True) @@ -228,7 +229,74 @@ def main(): vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + return lock, build, vanilla_server, horizon_server, client + +def one_player(name, script, shown, check, scope, step_seconds=4.0): + """A harness of one player, Alice: on each server she joins, then runs `script`, a list of (step, client + actions) `step_seconds` apart. The lines `shown(transcript)` keeps must match vanilla's exactly, and + `check(vanilla's shown lines, vanilla's transcript)` returns why vanilla's run is no proof (the script did + not run), or None.""" + lock, build, vanilla_server, horizon_server, client = sides(name) + + def run(label, server_command, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + process = subprocess.Popen([*map(str, client), '127.0.0.1', str(port), str(out)], cwd=lab.ROOT, + stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, text=True) + + def tell(line): + process.stdin.write(line + '\n') + process.stdin.flush() + try: + for line in ['players on', 'state on', 'step joins', 'join Alice']: + tell(line) + server.wait_for(r'Alice joined the game', timeout=120) + time.sleep(step_seconds) + for step, actions in script: + tell(f'step {step}') + for action in actions: + tell(action) + time.sleep(step_seconds) + tell('end') + process.wait(timeout=60) + finally: + if process.poll() is None: + process.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + world = generate_world(vanilla_server, build) + vanilla_all = run('vanilla', vanilla_server, world) + horizon_all = run('horizon', horizon_server, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if (why := check(vanilla, vanilla_all)) is not None: + raise AssertionError(f'{why}: the script did not run (see {build})') + lab.write_json(build / 'report.json', dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), scope=scope)) + return vanilla + + +def main(): + lock, build, vanilla_server, horizon_server, client = sides(NAME) + report = build / 'report.json' world = generate_world(vanilla_server, build) vanilla = run_side('vanilla', vanilla_server, client, build, world) horizon = run_side('horizon', horizon_server, client, build, world) From 0298d109886f0679f3a3ae11d001f0b81224026c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:31:37 +0100 Subject: [PATCH 22/26] Shulker boxes: one canFitInsideContainerItems for both menus, and a unit test The client's menu and the server's guest menus now share menu::fits_inside_container_items, and a resource-backed test checks that a guest's shulker box menu refuses shulker boxes by pickup, shift-click and number key while other containers take them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lan/menu.rs | 70 +++++++++++++++++++++------ crates/horizon-client/src/menu.rs | 13 ++--- 2 files changed, 61 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/lan/menu.rs b/crates/horizon-client/src/lan/menu.rs index fefcb1933..8e8772055 100644 --- a/crates/horizon-client/src/lan/menu.rs +++ b/crates/horizon-client/src/lan/menu.rs @@ -155,11 +155,9 @@ impl View<'_> { if self.container.is_none() && (5..=8).contains(&i) { return rules.armor_index(&stack.item) == Some(i - 5); } - // ShulkerBoxSlot.mayPlace: Item.canFitInsideContainerItems, false - // for shulker boxes. if self.shulker && self.container.as_ref().is_some_and(|c| i < c.len()) - && stack.item.ends_with("shulker_box") + && !crate::menu::fits_inside_container_items(stack) { return false; } @@ -675,6 +673,24 @@ mod tests { ) } + /// The prepared resources' items, or None (the test is skipped) without them. + fn rules() -> Option { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION) + }); + if !root.join("items.json").exists() { + eprintln!("skipping resource-backed menu check: {}", root.display()); + return None; + } + let registry = horizon_world::level::data::load_registry(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap(); + Some(ItemRules(Items::load(&root, ®istry, &facts).unwrap())) + } + fn contents(stack: &Option) -> Vec<(String, u32)> { let inside = stack.as_ref().and_then(|s| s.data()); inside.map_or(Vec::new(), |d| { @@ -690,20 +706,9 @@ mod tests { /// slot; a stack clicked onto a bundle goes in, as far as it fits. #[test] fn guest_chest_clicks_fill_and_empty_bundles() { - let root = std::env::var_os("HORIZON_RESOURCES") - .map(std::path::PathBuf::from) - .unwrap_or_else(|| { - std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../.local/horizon-client") - .join(horizon_core::VANILLA_VERSION) - }); - if !root.join("items.json").exists() { - eprintln!("skipping resource-backed bundle check: {}", root.display()); + let Some(rules) = rules() else { return; - } - let registry = horizon_world::level::data::load_registry(&root).unwrap(); - let facts = crate::blocks::BlockFacts::load(&root, ®istry).unwrap(); - let rules = ItemRules(Items::load(&root, ®istry, &facts).unwrap()); + }; let mut g = guest(); let mut chest = vec![ Some(ItemStack::new("minecraft:stone", 48)), @@ -747,4 +752,37 @@ mod tests { ); assert_eq!(contents(&view.get(2)), []); } + + #[test] + fn guest_shulker_box_menu_refuses_shulker_boxes() { + let Some(rules) = rules() else { + return; + }; + for shulker in [true, false] { + let mut g = guest(); + let mut container = vec![None; 27]; + let mut drag = None; + let mut view = View { + guest: &mut g, + container: Some(&mut container), + shulker, + }; + // Carried onto an empty slot, shift-clicked from the hotbar + // (menu slot 27 + 27) and swapped in with the number key 1. + view.guest.carried = Some(ItemStack::new("minecraft:red_shulker_box", 1)); + click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules); + assert_eq!(view.get(0).is_none(), shulker); + view.guest.carried = None; + view.guest.inventory[0] = Some(ItemStack::new("minecraft:shulker_box", 1)); + click(&mut view, &mut drag, 54, 0, input::QUICK_MOVE, &rules); + assert_eq!(view.guest.inventory[0].is_some(), shulker); + view.guest.inventory[0] = Some(ItemStack::new("minecraft:blue_shulker_box", 1)); + click(&mut view, &mut drag, 5, 0, input::SWAP, &rules); + assert_eq!(view.get(5).is_none(), shulker); + // Anything else goes in. + view.guest.carried = Some(ItemStack::new("minecraft:diamond", 1)); + click(&mut view, &mut drag, 9, 0, input::PICKUP, &rules); + assert!(view.get(9).is_some()); + } + } } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 07e4ba2b9..764abe0d9 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -247,6 +247,12 @@ pub fn beacon_required_levels(effect: Option<&str>) -> i32 { .map_or(i32::MAX, |i| i as i32 + 1) } +/// `Item.canFitInsideContainerItems` (`ShulkerBoxSlot.mayPlace`): shulker +/// boxes cannot nest. +pub fn fits_inside_container_items(stack: &ItemStack) -> bool { + !stack.item.ends_with("shulker_box") +} + /// The containers a menu spans. const PLAYER: usize = 0; const MAIN: usize = 1; @@ -1210,11 +1216,6 @@ impl Menu { env.items.get(&stack.item).is_some_and(|i| i.fuel.is_some()) } - /// `Item.canFitInsideContainerItems`: shulker boxes cannot nest. - fn fits_inside(stack: &ItemStack) -> bool { - !(stack.item.ends_with("shulker_box")) - } - // ---- Slot ---- fn may_place(&self, env: &Env, s: usize, stack: &ItemStack) -> bool { @@ -1247,7 +1248,7 @@ impl Menu { .as_deref() .is_some_and(|m| i.equip_allowed.as_ref().is_none_or(|a| a.contains(m))) }), - Role::Shulker => Self::fits_inside(stack), + Role::Shulker => fits_inside_container_items(stack), Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack), Role::Output | Role::CraftResult | Role::Inert => false, Role::CrafterIn => self.data.get(self.slots[s].index) != Some(&1), From 0dfc6d8700554d0d0b8bfb93cc00cd14062daa49 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:38:28 +0100 Subject: [PATCH 23/26] command_exec harness: summoned mobs' saved attribute bases and health (#1483) A cow summoned with max_health and movement_speed bases, and a zombie with an attack_damage base and a saved Health, against vanilla. Co-Authored-By: Claude Opus 5.5 --- tools/command_exec_corpus.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 0e376e260..be4e16a8a 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -291,6 +291,19 @@ def entities(): cmd('/data get entity @e[tag=root,limit=1] Passengers[0].Health'), cmd('/data get entity @e[tag=root,limit=1] Passengers[0].id'), cmd('/kill @e[tag=root]'), + # Saved attribute bases are read for every mob, then Health or the max + # health when there is none (LivingEntity.readAdditionalSaveData, #1483). + cmd('/summon minecraft:cow 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,' + 'attributes:[{id:"minecraft:max_health",base:40.0d},{id:"minecraft:movement_speed",base:0.5d}]}'), + cmd('/data get entity @e[tag=attr,limit=1] Health'), + cmd('/attribute @e[tag=attr,limit=1] minecraft:max_health base get'), + cmd('/attribute @e[tag=attr,limit=1] minecraft:movement_speed base get'), + cmd('/kill @e[tag=attr]'), + cmd('/summon minecraft:zombie 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,Health:7.0f,' + 'attributes:[{id:"minecraft:attack_damage",base:9.0d}]}'), + cmd('/data get entity @e[tag=attr,limit=1] Health'), + cmd('/attribute @e[tag=attr,limit=1] minecraft:attack_damage base get'), + cmd('/kill @e[tag=attr]'), *setup('/kill @e[type=minecraft:armor_stand]'), {'op': 'tick', 'n': 25}, cmd('/execute if entity @e[tag=h]'), From 8c54e1858741b47dcca050cd5dc35b6d32f2d23c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:40:41 +0100 Subject: [PATCH 24/26] /ride dismount: the boats' BOARDING_COOLDOWN, not a second 60 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/boat_passengers.rs | 2 +- crates/horizon-client/src/game/commands/world_cmds.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/boat_passengers.rs b/crates/horizon-client/src/game/boat_passengers.rs index 96686f69b..7055cccfd 100644 --- a/crates/horizon-client/src/game/boat_passengers.rs +++ b/crates/horizon-client/src/game/boat_passengers.rs @@ -13,7 +13,7 @@ use horizon_client::{ use horizon_core::geometry::{Aabb, Vec3}; /// `Entity.boardingCooldown` once a mob leaves its boat. -const BOARDING_COOLDOWN: i32 = 60; +pub(super) const BOARDING_COOLDOWN: i32 = 60; /// `Player.DEFAULT_VEHICLE_ATTACHMENT`: how far below the seat a player's /// feet are. const PLAYER_RIDING_OFFSET: f64 = 0.6; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index c8bd220be..30f019997 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -1191,7 +1191,7 @@ impl Game<'_> { }; let m = &mut self.mobs[i]; m.extra.passenger = false; - m.extra.boarding_cooldown = 60; + m.extra.boarding_cooldown = super::super::boat_passengers::BOARDING_COOLDOWN; m.position = at; m.previous = at; } From b873f30c29b66a551b6f3744be5efa7468795c9c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 17:41:04 +0100 Subject: [PATCH 25/26] wears_freeze_immune above sync_player_body's doc comment, which it had taken over Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4e4865c7a..6dd5f4678 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1837,13 +1837,6 @@ impl Game<'_> { .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }) } - /// What the window decides for its player's body every tick, in frame and - /// on a server alike: the look (Player.travel steers sprint-swimming by - /// the pitch), Auto Jump (LocalPlayer.sendPosition), the slowdown of an - /// item in use (LocalPlayer.modifyInput), the helmet's Respiration - /// (decreaseAirSupply), the wings, leather boots on powder snow - /// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear - /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA. /// `LivingEntity.canFreeze`'s armor half: any worn piece in /// `freeze_immune_wearables`. pub(crate) fn wears_freeze_immune(&self) -> bool { @@ -1857,6 +1850,13 @@ impl Game<'_> { .flatten() .any(|s| immune.is_some_and(|t| t.contains(&*s.item))) } + /// What the window decides for its player's body every tick, in frame and + /// on a server alike: the look (Player.travel steers sprint-swimming by + /// the pitch), Auto Jump (LocalPlayer.sendPosition), the slowdown of an + /// item in use (LocalPlayer.modifyInput), the helmet's Respiration + /// (decreaseAirSupply), the wings, leather boots on powder snow + /// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear + /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA. pub(crate) fn sync_player_body(&mut self) { let glider = self.glider_worn(); let item_use_speed = self From 4513af89954872409e1f02909633789c6293a5a9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 20:13:36 +0100 Subject: [PATCH 26/26] horizon-server: the lock test waits for a fork-held descriptor to close Tests in the same binary spawn processes (tar, the engine); between fork and exec the child holds a copy of every open descriptor, the lock's too, so relocking right after drop could see WouldBlock. Seen twice on CI (#1833, #1895). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-server/src/supervisor.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs index 4de011362..f2e811700 100644 --- a/crates/horizon-server/src/supervisor.rs +++ b/crates/horizon-server/src/supervisor.rs @@ -849,7 +849,17 @@ mod tests { let first = lock(&dir).unwrap(); assert!(lock(&dir).unwrap_err().contains("already running")); drop(first); - lock(&dir).unwrap(); + // A process another test spawns holds a copy of the lock's descriptor between its fork and exec: + // the lock comes back once that child has exec'd. + let mut again = lock(&dir); + for _ in 0..50 { + if again.is_ok() { + break; + } + std::thread::sleep(std::time::Duration::from_millis(20)); + again = lock(&dir); + } + again.unwrap(); std::fs::remove_dir_all(&dir).unwrap(); } }