From 4f2674275d1286a1b5193f2ab07666089213cc0b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 00:34:14 +0200 Subject: [PATCH 1/4] horizon-prepare: keep the registry and command reports with the prepared files A dedicated server reads registries.json and commands.json (the data generator's reports) next to the prepared resources, and otherwise only finds them in the .local/datagen folder of a development checkout. A prepared folder copied or mounted on its own, as the Docker image expects, stopped the server at start with "registries.json not found next to the resources". The prepare step now copies both reports into the folder (again whenever the server jar changes). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-prepare/src/lib.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/horizon-prepare/src/lib.rs b/crates/horizon-prepare/src/lib.rs index f997be326..ac1e97af8 100644 --- a/crates/horizon-prepare/src/lib.rs +++ b/crates/horizon-prepare/src/lib.rs @@ -802,6 +802,17 @@ fn steps( } } + // The registry and command reports, which the game reads next to these + // files when it serves players (a dedicated server, a LAN world): kept + // here too, so this folder works when it is copied or mounted alone. + let reports = run.local.join("datagen").join("out").join("reports"); + for name in ["registries.json", "commands.json"] { + let (from, to) = (reports.join(name), root.join(name)); + if from.is_file() && (!to.exists() || !run.same("server_sha256")) { + copy(&from, &to)?; + } + } + // Biome parameter tables come from the data generator reports above. prepare_worldgen(run)?; From 5118d824a688a8ae3e4fb0ee25406b65f57aef5b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 04:47:35 +0200 Subject: [PATCH 2/4] LAN hub: hand a tick's packets to each connection together Every packet sent to a guest woke its writer thread, and at 25 walking bots those wake-ups (mpsc notify, semaphore_signal) were about a quarter of the server thread's tick. While tick_lan runs, packets for each guest are held and handed over in one Out::Packets at the end; a send outside a tick, or a disconnect, first hands over what is held, so the bytes and their order are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 6 ++ crates/horizon-client/src/game/scoreboard.rs | 5 +- crates/horizon-client/src/lan/conn.rs | 108 +++++++++++++++++-- crates/horizon-client/src/lan/hub.rs | 4 +- crates/horizon-client/src/lan/mod.rs | 4 +- 5 files changed, 111 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 1d00134e4..f6fc1e860 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -684,6 +684,8 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + // What the tick sends a guest goes to its connection at the end. + let holding = lan::Holding::start(); let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { @@ -783,6 +785,10 @@ impl Game<'_> { self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); + drop(holding); + for g in &host.hub.guests { + g.sender.flush(); + } self.lan = Some(host); } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 16297e930..ff1f602a4 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -737,10 +737,7 @@ mod tab_list_tests { name: name.into(), info: ClientInformation::new(8), brand: "test".into(), - sender: PlayerSender { - tx, - pending: Arc::default(), - }, + sender: PlayerSender::new(tx, Arc::default()), latency: Arc::new(AtomicI32::new(42)), address: "127.0.0.1:25565".parse().unwrap(), }, diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index a1ffac4fa..fa31f2275 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -21,9 +21,10 @@ use horizon_protocol::{ text::translatable, }; use std::{ + cell::Cell, net::TcpStream, sync::{ - Arc, + Arc, Mutex, PoisonError, atomic::{AtomicI32, AtomicI64, AtomicUsize, Ordering}, mpsc::{Receiver, RecvTimeoutError, Sender, channel}, }, @@ -122,16 +123,64 @@ pub fn valid_name(name: &str) -> bool { (1..=16).contains(&name.len()) && name.chars().all(|c| c as u32 > 32 && (c as u32) < 127) } +thread_local! { + static HOLDING: Cell = const { Cell::new(false) }; +} + +/// While one is alive, the packets this thread sends to each player are held +/// and handed to the player's writer thread together by +/// [`PlayerSender::flush`]: one wake-up per player per tick rather than one +/// per packet. The bytes and their order don't change. +pub struct Holding(bool); +impl Holding { + pub fn start() -> Self { + Self(HOLDING.replace(true)) + } +} +impl Drop for Holding { + fn drop(&mut self) { + HOLDING.set(self.0); + } +} + /// The sending half given to the game thread. #[derive(Clone)] pub struct PlayerSender { pub tx: Sender, pub pending: Arc, + held: Arc>>>, } impl PlayerSender { + pub fn new(tx: Sender, pending: Arc) -> Self { + Self { + tx, + pending, + held: Arc::default(), + } + } + fn held(&self) -> std::sync::MutexGuard<'_, Vec>> { + self.held.lock().unwrap_or_else(PoisonError::into_inner) + } pub fn send(&self, body: Vec) { self.pending.fetch_add(body.len(), Ordering::Relaxed); - let _ = self.tx.send(Out::Packet(body)); + if HOLDING.get() { + self.held().push(body); + } else { + self.flush(); + let _ = self.tx.send(Out::Packet(body)); + } + } + /// Hand the held packets to the writer thread. + pub fn flush(&self) { + let held = std::mem::take(&mut *self.held()); + if !held.is_empty() { + let _ = self.tx.send(Out::Packets(held)); + } + } + /// Send a play disconnect with this reason after what was sent before. + pub fn disconnect(&self, reason: horizon_world::nbt::Tag) { + self.flush(); + let _ = self.tx.send(Out::Disconnect(reason)); } } @@ -466,10 +515,7 @@ fn play(c: Connection, shared: &Arc, parts: Parts, address: std::net::So let pending = Arc::new(AtomicUsize::new(0)); let latency = Arc::new(AtomicI32::new(0)); let alive = Arc::new(AtomicI64::new(-1)); - let sender = PlayerSender { - tx: tx.clone(), - pending: pending.clone(), - }; + let sender = PlayerSender::new(tx.clone(), pending.clone()); let writer_thread = { let (alive, latency, pending) = (alive.clone(), latency.clone(), pending.clone()); std::thread::Builder::new() @@ -544,13 +590,18 @@ fn write_loop( let mut sent_at: Option<(i64, Instant)> = None; let mut next = Instant::now() + KEEP_ALIVE_EVERY; loop { + let mut write = |body: Vec| { + pending.fetch_sub(body.len(), Ordering::Relaxed); + writer.send(&body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING + }; match rx.recv_timeout(Duration::from_millis(200)) { Ok(Out::Packet(body)) => { - pending.fetch_sub(body.len(), Ordering::Relaxed); - if writer.send(&body).is_err() { + if !write(body) { break; } - if pending.load(Ordering::Relaxed) > MAX_PENDING { + } + Ok(Out::Packets(bodies)) => { + if !bodies.into_iter().all(&mut write) { break; } } @@ -594,3 +645,42 @@ fn write_loop( } writer.shutdown(); } + +#[cfg(test)] +mod tests { + use super::*; + + fn bodies(rx: &Receiver) -> Vec>> { + rx.try_iter() + .map(|out| match out { + Out::Packet(body) => vec![body], + Out::Packets(bodies) => bodies, + Out::Disconnect(_) => vec![b"disconnect".to_vec()], + Out::Close => vec![b"close".to_vec()], + }) + .collect() + } + + #[test] + fn held_packets_go_together_and_in_order() { + let (tx, rx) = channel(); + let sender = PlayerSender::new(tx, Arc::default()); + sender.send(vec![1]); + assert_eq!(bodies(&rx), [vec![vec![1]]]); + let holding = Holding::start(); + sender.send(vec![2]); + sender.send(vec![3]); + assert!(bodies(&rx).is_empty()); + drop(holding); + // A packet sent after the tick still follows the held ones. + sender.send(vec![4]); + assert_eq!(bodies(&rx), [vec![vec![2], vec![3]], vec![vec![4]]]); + let holding = Holding::start(); + sender.send(vec![5]); + sender.disconnect(horizon_world::nbt::Tag::Byte(0)); + drop(holding); + sender.flush(); + assert_eq!(bodies(&rx), [vec![vec![5]], vec![b"disconnect".to_vec()]]); + assert_eq!(sender.pending.load(Ordering::Relaxed), 5); + } +} diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index cb438508e..414979a87 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -389,7 +389,7 @@ impl Hub { /// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect). pub fn kick(&mut self, conn: u32, reason: Tag) { if let Some(g) = self.guest(conn) { - let _ = g.sender.tx.send(super::Out::Disconnect(reason)); + g.sender.disconnect(reason); } } @@ -1638,7 +1638,7 @@ impl Hub { pub fn disconnect_all(&mut self) { let reason = translatable("multiplayer.disconnect.server_shutdown", &[]); for g in &self.guests { - let _ = g.sender.tx.send(super::Out::Disconnect(reason.clone())); + g.sender.disconnect(reason.clone()); } } } diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 7084f20a6..6af4a1fef 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -21,7 +21,7 @@ pub mod playerdata; mod recipes; pub mod tracking; -pub use conn::PlayerSender; +pub use conn::{Holding, PlayerSender}; use horizon_protocol::packets::play; use horizon_protocol::{ GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation, @@ -69,6 +69,8 @@ pub struct Joined { pub enum Out { /// A packet body: VarInt id and payload. Packet(Vec), + /// Packet bodies held during a tick, in order. + Packets(Vec>), /// Send a play disconnect with this component, then close. Disconnect(horizon_world::nbt::Tag), Close, From 67633fc7891a3c6f2bcd5443499a11ec0ed36360 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:46:07 -0400 Subject: [PATCH 3/4] Reset player experience on respawn and award capped death XP --- crates/horizon-client/src/entities.rs | 45 +++++++++++++++++++ crates/horizon-client/src/game.rs | 11 ++--- crates/horizon-client/src/game/lan_actions.rs | 14 ++++++ crates/horizon-client/src/game/screens.rs | 4 ++ 4 files changed, 69 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index a1e18076e..5e6a3336a 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -301,6 +301,20 @@ pub struct Experience { pub total: i32, } impl Experience { + /// `Player.getBaseExperienceReward`: keep-inventory and spectators drop none. + pub fn death_reward(&self, keep: bool) -> u32 { + if keep { + 0 + } else { + self.level.wrapping_mul(7).clamp(0, 100) as u32 + } + } + /// `ServerPlayer.restoreFrom`: only keep-inventory and spectators retain XP. + pub fn respawn(&mut self, keep: bool) { + if !keep { + *self = Self::default(); + } + } pub fn needed(level: i32) -> i32 { if level >= 30 { 112 + (level - 30) * 9 @@ -540,6 +554,37 @@ impl ArmorStand { } } +#[cfg(test)] +mod experience_tests { + use super::*; + + #[test] + fn death_reward_uses_levels_and_caps_the_recoverable_points() { + for (level, reward) in [(0, 0), (1, 7), (14, 98), (15, 100), (30, 100)] { + let xp = Experience { + level, + progress: 0.75, + total: 10_000, + }; + assert_eq!(xp.death_reward(false), reward); + assert_eq!(xp.death_reward(true), 0); + } + } + + #[test] + fn respawn_clears_all_xp_unless_it_is_kept() { + let mut xp = Experience::default(); + xp.give(155); + let before = (xp.level, xp.progress, xp.total); + xp.respawn(true); + assert_eq!((xp.level, xp.progress, xp.total), before); + xp.respawn(false); + assert_eq!((xp.level, xp.progress, xp.total), (0, 0.0, 0)); + xp.give(7); + assert_eq!((xp.level, xp.progress, xp.total), (1, 0.0, 7)); + } +} + #[cfg(test)] mod fire_environment_tests { use super::*; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 73fcbbf52..2680aa3c6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3419,11 +3419,8 @@ impl Game<'_> { } if player.health.dead_or_dying() && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. - let at = [ - player.position.x, - player.position.y + 1.32, - player.position.z, - ]; + let feet = [player.position.x, player.position.y, player.position.z]; + let at = [feet[0], feet[1] + 1.32, feet[2]]; let killer = self.combat_killer_kind(); self.death_message(); // ServerPlayer.die: deaths, and the time-since counters restart. @@ -3439,6 +3436,10 @@ impl Game<'_> { } self.stats.reset("custom", "minecraft:time_since_death"); self.stats.reset("custom", "minecraft:time_since_rest"); + let reward = self + .experience + .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); + self.spawn_orbs(feet, reward); if !self.creative && !self.ui.rules.bool("keep_inventory") { // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). let mut stacks: Vec = diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ec4ac6cee..af7ff10f8 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -822,6 +822,13 @@ impl Game<'_> { g.saturation = 5.0; g.sent_health = None; g.motion = None; + let mut xp = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + }; + xp.respawn(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); + (g.xp_level, g.xp_progress, g.xp_total) = (xp.level, xp.progress, xp.total); // A new body: nothing given to the old one carries over. if let Some(play) = host.play.get_mut(&conn) { play.potions = Default::default(); @@ -898,6 +905,12 @@ impl Game<'_> { g.dead = true; g.last_death = Some(g.position.map(|v| v.floor() as i32)); let (id, at) = (g.entity_id, g.position); + let reward = Experience { + level: g.xp_level, + progress: g.xp_progress, + total: g.xp_total, + } + .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let message = literal(&format!("{} died", g.name)); host.hub.send_to( conn, @@ -905,6 +918,7 @@ impl Game<'_> { ); // LivingEntity.die: the death animation, the dying player included. host.hub.entity_event(id, 3, at); + self.spawn_orbs(at, reward); } } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 54012ca03..3c6f90099 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -260,6 +260,10 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); + if hit == Some(0) && self.remote.is_none() { + let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); + self.experience.respawn(keep); + } match hit { Some(0) if self.remote.is_some() => { self.ui.death_text = None; From 7ee9b0c81d33b3c49fcbb21f13db992d8bdf476d Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Sat, 17 Oct 2026 01:53:10 -0400 Subject: [PATCH 4/4] Render chest breaking overlays on their animated models --- .../horizon-client/src/block_entity_render.rs | 97 ++++++++++++------- crates/horizon-client/src/game.rs | 2 +- 2 files changed, 61 insertions(+), 38 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 85107c1cb..9c90e8ebf 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -898,15 +898,9 @@ impl BlockEntityRenderer { pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) } - /// BannerRenderer submits the support and animated flag once for crumbling. - pub fn render_banner_breaking( - &self, - scene: &Scene, - pos: [i32; 3], - state: u32, - out: &mut Vec, - ) { - if !matches!(self.kind(state), Kind::Banner { .. }) { + /// ChestRenderer and BannerRenderer submit their animated models for crumbling. + pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } let origin = (DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) @@ -1098,7 +1092,7 @@ impl BlockEntityRenderer { ChestPart::Left => "double_chest_left", ChestPart::Right => "double_chest_right", }; - let (Some(model), Some(_)) = (self.models.get(model), sprite(texture)) else { + let Some(model) = self.models.get(model) else { return; }; let (open, other) = self.chest_openness( @@ -1719,18 +1713,28 @@ mod tests { use super::*; #[test] #[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"] - fn banner_particle_and_breaking_use_exported_models() -> crate::Result<()> { + fn entity_block_particles_and_breaking_use_exported_models() -> crate::Result<()> { use crate::{models::catalog::StateModels, sprites::Sprites}; use horizon_world::{DATA_VERSION, chunk::BlockState, nbt::Tag}; let root = std::path::PathBuf::from( std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), ); - let names = ["white_banner", "white_wall_banner"]; + let names = [ + "white_banner", + "white_wall_banner", + "chest", + "trapped_chest", + "ender_chest", + "copper_chest", + ]; let mut facts: std::collections::BTreeMap = serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?; let states = names.map(|name| { let name = format!("minecraft:{name}"); - let first = facts[&name]["states"][0].clone(); + let mut first = facts[&name]["states"][0].clone(); + if first.get("type").is_some() { + first["type"] = serde_json::json!("single"); + } facts.get_mut(&name).unwrap()["states"] = serde_json::json!([first.clone()]); BlockState { name, @@ -1743,24 +1747,28 @@ mod tests { ("states", Tag::List(states.into())), ( "defaults", - Tag::compound([ - ("minecraft:white_banner", Tag::Int(0)), - ("minecraft:white_wall_banner", Tag::Int(1)), - ]), + Tag::compound(names.iter().enumerate().map(|(id, name)| { + ( + horizon_world::nbt::JavaString::from(format!("minecraft:{name}").as_str()), + Tag::Int(id as i32), + ) + })), ), ]))?; let mut sprites = Sprites::default(); let catalog = StateModels::from_facts(&root, ®istry, &names, &mut sprites, &facts)?; - for id in 0..2 { + for (id, name) in names.iter().enumerate() { let models = catalog.collect( - BlockStateId(id), + BlockStateId(id as u32), horizon_core::position::BlockPos::default(), )?; assert!(models.iter().all(|(_, model)| model.faces.is_empty())); - assert_eq!( - models[0].1.particle, - Some(sprites.layers["minecraft:block/oak_planks"]) - ); + let particle = match *name { + "ender_chest" => "minecraft:block/obsidian", + "copper_chest" => "minecraft:block/copper_block", + _ => "minecraft:block/oak_planks", + }; + assert_eq!(models[0].1.particle, Some(sprites.layers[particle])); } let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; let renderer = BlockEntityRenderer::new( @@ -1771,17 +1779,28 @@ mod tests { ®istry, ); let world = World::new(BlockStateId(0), 1); - let base_sprites = HashMap::from([( - "entity/banner/banner_base".to_owned(), - Rect { - u0: 0.0, - v0: 0.0, - u1: 1.0, - v1: 1.0, - w: 16, - h: 16, - }, - )]); + let base_sprites = [ + "entity/banner/banner_base", + "entity/chest/normal", + "entity/chest/trapped", + "entity/chest/ender", + "entity/chest/copper", + ] + .into_iter() + .map(|name| { + ( + name.to_owned(), + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }, + ) + }) + .collect(); let mut scene = Scene { camera: DVec3::ZERO, orientation: Quat::IDENTITY, @@ -1798,11 +1817,11 @@ mod tests { banner: &|_| Vec::new(), glyph: &|_| (None, 0.0), }; - for state in 0..2 { + for state in 0..names.len() as u32 { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_banner_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1812,10 +1831,14 @@ mod tests { && v.color == u32::MAX && v.uv.iter().all(|u| u.is_finite()))); scene.game_time = 20; + if state >= 2 { + scene.lid = &|_| 1.0; + } let mut animated = Vec::new(); - renderer.render_banner_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; + scene.lid = &|_| 0.0; } Ok(()) } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 73fcbbf52..472b975a6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5601,7 +5601,7 @@ impl Game<'_> { .block(mining.pos[0], mining.pos[1], mining.pos[2]); self.res .block_entity_render - .render_banner_breaking(&scene, mining.pos, state.0, &mut out); + .render_breaking(&scene, mining.pos, state.0, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.