From a7ff22eea05de72275341d7346252fc5d2ecdbb6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 23:05:12 +0100 Subject: [PATCH 001/195] Give a server player's new body its effects at once after a level change A server's player gets a new body when it joins, respawns or changes level, but what the old body had been given by its effects (the applied attribute modifiers and the armor protection table) was kept in its per-player record. apply_effect_status then saw nothing to change, so after a trip to another dimension Speed kept its icon while the body's movement speed fell back from 0.14 to 0.10, until the effect was reapplied. Vanilla keeps the same ServerPlayer through ServerPlayer.teleport into another level, with its attributes and MobEffect modifiers. A new body now starts with nothing applied, and its effects are applied as soon as it is created, before the movement that brought it is handled. --- crates/horizon-client/src/game/lan_actions.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 9d4d868e0..41f92106c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -250,8 +250,10 @@ impl Game<'_> { } let mut play = host.play.remove(&conn).unwrap_or_default(); if fresh { - // A new body (joined, respawned, changed level): nothing on it yet. + // A new body (joined, respawned, changed level): nothing on it yet, + // its effects' modifiers and armor protection included. play.equipped = None; + play.potions = Default::default(); } let g = &mut host.hub.guests[i]; // The guest's body. @@ -384,6 +386,12 @@ impl Game<'_> { self.apply_equipment(); play.equipped = Some(equipped); } + // The player's effects are on the new body before anything it does + // (the movement that brought it, a landing): vanilla keeps the same + // entity through a level change, with its attributes and effects. + if fresh { + self.apply_effect_status(); + } self.update_totem_ready(); Some(GuestSwap { conn, From 19a5098b140f4ca6eab01b0e73f5d8688cd52d85 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 01:03:41 +0100 Subject: [PATCH 002/195] Leave a respawned body's reset to the swap that builds it Respawning drops the guest's body, so the next swap builds a fresh one, which now clears what the old body was given (equipment, effects and armor protection) itself. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 41f92106c..00ea51de8 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1707,10 +1707,6 @@ impl Game<'_> { }; 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(); - } let clock_rate = self.network_clock_rate(); let ctx = TickCtx { world: &mut self.world, From 9e3956282abf29f49ba9e0e1f0f04b3622a9b900 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:18:36 +0100 Subject: [PATCH 003/195] Send a deflected fireball's new direction to the player at once A ghast fireball or wind charge hit back by a player was turned on the server, but the player kept seeing it fly on until its next update ten ticks later. Mark the turn to be sent right away, as vanilla does with needsSync, and reset the acceleration power to 0.1 as an attack deflection does. --- crates/horizon-client/src/game/deflect.rs | 5 +++++ crates/horizon-client/src/game/lan.rs | 3 +++ crates/horizon-client/src/game/lan_entities.rs | 1 + crates/horizon-client/src/projectiles.rs | 4 ++++ 4 files changed, 13 insertions(+) diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs index a08de87b3..088374a34 100644 --- a/crates/horizon-client/src/game/deflect.rs +++ b/crates/horizon-client/src/game/deflect.rs @@ -120,6 +120,11 @@ impl Game<'_> { p.guest = guest; // Not into the one who turned it on its way out. p.left_owner = false; + // `AbstractHurtingProjectile.onDeflection` by an attack, and the + // `needsSync` that `AIM_DEFLECT` sets: a server's players see it turn + // at once, not at the fireball's next update ten ticks later. + p.acceleration = 0.1; + p.needs_sync = true; self.reset_attack_strength(); self.swing_arm(); let from = self diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..721fea5cd 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -912,6 +912,9 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + for p in &mut self.creatures.projectiles { + p.needs_sync = false; + } let entities = states.as_slice(); let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..a5c925a65 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -325,6 +325,7 @@ impl Game<'_> { let mut e = state(p.id, kind, at(p.position), p.yaw, false); e.pitch = p.pitch; e.velocity = at(p.velocity); + e.needs_sync = p.needs_sync; // Projectile.getAddEntityPacket: the owner's id. e.data = match p.guest.and_then(|conn| hub.guest(conn)) { Some(g) => g.entity_id, diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 219d59b6b..ef50c30a4 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -104,6 +104,9 @@ pub struct Projectile { pub arrow: Option>, /// `AbstractHurtingProjectile.accelerationPower`. pub acceleration: f64, + /// `Entity.needsSync`: a server tells its clients about the change this + /// tick instead of at the next update interval. + pub needs_sync: bool, } /// What a projectile struck this tick. #[derive(Clone, Copy, Debug, PartialEq)] @@ -168,6 +171,7 @@ impl Projectile { left_owner: false, bonus: Default::default(), acceleration: 0.1, + needs_sync: false, arrow: kind_is_arrow.then(|| { // Entity.random: seeded unpredictably, the position stands in. Box::new(crate::arrows::ArrowState::new( From f5f7448909e1dfe7db76ff0c9a565bc59f786967 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:31:40 +0100 Subject: [PATCH 004/195] Lingering potions leave an effect cloud A thrown lingering potion used to act as one weaker splash. It now leaves an area effect cloud like vanilla: radius 3, a 10 tick wait, 600 ticks, shrinking as it goes and by 0.5 each time it affects someone. Every 5 ticks it affects the mobs and players inside, with a 20 tick delay per entity, at a quarter of the duration (instant effects at half strength). Server players see it as an area_effect_cloud, like the dragon's breath clouds. --- crates/horizon-client/src/game/dragon.rs | 38 ++- .../horizon-client/src/game/lan_entities.rs | 10 +- crates/horizon-client/src/game/potions.rs | 248 ++++++++++++++++-- .../src/game/remote_projectiles.rs | 98 +++---- 4 files changed, 310 insertions(+), 84 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e1880f9aa..c55e3ec9d 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -289,11 +289,11 @@ pub(super) enum FightWho { } /// A player in the End as the dragon sees it. #[derive(Clone, Copy, Debug)] -struct FightPlayer { - who: FightWho, - position: Vec3, - bounds: Aabb, - alive: bool, +pub(super) struct FightPlayer { + pub(super) who: FightWho, + pub(super) position: Vec3, + pub(super) bounds: Aabb, + pub(super) alive: bool, creative: bool, spectator: bool, } @@ -691,7 +691,7 @@ impl Game<'_> { } /// The players in the level the dragon sees (`level.players()`): the /// window's own, then every guest in the level. - fn fight_players(&self) -> Vec { + pub(super) fn fight_players(&self) -> Vec { let mut out = Vec::new(); if let Some(p) = self.player.as_ref() { out.push(FightPlayer { @@ -720,7 +720,7 @@ impl Game<'_> { } /// Run `f` as the fight's player `who` (a guest's turn, its knockback /// sent to its client). - fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { + pub(super) fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { match who { FightWho::Host => f(self), FightWho::Guest(conn) => { @@ -1564,6 +1564,7 @@ impl Game<'_> { age: 0, duration: 200, from_dragon: true, + potion: None, }); } } @@ -2091,6 +2092,7 @@ impl Game<'_> { age: 0, duration: 600, from_dragon: false, + potion: None, }); self.audio.play( "minecraft:entity.dragon_fireball.explode", @@ -2123,6 +2125,10 @@ impl Game<'_> { let mut harmed: Vec<(FightWho, f32)> = Vec::new(); let mut clouds = std::mem::take(&mut self.breath_clouds); clouds.retain_mut(|c| { + // Lingering potions' clouds tick with the potions. + if c.potion.is_some() { + return true; + } c.age += 1; if c.age >= c.duration { return false; @@ -2250,8 +2256,22 @@ pub(super) struct Breath { pub(super) at: [f64; 3], pub(super) radius: f32, pub(super) age: i32, - duration: i32, - from_dragon: bool, + pub(super) duration: i32, + pub(super) from_dragon: bool, + /// A lingering potion's cloud (`ThrownLingeringPotion`): what it applies. + pub(super) potion: Option, +} +impl Breath { + /// `AreaEffectCloud.isWaiting`: before its wait time (20 ticks, 10 for a + /// lingering potion's). + pub(super) fn waiting(&self) -> bool { + self.age + < if self.potion.is_some() { + super::potions::LINGERING_WAIT + } else { + 20 + } + } } impl Game<'_> { /// `EnderDragonRenderer` and `EnderDragonModel.setupAnim`. diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 574f5303e..d8e2a09a6 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -439,7 +439,7 @@ impl Game<'_> { } out.push(e); } - // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // The dragon's breath and lingering potion clouds (AreaEffectCloud's DATA_RADIUS, // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the // client draws them from these (`tick_remote_clouds`). let breath = self.network_particle( @@ -457,10 +457,14 @@ impl Game<'_> { for b in self.breath_clouds.iter().filter(|b| b.id != 0) { let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); - if b.age < 20 { + if b.waiting() { e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); } - if let Some(p) = &breath { + let particle = match &b.potion { + Some(p) => self.network_particle(&p.particle(), None), + None => breath.clone(), + }; + if let Some(p) = &particle { e.meta .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); } diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 74c4ccd0c..bfffff5ee 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,7 +2,12 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen, item_draw::owner_at}; +use super::{ + Game, Screen, + dragon::{Breath, FightPlayer, FightWho}, + item_draw::owner_at, + remote_projectiles::cloud_client_tick, +}; use horizon_assets::item_model::DisplayContext; use horizon_client::{ block_entity_render::vertex_light, @@ -12,8 +17,12 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] @@ -27,6 +36,32 @@ pub(super) struct ThrownPotion { velocity: Vec3, age: u32, } +/// `AreaEffectCloud` wait time set by `ThrownLingeringPotion.onHitAsPotion`. +pub(super) const LINGERING_WAIT: i32 = 10; +/// `AreaEffectCloud.DEFAULT_REAPPLICATION_DELAY`. +const REAPPLICATION_DELAY: i32 = 20; +/// An entity a cloud has affected (`AreaEffectCloud.victims`). +#[derive(Clone, Copy, PartialEq)] +enum Victim { + Mob(u32), + Player(FightWho), +} +/// What a lingering potion's `AreaEffectCloud` applies: the potion's effects +/// (at the lingering item's 0.25 duration scale) and who it has affected. +pub(super) struct PotionCloud { + effects: &'static [(&'static str, i32, i32)], + /// The potion's colour (`PotionContents.getColor`). + color: u32, + /// Each victim and the tick it can be affected again. + victims: Vec<(Victim, i32)>, +} +impl PotionCloud { + /// `AreaEffectCloud.updateParticle`: an entity effect in the potion's colour. + pub(super) fn particle(&self) -> ParticleOptions { + let c = |shift: u32| (self.color >> shift & 255) as f32 / 255.0; + ParticleOptions::colored(ParticleType::EntityEffect, [c(16), c(8), c(0), 1.0]) + } +} /// A mob's effect ids carry the `minecraft:` namespace. fn mob_effect_id(id: &str) -> Option<&'static str> { use std::{collections::HashMap, sync::OnceLock}; @@ -368,6 +403,7 @@ impl Game<'_> { self.tick_mob_effects(); if running { self.tick_thrown_potions(); + self.tick_potion_clouds(); } } /// `LivingEntity.tickEffects` (server side) for `self.player`, the local @@ -504,21 +540,20 @@ impl Game<'_> { let state = self.world .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts().get(state).full_collision - || self.mobs.iter().any(|m| { - m.alive() - && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 - && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 - && p.y >= m.position.y - && p.y <= m.position.y + m.kind.height - }) - { - hit = Some(p); + let mob = self.mobs.iter().find(|m| { + m.alive() + && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 + && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 + && p.y >= m.position.y + && p.y <= m.position.y + m.kind.height + }); + if self.res.facts().get(state).full_collision || mob.is_some() { + hit = Some((p, mob.map(|m| m.position))); break; } } - if let Some(p) = hit { - landed.push((t.stack.clone(), p)); + if let Some((p, mob)) = hit { + landed.push((t.stack.clone(), p, mob)); return false; } t.position = next; @@ -537,8 +572,148 @@ impl Game<'_> { t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at) in landed { - self.splash(&stack, at); + for (stack, at, mob) in landed { + self.splash(&stack, at, mob); + } + } + /// `AreaEffectCloud.tick` for the lingering potions' clouds: the client + /// tick's particles, then the server tick. + fn tick_potion_clouds(&mut self) { + if self.breath_clouds.iter().all(|c| c.potion.is_none()) { + return; + } + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive) + .collect(); + let mut clouds = std::mem::take(&mut self.breath_clouds); + clouds.retain_mut(|c| c.potion.is_none() || self.tick_potion_cloud(c, &players)); + self.breath_clouds.append(&mut clouds); + } + /// `AreaEffectCloud.serverTick` for a lingering potion's cloud: after its + /// wait it shrinks, and every 5 ticks it affects the living entities in + /// its box and radius that were not affected in the last 20 ticks, each + /// taking some of its radius. False once it is gone. + fn tick_potion_cloud(&mut self, c: &mut Breath, players: &[FightPlayer]) -> bool { + c.age += 1; + let Some(potion) = c.potion.as_mut() else { + return true; + }; + if c.age - LINGERING_WAIT >= c.duration { + return false; + } + let waiting = c.age < LINGERING_WAIT; + cloud_client_tick( + &mut self.particles, + c.at, + c.radius, + waiting, + &potion.particle(), + ); + if waiting { + return true; + } + // setRadiusPerTick(-radius / duration). + c.radius += -3.0 / 600.0; + if c.radius < 0.5 { + return false; + } + if c.age % 5 != 0 { + return true; + } + potion.victims.retain(|(_, until)| c.age < *until); + let r = f64::from(c.radius); + let area = Aabb::new( + Vec3::new(c.at[0] - r, c.at[1], c.at[2] - r), + Vec3::new(c.at[0] + r, c.at[1] + 0.5, c.at[2] + r), + ); + let mut inside = Vec::new(); + for p in players.iter().filter(|p| p.bounds.intersects(area)) { + inside.push((Victim::Player(p.who), p.position.x, p.position.z)); + } + for m in self + .mobs + .iter() + .filter(|m| m.alive() && m.bounds().intersects(area)) + { + inside.push((Victim::Mob(m.id), m.position.x, m.position.z)); + } + let effects = potion.effects; + for (victim, x, z) in inside { + let (dx, dz) = (x - c.at[0], z - c.at[2]); + if potion.victims.iter().any(|(v, _)| *v == victim) + || dx * dx + dz * dz > f64::from(c.radius * c.radius) + { + continue; + } + potion.victims.push((victim, c.age + REAPPLICATION_DELAY)); + self.cloud_affect(victim, effects, c.at); + // setRadiusOnUse(-0.5). + c.radius -= 0.5; + if c.radius < 0.5 { + return false; + } + } + true + } + /// What a cloud puts on one entity: instant effects at half strength + /// (`applyInstantaneousEffect` with 0.5), the others for their duration + /// at the lingering item's 0.25 scale (`PotionContents.forEachEffect`). + fn cloud_affect( + &mut self, + victim: Victim, + effects: &'static [(&'static str, i32, i32)], + at: [f64; 3], + ) { + let scaled = |duration: i32| ((f64::from(duration) * 0.25) as i32).max(1); + match victim { + Victim::Player(who) => self.as_fight_player(who, |g| { + for (id, duration, amp) in effects { + let Some(e) = brewing::effect(id) else { + continue; + }; + if e.instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, 0.5) { + g.apply_effect_action(a); + } + } else { + g.add_player_effect(EffectInstance::new(e.id, scaled(*duration), *amp)); + } + } + }), + Victim::Mob(mob) => { + let Some(i) = self.mobs.iter().position(|m| m.id == mob) else { + return; + }; + // Undead invert healing and harming. + let inverted = self + .res + .stations() + .enchantments + .entity_tags + .get("minecraft:inverted_healing_and_harm") + .is_some_and(|t| t.contains(&self.mobs[i].kind.id)); + for (id, duration, amp) in effects { + let m = &mut self.mobs[i]; + match *id { + "instant_damage" | "instant_health" => { + let amount = + |base: i32| (0.5 * f64::from(base << amp) + 0.5) as i32 as f32; + if (*id == "instant_damage") != inverted { + m.hurt(amount(6), Some(at), &mut self.world.random); + } else { + m.health = (m.health + amount(4)).min(m.kind.max_health); + } + } + _ => { + if let Some(name) = mob_effect_id(id) { + m.add_effect(name, scaled(*duration), *amp); + } + } + } + } + } } } /// `ThrownItemRenderer` for thrown splash and lingering potions and @@ -587,12 +762,7 @@ impl Game<'_> { } } /// A splash potion's effects on the player in place, by their distance. - fn splash_on_player( - &mut self, - effects: &'static [(&'static str, i32, i32)], - at: Vec3, - scale: f64, - ) { + fn splash_on_player(&mut self, effects: &'static [(&'static str, i32, i32)], at: Vec3) { if let Some(p) = self.player.as_ref() { let center = Vec3::new( p.position.x, @@ -610,7 +780,7 @@ impl Game<'_> { self.apply_effect_action(a); } } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(e) = brewing::effect(id) { @@ -621,8 +791,9 @@ impl Game<'_> { } } } - /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3) { + /// `ThrownSplashPotion.onHitAsPotion`, or `ThrownLingeringPotion.onHitAsPotion` + /// for a lingering potion; `mob` is where it hit a mob. + fn splash(&mut self, stack: &ItemStack, at: Vec3, mob: Option) { if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level // event 2002) and 3 to 11 experience. @@ -677,13 +848,34 @@ impl Game<'_> { ); self.particles.push(p); } - let scale = if lingering { 0.25 } else { 1.0 }; let Some(def) = stack.potion().and_then(brewing::potion) else { return; }; + if lingering { + // The cloud sits at the mob it hit (its feet), else the impact; + // radius 3, wait 10, 600 ticks, shrinking to nothing, and a + // potion with no effects leaves none. + if !def.effects.is_empty() { + let at = mob.unwrap_or(at); + self.breath_clouds.push(Breath { + id: 0, + at: [at.x, at.y, at.z], + radius: 3.0, + age: 0, + duration: 600, + from_dragon: false, + potion: Some(PotionCloud { + effects: def.effects, + color, + victims: Vec::new(), + }), + }); + } + return; + } // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); + self.for_each_player(|g| g.splash_on_player(def.effects, at)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); @@ -706,7 +898,7 @@ impl Game<'_> { _ => { // `Potion.applySplash`: timed effects last in // proportion to how close the mob was. - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(name) = mob_effect_id(id) { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index bbb7b7cde..f6fff2ca2 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -23,6 +23,58 @@ fn default_cloud_particle() -> ParticleOptions { ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) } +/// `AreaEffectCloud.clientTick`: while waiting, now and then two particles +/// near the middle; then about one per square block of the disc, drifting +/// (an entity effect stays still). +pub(super) fn cloud_client_tick( + particles: &mut horizon_client::particles::ParticleEngine, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: &ParticleOptions, +) { + if waiting && particles.random().next_boolean() { + return; + } + let (count, spread) = if waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * radius * radius).ceil() as i32, + radius, + ) + }; + for _ in 0..count { + let r = particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + at[0] + f64::from(angle.cos() * distance), + at[1], + at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if particle.ty == ParticleType::EntityEffect { + let default = waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + particle.clone() + }; + (options, [0.0; 3]) + } else if waiting { + (particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (particle.clone(), v) + }; + particles.add(&options, at, velocity); + } +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -380,52 +432,10 @@ impl Game<'_> { } } - /// `AreaEffectCloud.clientTick`: while waiting, now and then two - /// particles near the middle; then about one per square block of the - /// disc, drifting (an entity effect stays still). + /// `AreaEffectCloud.clientTick` for each cloud a server tracks. fn tick_remote_clouds(&mut self) { for c in &self.potions.clouds { - let r = self.particles.random(); - if c.waiting && r.next_boolean() { - continue; - } - let (count, spread) = if c.waiting { - (2, 0.2) - } else { - ( - (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, - c.radius, - ) - }; - for _ in 0..count { - let r = self.particles.random(); - let angle = r.next_float() * std::f32::consts::TAU; - let distance = r.next_float().sqrt() * spread; - let at = [ - c.at[0] + f64::from(angle.cos() * distance), - c.at[1], - c.at[2] + f64::from(angle.sin() * distance), - ]; - let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { - let default = c.waiting && r.next_boolean(); - let options = if default { - default_cloud_particle() - } else { - c.particle.clone() - }; - (options, [0.0; 3]) - } else if c.waiting { - (c.particle.clone(), [0.0; 3]) - } else { - let v = [ - (0.5 - r.next_double()) * 0.15, - f64::from(0.01f32), - (0.5 - r.next_double()) * 0.15, - ]; - (c.particle.clone(), v) - }; - self.particles.add(&options, at, velocity); - } + cloud_client_tick(&mut self.particles, c.at, c.radius, c.waiting, &c.particle); } } From 265965445d471e0dedba02d998362e8642443b78 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:34:59 +0100 Subject: [PATCH 005/195] Save the world when the game gets SIGTERM, Ctrl+C or SIGHUP, and disconnect on native quit --- crates/horizon-client/src/game.rs | 22 +++++++++++++++++++++ crates/horizon-threads/src/lib.rs | 32 +++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cdbd72d7b..e8e6a6bcb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8207,6 +8207,10 @@ impl Game<'_> { } self.lan_close(false); self.save_game()?; + if let Some(mut remote) = self.remote.take() { + // Minecraft.disconnect closes the connection, so the host sees a clean leave. + remote.session.disconnect(); + } self.saved_for_exit = true; Ok(()) } @@ -11960,6 +11964,16 @@ impl ApplicationHandler for Game<'_> { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 + && self.pending_save.as_ref().is_none_or(|save| !save.quit) + { + // SIGTERM, SIGINT or SIGHUP: the shutdown hook's server halt, as a window close. + if let Err(error) = self.begin_closing_save(true) { + self.error = Some(error); + event_loop.exit(); + return; + } + } if self.pending_save.is_some() { match self.poll_closing_save() { Ok(true) => event_loop.exit(), @@ -13405,6 +13419,11 @@ impl Loading { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 { + // No world is open yet: nothing to save. + event_loop.exit(); + return; + } if let Err(error) = self.poll_menu_resources() { self.error = Some(error); event_loop.exit(); @@ -13682,6 +13701,9 @@ pub fn run() -> Result<()> { { horizon_client::heartbeat::start(); } + if options.execution_role.is_client() { + horizon_threads::catch_stop_signals(); + } let started = Instant::now(); horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); diff --git a/crates/horizon-threads/src/lib.rs b/crates/horizon-threads/src/lib.rs index 90c8d128e..ec98b1690 100644 --- a/crates/horizon-threads/src/lib.rs +++ b/crates/horizon-threads/src/lib.rs @@ -126,6 +126,38 @@ fn idle() -> bool { false } +/// How many stop requests (Ctrl-C, SIGTERM, SIGHUP) arrived since `catch_stop_signals`. +pub fn stop_requests() -> u32 { + STOP_REQUESTS.load(std::sync::atomic::Ordering::SeqCst) +} + +static STOP_REQUESTS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + +/// Count stop requests from outside instead of dying on them: vanilla's "Client Shutdown Thread" +/// (`Main.java`) halts the integrated server when the JVM shuts down, and the JVM does that on +/// these signals, so a killed game still saves. The caller's event loop turns the first request +/// into a normal quit; a second one (the save is stuck) ends the process at once. +#[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))] +pub fn catch_stop_signals() { + extern "C" fn handle(_: libc::c_int) { + if STOP_REQUESTS.fetch_add(1, Ordering::SeqCst) >= 1 { + // SAFETY: _exit is async-signal-safe; 130 is the shell's code for a Ctrl-C death. + unsafe { libc::_exit(130) } + } + } + let handler = handle as extern "C" fn(libc::c_int); + for signal in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] { + // SAFETY: the handler only touches an atomic and calls _exit, both async-signal-safe. + unsafe { + libc::signal(signal, handler as libc::sighandler_t); + } + } +} + +/// Windows and the other systems keep their default: a closed window is a `CloseRequested`. +#[cfg(not(any(target_vendor = "apple", target_os = "linux", target_os = "android")))] +pub fn catch_stop_signals() {} + #[cfg(test)] mod tests { /// The hint holds on the platforms that take it. From 09078949d784d48ae928c59038cb79674a86a538 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:36:29 +0100 Subject: [PATCH 006/195] Send a guest's explosion to the players once their turn ends An end crystal (or minecart) hit by a player on the server thread blew up with sound and damage but no explosion particles. The blast runs inside the guest's turn, while the host holds the players, so lan_explode had no hub to send the explosion packet through and dropped it. Queue it like a wind burst and send it when the turn is over. --- crates/horizon-client/src/game/creatures.rs | 4 ++++ crates/horizon-client/src/game/lan.rs | 3 ++- .../horizon-client/src/game/lan_particles.rs | 18 +++++++++++++++++- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..db6fca100 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -45,6 +45,9 @@ pub(super) struct Creatures { pub projectiles: Vec, /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). pub wind_bursts: Vec, + /// Explosion packets from a guest's turn, waiting for it to end + /// (centre, radius, blocks hit; game/lan_particles.rs). + pub lan_explosions: Vec<([f64; 3], f32, usize)>, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -1839,6 +1842,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } + self.flush_lan_explosions(); self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..29c405674 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1044,7 +1044,8 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); - // A mace's wind burst from a guest's attack. + // A blast from a guest's attack, and a mace's wind burst. + self.flush_lan_explosions(); let _ = self.flush_wind_bursts(); } diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 0e35392bf..d58f18f5f 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -194,7 +194,16 @@ impl Game<'_> { /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. - pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { + pub(super) fn lan_explode(&mut self, center: [f64; 3], radius: f32, block_count: usize) { + // In a guest's turn (their hit on an end crystal or a minecart) the + // host holds the players (`as_guest`): the packet waits for the turn + // to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures + .lan_explosions + .push((center, radius, block_count)); + return; + } let emitter = if radius < 2.0 { "minecraft:explosion" } else { @@ -208,6 +217,13 @@ impl Game<'_> { } } + /// The explosions guests' turns put off. + pub(super) fn flush_lan_explosions(&mut self) { + for (center, radius, block_count) in std::mem::take(&mut self.creatures.lan_explosions) { + self.lan_explode(center, radius, block_count); + } + } + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, /// no block particles, and for each player it pushed the push /// (`ServerExplosion.hitPlayers`), which only that client applies, as From 3287a74d64e64ac8b3aa976276987b9b4b93f83f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:00:40 +0100 Subject: [PATCH 007/195] Send fence knots to server players so leads tied to fences are drawn --- crates/horizon-client/src/game.rs | 8 ++++++ crates/horizon-client/src/game/lan.rs | 4 +-- .../horizon-client/src/game/lan_entities.rs | 28 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 10 +++++-- .../horizon-client/src/game/remote_objects.rs | 16 +++++++++-- 5 files changed, 60 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cdbd72d7b..0134dd9a1 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1459,6 +1459,12 @@ struct Game<'a> { /// Map textures waiting for the next HUD batch to upload them. map_patches: Vec, text_displays: std::collections::HashMap, + /// The fence knots a server tracks to this client, by entity id, at their + /// block (`LeashFenceKnotEntity`). + remote_knots: HashMap, + /// The entity ids a hosted server gives the knots its mobs hang on, by + /// block, while a lead is tied there. + knot_ids: HashMap<[i32; 3], u32>, text_display_vertices: usize, /// Player skin downloads, and which skin each atlas skin slot holds /// (least recently shown first). @@ -12291,6 +12297,8 @@ impl<'a> Game<'a> { dragon_model: prepared.dragon_model, map_patches: Vec::new(), text_displays: Default::default(), + remote_knots: Default::default(), + knot_ids: Default::default(), text_display_vertices: 0, skin_downloads: RefCell::new(horizon_client::skins::Downloader::new( std::env::current_dir() diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..c698e969e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -819,7 +819,7 @@ impl Game<'_> { out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { // The lead's holder: the player the mob sees (a guest, else the - // host) or another mob. A fence knot isn't an entity here. + // host), another mob or a fence knot (game/lan_entities.rs). let leash = m.extra.leash.and_then(|h| match h { Holder::Player => mob_players .get(&m.id) @@ -827,7 +827,7 @@ impl Game<'_> { .map(|g| g.entity_id) .or(host_entity), Holder::Mob(id) => Some(id as i32), - Holder::Knot(_) => None, + Holder::Knot(p) => self.knot_ids.get(&p).map(|&id| id as i32), }); let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); e.position = [m.position.x, m.position.y, m.position.z]; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cd4ba2fb8..e161b9a2b 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -225,6 +225,16 @@ impl Game<'_> { } out.push(e); } + for (p, &id) in &self.knot_ids { + // LeashFenceKnotEntity.getAddEntityPacket: the fence's block. + out.push(state( + id, + "minecraft:leash_knot", + p.map(f64::from), + 0.0, + false, + )); + } for p in &self.paintings { let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false); // Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its @@ -260,6 +270,24 @@ impl Game<'_> { /// Gives the entities Horizon keeps without an id one (`Entity.id`, from /// the same counter as the rest) before they are first tracked. pub(super) fn lan_assign_ids(&mut self) { + // LeashFenceKnotEntity: one per fence post with a lead on it + // (`notifyLeasheeRemoved` discards it once the last lead is gone). + let knots: Vec<[i32; 3]> = self + .mobs + .iter() + .filter(|m| !m.removed) + .filter_map(|m| match m.extra.leash { + Some(horizon_client::mobs::leash::Holder::Knot(p)) => Some(p), + _ => None, + }) + .collect(); + self.knot_ids.retain(|p, _| knots.contains(p)); + for p in knots { + self.knot_ids.entry(p).or_insert_with(|| { + self.next_entity += 1; + self.next_entity + }); + } let next = &mut self.next_entity; let mut give = |id: &mut u32| { if *id == 0 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..849d6dfab 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1808,7 +1808,8 @@ impl Game<'_> { } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), // ClientPacketListener.handleEntityLinkPacket: who holds a mob's - // lead (this player, another player or a mob), for the rope. + // lead (this player, another player, a mob or a fence knot), for + // the rope. C::SetEntityLink(p) => { let me = self.remote.as_ref().map(|r| r.entity_id); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) { @@ -1816,7 +1817,12 @@ impl Game<'_> { m.extra.leash = match p.dest { 0 => None, d if Some(d) == me => Some(Holder::Player), - d => Some(Holder::Mob(d as u32)), + d => match self.remote_knots.get(&(d as u32)) { + Some(&block) => Some(Holder::Knot(block)), + // Not a known knot yet: kept by id until the knot + // arrives (game/remote_objects.rs). + None => Some(Holder::Mob(d as u32)), + }, }; } } diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 251d277f3..3f39072e9 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -1,9 +1,10 @@ -//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! Boats, minecarts, armor stands, item frames, paintings and fence knots on a server's //! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, //! `handleSetEquipment`): the server simulates them, the client places them //! where it says and interpolates their moves like a mob's. use super::Game; use horizon_client::entities::{ArmorStand, ItemFrame, Painting}; +use horizon_client::mobs::leash::Holder; use horizon_core::geometry::Vec3; use horizon_protocol::entity_data::Value; use std::sync::Arc; @@ -24,7 +25,17 @@ impl Game<'_> { let at = Vec3::new(position[0], position[1], position[2]); let block = position.map(|v| v.floor() as i32); self.remove_remote_object(id); - if kind == "minecraft:text_display" { + if kind == "minecraft:leash_knot" { + // A lead that came before its knot waits as a mob holder with the + // knot's id (handleEntityLinkPacket's delayed holder); now it can + // be tied to the fence. + self.remote_knots.insert(id, block); + for m in &mut self.mobs { + if m.extra.leash == Some(Holder::Mob(id)) { + m.extra.leash = Some(Holder::Knot(block)); + } + } + } else if kind == "minecraft:text_display" { self.text_displays.insert( id as i32, super::text_displays::RemoteTextDisplay::new(position, yaw), @@ -292,6 +303,7 @@ impl Game<'_> { pub(super) fn remove_remote_object(&mut self, id: u32) { self.text_displays.remove(&(id as i32)); + self.remote_knots.remove(&id); self.carts.retain(|c| c.id != id); self.boats.retain(|b| b.id != id); self.armor_stands.retain(|a| a.id != id); From 5c0f7142f36cad8e1a1e7adffe3c6c5902328edb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:03:44 +0100 Subject: [PATCH 008/195] Draw the level events the client dropped: lava and torch smoke, drips, chorus, sniffer eggs, dragon fireball burst --- crates/horizon-client/src/game.rs | 51 ++++- crates/horizon-client/src/game/dragon.rs | 15 +- .../src/game/level_particles.rs | 205 ++++++++++++++++-- crates/horizon-client/src/particles.rs | 13 +- 4 files changed, 261 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cdbd72d7b..f042bc28d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2800,6 +2800,34 @@ impl Game<'_> { pos, data, } => self.composter_fill_event(pos, data == 1), + // LevelEventHandler 1504: the stalactite's drip particle. + LevelEvent::LevelEvent { id: 1504, pos, .. } => self.dripstone_drip_particle(pos), + // LevelEventHandler 2006: the dragon fireball's burst. + LevelEvent::LevelEvent { + id: 2006, + pos, + data, + } => self.dragon_fireball_burst(pos, data), + // LevelEventHandler 2009: a wet sponge drying. + LevelEvent::LevelEvent { id: 2009, pos, .. } => { + self.puffs_above_block(pos, horizon_client::particles::ParticleType::Cloud) + } + // LevelEventHandler 2012: a turtle egg laid. + LevelEvent::LevelEvent { + id: 2012, + pos, + data, + } => self.turtle_egg_particles(pos, data), + // LevelEventHandler 2014: a straw bed destroyed, with no sound. + LevelEvent::LevelEvent { + id: 2014, + pos, + data, + } => self.destroy_particles([pos.x, pos.y, pos.z], BlockStateId(data as u32)), + // LevelEventHandler 3009: a sniffer egg cracking. + LevelEvent::LevelEvent { id: 3009, pos, .. } => { + self.sniffer_egg_crack_particles(pos) + } LevelEvent::LevelEvent { id: id @ 3011..=3021, pos, @@ -2815,6 +2843,16 @@ impl Game<'_> { 1501 => Some(("minecraft:block.lava.extinguish", 0.5)), 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), + 1033 => Some(("minecraft:block.chorus_flower.grow", 1.0)), + 1034 => Some(("minecraft:block.chorus_flower.death", 1.0)), + 1046 => Some(( + "minecraft:block.pointed_dripstone.drip_lava_into_cauldron", + 2.0, + )), + 1047 => Some(( + "minecraft:block.pointed_dripstone.drip_water_into_cauldron", + 2.0, + )), 1030 => Some(("minecraft:block.anvil.use", 1.0)), 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), @@ -2826,12 +2864,12 @@ impl Game<'_> { }; if let Some((name, volume)) = sound { let pitch = match id { - 1009 => { + 1009 | 1501 | 1502 => { 2.6 + (self.world.random.next_float() - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1043 | 1044 => { + 1029 | 1030 | 1042 | 1043 | 1044 | 1046 | 1047 => { self.world.random.next_float() * 0.1 + 0.9 } _ => 1.0, @@ -2844,6 +2882,15 @@ impl Game<'_> { self.audio.play(name, c, volume, pitch); } } + // LevelEventHandler 1501 and 1502 draw their smoke after the sound. + match id { + 1501 => self.puffs_above_block( + pos, + horizon_client::particles::ParticleType::LargeSmoke, + ), + 1502 => self.torch_burnout_smoke(pos), + _ => {} + } } LevelEvent::Sound { pos, diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8c316deeb..c83018c82 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2089,11 +2089,16 @@ impl Game<'_> { duration: 600, from_dragon: false, }); - self.audio.play( - "minecraft:entity.dragon_fireball.explode", - Some([next.x, next.y, next.z]), - 1.0, - 1.0, + // DragonFireball.onHit: level event 2006 (the burst of dragon + // breath and the explosion sound) at its block position. + self.level_event_at( + 2006, + [ + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ], + 1, ); return false; } diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..e6593e7b9 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,11 +1,13 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles //! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a //! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax -//! off (3004) and scraping (3005). +//! off (3004) and scraping (3005), plus the smoke, drips, egg and dragon +//! fireball particles of 1501, 1502, 1504, 2006, 2009, 2012 and 3009. use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; -use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_core::{geometry::trig, position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; +use horizon_world::registry::BlockStateId; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { @@ -65,24 +67,42 @@ impl Game<'_> { } else { // ParticleUtils.spawnParticleInBlock: up to the // block's shape (a full block when air). - let inside = self.world.block(at[0], at[1], at[2]); - let height = if facts.is_air(inside) { - 1.0 - } else { - facts - .get(inside) - .outline - .iter() - .map(|b| b[4]) - .fold(0.0, f64::max) - }; - (at, count, 0.5, height, true) + (at, count, 0.5, self.block_shape_top(at), true) } } None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false), None => return, }; - let options = ParticleOptions::simple(ParticleType::HappyVillager); + self.spawn_particles(at, count, xz, height, floating, ParticleType::HappyVillager); + } + /// `BlockState.getShape(..).max(Y)` of the block at `at`, 1.0 for air. + fn block_shape_top(&self, at: [i32; 3]) -> f64 { + let facts = self.res.facts(); + let inside = self.world.block(at[0], at[1], at[2]); + if facts.is_air(inside) { + 1.0 + } else { + facts + .get(inside) + .outline + .iter() + .map(|b| b[4]) + .fold(0.0, f64::max) + } + } + /// `ParticleUtils.spawnParticles`: `count` slow particles spread over + /// `xz` blocks around `at` and `height` up, only above solid ground + /// unless floating ones are allowed. + fn spawn_particles( + &mut self, + at: [i32; 3], + count: i32, + xz: f64, + height: f64, + floating: bool, + ty: ParticleType, + ) { + let options = ParticleOptions::simple(ty); for _ in 0..count.max(0) { let r = self.particles.level_random(); let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02); @@ -101,6 +121,161 @@ impl Game<'_> { } } } + /// `LevelEventHandler` 2012 (a turtle egg laid on sand): + /// `ParticleUtils.spawnParticleInBlock` with happy villager sparks. + pub(super) fn turtle_egg_particles(&mut self, pos: BlockPos, count: i32) { + let at = [pos.x, pos.y, pos.z]; + let height = self.block_shape_top(at); + self.spawn_particles(at, count, 0.5, height, true, ParticleType::HappyVillager); + } + /// `LevelEventHandler` 3009 (a sniffer egg cracking on moss): + /// `spawnParticlesOnBlockFaces(.., EGG_CRACK, UniformInt.of(3, 6))`. + pub(super) fn sniffer_egg_crack_particles(&mut self, pos: BlockPos) { + let mut spawned = Vec::new(); + particles::on_block_faces_between( + self.particles.level_random(), + [pos.x, pos.y, pos.z], + 3, + 6, + |p, v| spawned.push((p, v)), + ); + let options = ParticleOptions::simple(ParticleType::EggCrack); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } + /// `LevelEventHandler` 1501 (lava put out) and 2009 (a wet sponge dried): + /// eight puffs just above the block, drawn after the sound. + pub(super) fn puffs_above_block(&mut self, pos: BlockPos, ty: ParticleType) { + let options = ParticleOptions::simple(ty); + for _ in 0..8 { + let r = self.particles.level_random(); + let x = f64::from(pos.x) + r.next_double(); + let z = f64::from(pos.z) + r.next_double(); + self.particles + .add(&options, [x, f64::from(pos.y) + 1.2, z], [0.0; 3]); + } + } + /// `LevelEventHandler` 1502 (a redstone torch burning out): five smoke + /// puffs inside the block, drawn after the sound. + pub(super) fn torch_burnout_smoke(&mut self, pos: BlockPos) { + let options = ParticleOptions::simple(ParticleType::Smoke); + for _ in 0..5 { + let r = self.particles.level_random(); + let x = f64::from(pos.x) + r.next_double() * 0.6 + 0.2; + let y = f64::from(pos.y) + r.next_double() * 0.6 + 0.2; + let z = f64::from(pos.z) + r.next_double() * 0.6 + 0.2; + self.particles.add(&options, [x, y, z], [0.0; 3]); + } + } + /// `LevelEventHandler` 2006 (`DragonFireball.onHit`): 200 dragon breath + /// particles thrown outwards, then the explosion sound when `data` is 1. + pub(super) fn dragon_fireball_burst(&mut self, pos: BlockPos, data: i32) { + for _ in 0..200 { + let r = self.particles.level_random(); + let dist = r.next_float() * 4.0; + let angle = r.next_float() * std::f32::consts::TAU; + let vx = f64::from(trig::cos(f64::from(angle)) * dist); + let vy = 0.01 + r.next_double() * 0.5; + let vz = f64::from(trig::sin(f64::from(angle)) * dist); + let options = ParticleOptions { + scale: dist, + ..ParticleOptions::simple(ParticleType::DragonBreath) + }; + self.particles.add( + &options, + [ + f64::from(pos.x) + vx * 0.1, + f64::from(pos.y) + 0.3, + f64::from(pos.z) + vz * 0.1, + ], + [vx, vy, vz], + ); + } + if data == 1 { + let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + self.audio.play( + "minecraft:entity.dragon_fireball.explode", + Some(at), + 1.0, + pitch, + ); + } + } + /// `SpeleothemBlock.isStalactite`: a speleothem whose tip points down. + fn is_stalactite(&self, state: BlockStateId) -> bool { + self.res.facts().get(state).has_class("SpeleothemBlock") + && self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("vertical_direction")) + .is_some_and(|d| d == "down") + } + /// `LevelEventHandler` 1504: `PointedDripstoneBlock.spawnDripParticle` at + /// the tip `pos`. The fluid above the stalactite's root picks the drip; + /// with none, the dimension's default (lava in the Nether). + pub(super) fn dripstone_drip_particle(&mut self, pos: BlockPos) { + let tip_state = self.world.block(pos.x, pos.y, pos.z); + if !self.is_stalactite(tip_state) { + return; + } + // findRootBlock: up through the same stalactite, at most 11 steps. + let tip_name = self.res.facts().get(tip_state).name.clone(); + let mut root = None; + for step in 1..11 { + let y = pos.y + step; + if !(horizon_client::chunk::MIN_Y + ..horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT) + .contains(&y) + { + break; + } + let state = self.world.block(pos.x, y, pos.z); + if self.res.facts().get(state).name != tip_name { + root = Some(y); + break; + } + if !self.is_stalactite(state) { + break; + } + } + let Some(root_y) = root else { + return; + }; + let above = self.world.block(pos.x, root_y + 1, pos.z); + let above_facts = self.res.facts().get(above); + let nether = self.dim == super::Dim::Nether; + let fluid = if &*above_facts.name == "minecraft:mud" && !nether { + horizon_client::blocks::Fluid::Water + } else { + above_facts.fluid + }; + let ty = match fluid { + horizon_client::blocks::Fluid::Water => ParticleType::DrippingDripstoneWater, + horizon_client::blocks::Fluid::Lava => ParticleType::DrippingDripstoneLava, + horizon_client::blocks::Fluid::None if nether => ParticleType::DrippingDripstoneLava, + horizon_client::blocks::Fluid::None => ParticleType::DrippingDripstoneWater, + }; + let offset = self + .pack + .context + .tables + .offset(tip_state, pos.x, pos.z) + .unwrap_or([0.0; 3]); + // The tip shape starts 5/16 up; the particle sits a pixel below that. + self.particles.add( + &ParticleOptions::simple(ty), + [ + f64::from(pos.x) + 0.5 + offset[0], + f64::from(pos.y) + 5.0 / 16.0 - 0.0625, + f64::from(pos.z) + 0.5 + offset[2], + ], + [0.0; 3], + ); + } /// `ServerLevel.globalLevelEvent`: heard by every player on the server /// (an end portal opening, the dragon's death roar): here, and sent to /// every guest whatever their dimension. diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..3099069ba 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -751,6 +751,17 @@ fn next_double_between(random: &mut impl RandomSource, min: f64, max: f64) -> f6 pub fn on_block_faces( random: &mut impl RandomSource, pos: [i32; 3], + emit: impl FnMut([f64; 3], [f64; 3]), +) { + on_block_faces_between(random, pos, 3, 5, emit); +} +/// `ParticleUtils.spawnParticlesOnBlockFaces` with `UniformInt.of(min, max)` +/// particles per face (3009 sniffer egg cracks use 3 to 6). +pub fn on_block_faces_between( + random: &mut impl RandomSource, + pos: [i32; 3], + min: i32, + max: i32, mut emit: impl FnMut([f64; 3], [f64; 3]), ) { const FACES: [[i32; 3]; 6] = [ @@ -762,7 +773,7 @@ pub fn on_block_faces( [1, 0, 0], ]; for face in FACES { - let count = random.next_int_bound(5 - 3 + 1).unwrap_or(0) + 3; + let count = random.next_int_bound(max - min + 1).unwrap_or(0) + min; for _ in 0..count { // getRandomSpeedRanges, then spawnParticleOnFace with step factor 0.55. let speed: [f64; 3] = std::array::from_fn(|_| next_double_between(random, -0.5, 0.5)); From 4825e537ccc51d123bcc0f97d777e3330a570f52 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:05:51 +0100 Subject: [PATCH 009/195] Tilt a server player's camera towards the hit The server never sent ClientboundHurtAnimationPacket, and the client ignored the yaw it carried, so a player on a server got the flash but the camera never tilted towards where the hit came from. ServerPlayer.indicateDamage now runs where the hit's knockback is dealt (and with no direction for hits that have none), the packet goes out when the guest's turn ends, and the client keeps the yaw as Player.hurtDir for GameRenderer.bobHurt. --- crates/horizon-client/src/game/creatures.rs | 4 +++ crates/horizon-client/src/game/fov.rs | 2 +- crates/horizon-client/src/game/lan_actions.rs | 7 +++++ crates/horizon-client/src/game/remote.rs | 3 ++- crates/horizon-client/src/health.rs | 27 +++++++++++++++++++ 5 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..2f80be926 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1528,6 +1528,10 @@ impl Game<'_> { // hurt cooldown (a stronger hit there only adds its difference). if o.knockback { let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); + // dealDefaultKnockback's `indicateDamage`, unless blocked. + if o.blocked <= 0.0 { + player.health.indicate_damage(xd, zd, player.yaw); + } self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 95e2e1e6e..364f89189 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -114,7 +114,7 @@ impl Game<'_> { living: Some(HurtBob { hurt_time: p.health.hurt_animation_time as f32 - partial, hurt_duration: hurt.hurt_duration, - hurt_dir: 0.0, + hurt_dir: p.health.hurt_dir, death_time: self.death_time().map(|t| t as f32 + partial), }), player: Some(( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bbb0c37c0..e6869650b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -650,6 +650,13 @@ impl Game<'_> { g.sprinting = false; } m.sprinting = false; + // ServerPlayer.indicateDamage: the hit's direction to the player. + if let Some(yaw) = m.health.indicated_dir.take() { + g.send(&C::HurtAnimation(play::HurtAnimation { + id: g.entity_id, + yaw, + })); + } let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..c4571c3a9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2042,8 +2042,9 @@ impl Game<'_> { } C::HurtAnimation(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + // Player.animateHurt: the tilt turns around the yaw. if let Some(pl) = self.player.as_mut() { - pl.health.animate_hurt(); + pl.health.animate_hurt_dir(p.yaw); } } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 25c719bfb..b9670d065 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -163,6 +163,12 @@ pub struct PlayerHealth { pub hurt: State, /// Client hurt animation; fully blocked hits only refresh the server's hurt state. pub hurt_animation_time: i32, + /// `Player.hurtDir` on a client: the yaw `ClientboundHurtAnimationPacket` + /// gave, which `GameRenderer.bobHurt` tilts the camera around. + pub hurt_dir: f32, + /// `ServerPlayer.hurtDir` of a hit the player's client hasn't been told + /// of yet (`indicateDamage`). + pub indicated_dir: Option, pub dead: bool, pub sync_velocity: bool, pub game_time: i64, @@ -213,6 +219,8 @@ impl PlayerHealth { last_stamp: 0, }, hurt_animation_time: 0, + hurt_dir: 0.0, + indicated_dir: None, dead: false, sync_velocity: false, game_time: 0, @@ -260,6 +268,18 @@ impl PlayerHealth { self.hurt.hurt_time = 10; self.hurt_animation_time = 10; } + /// `LivingEntity.animateHurt(yaw)` on a player: the tilt restarts around + /// `yaw` (`Player.animateHurt` keeps it as `hurtDir`). + pub fn animate_hurt_dir(&mut self, yaw: f32) { + self.animate_hurt(); + self.hurt_dir = yaw; + } + /// `ServerPlayer.indicateDamage`: the hit's direction relative to where + /// the player looks, kept for the packet to its client. + pub fn indicate_damage(&mut self, xd: f64, zd: f64, yaw: f32) { + use horizon_core::geometry::trig::{RAD_TO_DEG, atan2}; + self.indicated_dir = Some((atan2(zd, xd) * f64::from(RAD_TO_DEG) - f64::from(yaw)) as f32); + } /// `LocalPlayer.hurtTo` with `flashOnSetHealth`: a drop below the current /// health starts the hurt animation; `damageCooldownTime` (20 on a drop, /// 10 on a gain) is what lets `Hud.extractPlayerHealth` blink the hearts. @@ -348,6 +368,13 @@ impl PlayerMotion { if outcome.hurt { h.hurt_animation_time = h.hurt.hurt_time; } + // `dealDefaultKnockback` ends in `indicateDamage` unless blocked: a + // hit with no direction of its own (`xd` and `zd` zero) is sent as + // the opposite of the player's yaw. A hit that has a direction + // replaces this (`mob_hits_player`). + if outcome.knockback && outcome.blocked <= 0.0 { + h.indicate_damage(0.0, 0.0, self.yaw); + } let after = h.health() + h.absorption(); if self.hurt_log.len() >= HURT_LOG { self.hurt_log.remove(0); From 6bc8a8b8899fc5be2e6c03485db8b6b9b47ff05d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:09:45 +0100 Subject: [PATCH 010/195] Send sweep, damage indicator and fishing particles to a server's players Vanilla sends these with ServerLevel.sendParticles, so every player nearby sees them. Horizon drew them only in the host window's own particle engine, which a window on a server (and a guest next to the host) never sees. One helper now sends a ClientboundLevelParticlesPacket with the same count, offset and speed to each player within 32 blocks. While the host holds the players (a guest's turn, a host hit on a guest) the packet waits and goes out when the tick ends. --- crates/horizon-client/src/game.rs | 22 +++++-- crates/horizon-client/src/game/creatures.rs | 9 +++ crates/horizon-client/src/game/fishing.rs | 2 + crates/horizon-client/src/game/lan.rs | 2 + .../horizon-client/src/game/lan_particles.rs | 61 +++++++++++++++++++ 5 files changed, 90 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cdbd72d7b..765354a0f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7455,13 +7455,15 @@ impl Game<'_> { } /// The visual and sound part of `Player.doSweepAttack` after a successful hit. pub(super) fn sweep_attack(&mut self, at: [f64; 3], from: Option<[f64; 3]>) { - self.particles.add( - &horizon_client::particles::ParticleOptions::simple( - horizon_client::particles::ParticleType::SweepAttack, - ), - at, - [0.0; 3], + let sweep = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::SweepAttack, ); + self.particles.add(&sweep, at, [0.0; 3]); + // Player.sweepAttack's `sendParticles(SWEEP_ATTACK, ..., 0, dx, 0, dz, 0)`: + // the offset is the one from the player to the particle. + let origin = from.unwrap_or(at); + let spread = [at[0] - origin[0], 0.0, at[2] - origin[2]]; + self.lan_send_particles(&sweep, at, spread, 0.0, 0); self.audio .play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0); } @@ -7625,6 +7627,14 @@ impl Game<'_> { 0.2, (actual * 0.5) as u32, ); + // The players a server serves are sent them too. + self.lan_send_particles( + &indicator, + [feet[0], feet[1] + height * 0.5, feet[2]], + [0.1, 0.0, 0.1], + 0.2, + (actual * 0.5) as u32, + ); } self.last_hurt_by_player .insert(self.mobs[index].id, self.lan_acting); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3a8562ee1..2fd9f588c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -49,6 +49,15 @@ pub(super) struct Creatures { pub elder_apparition: i32, /// The wandering trader spawner's clock. pub trader: super::wandering_trader::Spawner, + /// Particles from a guest's turn, waiting for it to end + /// (`lan_send_particles`: options, centre, spread, speed, count). + pub lan_particles: Vec<( + horizon_client::particles::ParticleOptions, + [f64; 3], + [f64; 3], + f64, + u32, + )>, } struct ProjWorld<'a, 'w> { w: &'a MobWorld<'w>, diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index d454df406..b62822beb 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -416,6 +416,8 @@ impl Game<'_> { let options = ParticleOptions::simple(kind); self.particles .send_particles(&options, at, spread, speed, count); + // The players a server serves are sent them too. + self.lan_send_particles(&options, at, spread, speed, count); } /// `FishingHook.tick`. pub(super) fn tick_fishing(&mut self) { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..af89844c6 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1046,6 +1046,8 @@ impl Game<'_> { self.lan = Some(host); // A mace's wind burst from a guest's attack. let _ = self.flush_wind_bursts(); + // Particles a guest's turn sent (sweep attack, damage indicator, a hook's splashes). + self.flush_lan_particles(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 0e35392bf..b1790686e 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -191,6 +191,67 @@ impl Game<'_> { } } + /// `ServerLevel.sendParticles` for the players a server serves: one + /// `ClientboundLevelParticlesPacket` to each player in the level whose + /// block is within 32 blocks of `at`. The window's own player is not + /// sent it (the caller draws it in this window). While the host holds + /// the players (a guest's turn through `as_guest`, a host's hit on a + /// guest) the packet waits for the turn to end so that it reaches every + /// player, the guest too. + pub(super) fn lan_send_particles( + &mut self, + options: &ParticleOptions, + at: [f64; 3], + spread: [f64; 3], + speed: f64, + count: u32, + ) { + if self.lan.is_none() { + // The server is running (its sounds are captured for the guests). + if self.audio.capture.is_some() { + self.creatures + .lan_particles + .push((options.clone(), at, spread, speed, count)); + } + return; + } + let Some(particle) = self.network_particle(options, None) else { + return; + }; + let Some(host) = self.lan.as_ref() else { + return; + }; + let body = C::LevelParticles(play::LevelParticles { + particle, + override_limiter: false, + always_show: false, + pos: at, + dist: spread.map(|d| d as f32), + max_speed: [speed as f32; 3], + count: count as i32, + randomization: 0, + }) + .encode(); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + // BlockPos.closerToCenterThan(at, 32): from the centre of the + // player's block. + let d: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if d < 32.0 * 32.0 { + g.sender.send(body.clone()); + } + } + } + + /// The particles guests' turns put off. + pub(super) fn flush_lan_particles(&mut self) { + for (options, at, spread, speed, count) in std::mem::take(&mut self.creatures.lan_particles) + { + self.lan_send_particles(&options, at, spread, speed, count); + } + } + /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. From 8697f3fd3f91a8e6f48d5ca19882413b7a55ba2b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:13:32 +0100 Subject: [PATCH 011/195] Furnaces: drying a wet sponge fills the bucket in the fuel slot --- crates/horizon-client/src/containers.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index d13c5e45b..b0e034e5b 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -639,6 +639,18 @@ impl Furnace { None => self.items[2] = Some(recipe.result.clone()), } *self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1; + // AbstractFurnaceBlockEntity.burn: drying a wet sponge fills + // the bucket in the fuel slot. + if self.items[0] + .as_ref() + .is_some_and(|i| &*i.item == "minecraft:wet_sponge") + && self.items[1] + .as_ref() + .is_some_and(|f| &*f.item == "minecraft:bucket") + { + self.items[1] = + Some(ItemStack::new("minecraft:water_bucket", 1)); + } if let Some(i) = self.items[0].as_mut() { i.count -= 1; if i.count == 0 { From e2781f7939dfb4451f356a60d6513e25a4a271fa Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:20:35 +0100 Subject: [PATCH 012/195] Apply suspicious stew effects when the stew is eaten --- crates/horizon-client/src/game/consume.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index 93d919911..37d27eeb8 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -57,6 +57,17 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.burp", self.feet(), 0.5, pitch); } + // SuspiciousStewEffects.onConsume, a ConsumableListener: each entry is + // added as a `MobEffectInstance(effect, duration)` (amplifier 0). + if let Some(data) = stack.extra.as_deref() { + for (id, duration) in &data.stew_effects { + if let Some(def) = horizon_client::brewing::effect(id) { + self.add_player_effect(horizon_client::effects::EffectInstance::new( + def.id, *duration, 0, + )); + } + } + } for effect in &consumable.effects { self.apply_consume_effect(effect); } From 30fa41ddbd4e85258e36a00f75e692976b7f3775 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:20:37 +0100 Subject: [PATCH 013/195] Make the fall, drowning, fire and freeze damage game rules work --- .../examples/probe/scene_motion_probe.rs | 1 + crates/horizon-client/src/game/chat.rs | 5 +++++ crates/horizon-client/src/health.rs | 19 +++++++++++++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/examples/probe/scene_motion_probe.rs b/crates/horizon-client/examples/probe/scene_motion_probe.rs index 21977eeab..523bd28a4 100644 --- a/crates/horizon-client/examples/probe/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -351,6 +351,7 @@ pub fn main() -> Result<()> { horizon_world::food::Difficulty::Hard, ][op["difficulty"].as_u64().unwrap() as usize], natural_regeneration: op["regenerate"].as_bool().unwrap(), + ..Default::default() }; } "food" => { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 5d3919c8b..e19e3669f 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -763,6 +763,11 @@ impl Game<'_> { pub(super) fn sync_rules(&mut self) { self.world.health_rules.natural_regeneration = self.ui.rules.bool("natural_health_regeneration"); + // Player.isInvulnerableTo: the damage-type rules. + self.world.health_rules.drowning_damage = self.ui.rules.bool("drowning_damage"); + self.world.health_rules.fall_damage = self.ui.rules.bool("fall_damage"); + self.world.health_rules.fire_damage = self.ui.rules.bool("fire_damage"); + self.world.health_rules.freeze_damage = self.ui.rules.bool("freeze_damage"); use horizon_world::food::Difficulty; self.world.health_rules.difficulty = match self.ui.difficulty { 0 => Difficulty::Peaceful, diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 25c719bfb..cf7397bf8 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -29,12 +29,22 @@ pub(crate) type State = HurtState; pub struct HealthRules { pub difficulty: Difficulty, pub natural_regeneration: bool, + /// The `drowning_damage`, `fall_damage`, `fire_damage` and + /// `freeze_damage` rules `Player.isInvulnerableTo` reads. + pub drowning_damage: bool, + pub fall_damage: bool, + pub fire_damage: bool, + pub freeze_damage: bool, } impl Default for HealthRules { fn default() -> Self { Self { difficulty: Difficulty::Normal, natural_regeneration: true, + drowning_damage: true, + fall_damage: true, + fire_damage: true, + freeze_damage: true, } } } @@ -604,8 +614,13 @@ impl ImmunityWorld for Environment<'_> { fn enchantment_immunity(&mut self) -> io::Result { Ok(false) } - fn damage_rule(&mut self, _: DamageRule) -> io::Result { - Ok(true) + fn damage_rule(&mut self, rule: DamageRule) -> io::Result { + Ok(match rule { + DamageRule::Drowning => self.rules.drowning_damage, + DamageRule::Fall => self.rules.fall_damage, + DamageRule::Fire => self.rules.fire_damage, + DamageRule::Freeze => self.rules.freeze_damage, + }) } fn changing_dimension(&mut self) -> io::Result { Ok(false) From f252941ac15a075b982d892b0c5d6924818a5a62 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:20:39 +0100 Subject: [PATCH 014/195] Charge melee exhaustion only when the hit hurts --- crates/horizon-client/src/game.rs | 12 ++++++---- crates/horizon-client/src/game/lan_actions.rs | 8 +++++-- crates/horizon-client/src/game/lan_pvp.rs | 23 ++++++++++++------- 3 files changed, 28 insertions(+), 15 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b397882cd..fbd6fd240 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7552,11 +7552,6 @@ impl Game<'_> { let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } let player = self.player.as_ref(); let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); if knockback_attack { @@ -7651,6 +7646,13 @@ impl Game<'_> { } } self.weapon_hit(index); + // Player.attack: causeFoodExhaustion(0.1F) only when the hit hurt + // (inside `if (wasHurt)`), after damageStatsAndHearts. + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } } else { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index bbb0c37c0..7cba4c162 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1468,9 +1468,13 @@ impl Game<'_> { if let Some(victim) = Self::pvp_victim(host, conn, id) { if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) && self.pvp_land(host, victim, &strike) - && strike.stops_sprint() { - self.as_guest(host, conn, |g| g.stop_sprint_after_extra_knockback()); + self.as_guest(host, conn, |g| { + g.pvp_exhaustion(); + if strike.stops_sprint() { + g.stop_sprint_after_extra_knockback(); + } + }); } return; } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 467c4537c..7b59681ed 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -82,9 +82,11 @@ impl Game<'_> { }; if let Some(strike) = self.pvp_strike() && self.pvp_land(&mut host, Victim::Guest(conn), &strike) - && strike.stops_sprint() { - self.stop_sprint_after_extra_knockback(); + self.pvp_exhaustion(); + if strike.stops_sprint() { + self.stop_sprint_after_extra_knockback(); + } } self.lan = Some(host); true @@ -102,8 +104,18 @@ impl Game<'_> { .map(|g| Victim::Guest(g.conn)) } + /// `Player.attack`'s `causeFoodExhaustion(0.1F)`, charged to the attacker + /// (the host, or a guest swapped in) only once the hit hurt the victim. + pub(super) fn pvp_exhaustion(&mut self) { + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } + } + /// The attacker's side of `Player.attack` (the host, or a guest swapped - /// in): the damage, the charge reset, the exhaustion and the swing. + /// in): the damage, the charge reset and the swing. pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; @@ -112,11 +124,6 @@ impl Game<'_> { let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } self.swing_arm(); Some(Strike { amount, From a8205dd80dc43779ec22d213e412ef97805553c6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:21:45 +0100 Subject: [PATCH 015/195] Infested blocks release their silverfish when broken --- crates/horizon-client/src/game.rs | 15 +++++++++++++++ crates/horizon-client/src/game/spawner.rs | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b397882cd..e5fe51b7c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3396,6 +3396,21 @@ impl Game<'_> { { self.hive_broken_by_player(pos, hive, honey, facing); } + // InfestedBlock.spawnAfterBreak: its silverfish comes out unless the + // tool has silk touch (#prevents_infested_spawns) or blocks don't drop. + if facts.name.starts_with("minecraft:infested_") + && !silk + && self.ui.rules.bool("block_drops") + { + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + if let Some(id) = self.spawn_mob("minecraft:silverfish", at, false) { + self.mob_poof(id); + } + } // SpawnerBlock.spawnAfterBreak pops its experience whatever the tool. let xp = if silk && &*facts.name != "minecraft:spawner" { 0 diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 538cb39e7..5dd907afb 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -253,7 +253,7 @@ impl Game<'_> { self.world.modified.insert((key.0 >> 4, key.2 >> 4)); } /// `LivingEntity.makePoofParticles` (entity event 20) for a mob. - fn mob_poof(&mut self, id: u32) { + pub(super) fn mob_poof(&mut self, id: u32) { let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; From d136dda0928f3150fead27675fa812eef83d8d66 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:08:48 +0100 Subject: [PATCH 016/195] Bee stings only poison on Normal and Hard --- crates/horizon-client/src/mobs/bee.rs | 19 +++++++++++++------ crates/horizon-client/src/mobs/spawning.rs | 4 ++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index 27d8e7c84..741a78df6 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -323,12 +323,19 @@ pub fn sting(m: &mut Mob, who: Who, cx: &mut Cx) { match who { Who::Player => { cx.events.push(MobEvent::AttackPlayer(amount, from)); - let seconds = if cx.w.difficulty.hard { 18 } else { 10 }; - cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:poison", - ticks: seconds * 20, - amplifier: 0, - }); + // Poison only on normal (10 s) and hard (18 s). + let seconds = match cx.w.difficulty.base { + 2 => 10, + 3 => 18, + _ => 0, + }; + if seconds > 0 { + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: seconds * 20, + amplifier: 0, + }); + } } Who::Mob(id) => cx.events.push(MobEvent::AttackMob { target: id, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..57ecb1692 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -37,6 +37,8 @@ pub struct LocalDifficulty { pub effective: f32, /// The world difficulty is hard. pub hard: bool, + /// The world difficulty id, 0 peaceful to 3 hard. + pub base: u8, } /// `DimensionType.MOON_BRIGHTNESS_PER_PHASE`. pub const MOON_BRIGHTNESS: [f32; 8] = [1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75]; @@ -49,6 +51,7 @@ impl LocalDifficulty { return Self { effective: 0.0, hard, + base, }; } let global = ((total as f32 - 72000.0) / 1_440_000.0).clamp(0.0, 1.0) * 0.25; @@ -61,6 +64,7 @@ impl LocalDifficulty { Self { effective: f32::from(base) * (0.75 + global + local), hard, + base, } } /// `getSpecialMultiplier`. From 790b191ed18f1e0fd839df8719a7d6300d3aac69 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:09:20 +0100 Subject: [PATCH 017/195] Bees let out of a sedated hive stay out for 400 ticks --- crates/horizon-client/src/mobs/bee.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index 27d8e7c84..c351439a5 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -421,10 +421,10 @@ pub fn drop_off_nectar(m: &mut Mob) { set_has_nectar(m, false); st(m).crops_grown = 0; } -/// `Bee.setStayOutOfHiveCountdown`, which in 26.3 only resets the time -/// without nectar. +/// `Bee.setStayOutOfHiveCountdown`: the bee will not enter a hive for 400 +/// ticks (the hive passes that when a sedated hive lets its bees out). pub fn set_stay_out_of_hive_countdown(m: &mut Mob) { - st(m).ticks_without_nectar = 0; + st(m).stay_out_of_hive = 400; } fn drop_hive(m: &mut Mob) { let b = st(m); From e553db9bb5505ce579134136f6349432f21d6f30 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:10:09 +0100 Subject: [PATCH 018/195] Let frogs take fall damage five points below the base amount --- crates/horizon-client/src/mobs/living.rs | 6 +++++- crates/horizon-client/src/mobs/species.rs | 1 - 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..f089b5355 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -629,7 +629,11 @@ impl Mob { return; } let power = self.fall_distance + 1.0e-6 - self.kind.safe_fall_distance; - let damage = (power * self.kind.fall_damage_multiplier).floor(); + let mut damage = (power * self.kind.fall_damage_multiplier).floor(); + // Frog.calculateFallDamage: five points less than the base damage. + if self.species() == super::Species::Frog { + damage -= 5.0; + } if damage > 0.0 { let at = [self.position.x, self.position.y, self.position.z]; let sound = if damage > 4.0 { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index f48a21fe9..fb62365a7 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1447,7 +1447,6 @@ impl Def { | S::IronGolem | S::Cat | S::Ocelot - | S::Frog | S::Slime | S::MagmaCube | S::Wither From 3615c65d18e24888cea2e6b3a7dda86c7ba5c7a6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:11:01 +0100 Subject: [PATCH 019/195] Make allays drop what they carry on death and use the default pickup delay when throwing --- crates/horizon-client/src/game/allays.rs | 3 ++- crates/horizon-client/src/mobs/drops.rs | 22 ++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index bed835663..dba4edfad 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -131,7 +131,8 @@ impl Game<'_> { let m = &mut self.mobs[i]; m.extra.ints[1] -= 1; m.extra.ints[3] = 60; - self.spawn_item(ItemStack::new(&item, 1), from, v, 40); + // ItemEntity.setDefaultPickUpDelay. + self.spawn_item(ItemStack::new(&item, 1), from, v, 10); if self.world.game_time % 7 == 0 && self.world.random.next_double() < 0.9 { const PITCHES: [f32; 16] = [ 0.5625, 0.625, 0.75, 0.9375, 1.0, 1.0, 1.125, 1.25, 1.5, 1.875, 2.0, 2.25, 2.5, diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index e5ccfd283..cdad5b7af 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -399,6 +399,15 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec (Vec 0 { + out.push(Drop::Item(loot_stack(&item, carried))); + } + if let Some(stack) = slot_item(m, "mainhand") + && !d.loot.prevents_equipment_drop(&stack) + { + out.push(Drop::Item(stack)); + clear_slot(m, "mainhand"); + } + } // dropEquipment: AbstractHorse's inventory, then a chested horse's chest. if equine::is_equine(s) { for stack in m.extra.items.iter().flatten() { From 9c3450622b8b94f69540e87fa4e629ab8e1c654c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:11:49 +0100 Subject: [PATCH 020/195] Update comparators when a copper golem moves items in or out of a chest --- crates/horizon-client/src/game/copper_golems.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 2f98e1c7e..db4e03b0b 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -44,13 +44,13 @@ impl Game<'_> { slot: usize, stack: Option, ) { - if let Some(e) = self - .world - .block_entities - .get_mut(&(chest[0], chest[1], chest[2])) + let key = (chest[0], chest[1], chest[2]); + if let Some(e) = self.world.block_entities.get_mut(&key) && let Some(s) = e.slots_mut().get_mut(slot) { *s = stack; + // TransportItemsBetweenContainers calls Container.setChanged. + self.container_changed(key); } } /// `ContainerOpenersCounter.recheckOpeners` every five ticks: the golems From b7c47ccbf9398b2131927f4c07d736f6228a2a4e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:11:52 +0100 Subject: [PATCH 021/195] Let a sneaking player open chest and hopper minecarts --- crates/horizon-client/src/game/minecarts.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..d7c57fca9 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1063,10 +1063,8 @@ impl Game<'_> { } self.riding = Some(self.carts[i].id); } + // AbstractMinecartContainer.interact: no sneak check. CartKind::Chest | CartKind::Hopper => { - if sneaking { - return false; - } let c = self.carts[i].clone(); let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); self.world From 0a5e80de7ba474d420e5c215cabb7ac134817a5b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:12:33 +0100 Subject: [PATCH 022/195] Step out of a minecart in vanilla's order --- crates/horizon-client/src/game/minecarts.rs | 30 +++++++++++++-------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..454b15245 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -942,7 +942,7 @@ impl Game<'_> { } true } - /// `getDismountLocationForPassenger`: beside the cart (across its motion), else on top. + /// `getDismountLocationForPassenger`: beside the cart (across its facing), else on top. pub(super) fn dismount_cart(&mut self, i: usize) { self.riding = None; let c = &self.carts[i]; @@ -952,17 +952,25 @@ impl Game<'_> { c.position.z.floor() as i32, ); let mut target = None; + // DismountHelper.offsetsForDirection of the cart's facing + // (Direction.fromYRot of its yaw): right, left, back right, back left, + // forward right, forward left, back, forward. + let step = |q: i32| [(0, 1), (-1, 0), (0, -1), (1, 0)][(q & 3) as usize]; + let facing = (f64::from(c.yaw) / 90.0 + 0.5).floor() as i32; + let (fx, fz) = step(facing); + let (rx, rz) = (-fz, fx); + let offsets = [ + (rx, rz), + (-rx, -rz), + (rx - fx, rz - fz), + (-rx - fx, -rz - fz), + (fx + rx, fz + rz), + (fx - rx, fz - rz), + (-fx, -fz), + (fx, fz), + ]; 'search: for dy in [0, 1, -1] { - for (dx, dz) in [ - (1, 0), - (-1, 0), - (0, 1), - (0, -1), - (1, 1), - (-1, -1), - (1, -1), - (-1, 1), - ] { + for (dx, dz) in offsets { let (x, y, z) = (bx + dx, by + dy, bz + dz); let below = self.res.facts().get(self.world.block(x, y - 1, z)); let here = self.res.facts().get(self.world.block(x, y, z)); From cc39d57e070d73b84080e031157704f2295529ce Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:12:42 +0100 Subject: [PATCH 023/195] Explosions empty and anger the bees of destroyed hives --- crates/horizon-client/src/game/beehives.rs | 2 +- crates/horizon-client/src/game/combat.rs | 4 +++ crates/horizon-client/src/game/creatures.rs | 10 ++++++- crates/horizon-client/src/game/explosion.rs | 29 +++++++++++++++++++++ crates/horizon-client/src/game/minecarts.rs | 4 ++- crates/horizon-client/src/game/tnt.rs | 4 ++- crates/horizon-client/src/game/wither.rs | 2 +- 7 files changed, 50 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index b7f7efb1a..258610f5e 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -196,7 +196,7 @@ impl Game<'_> { } /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) /// without a target go for a player in the same box. - fn anger_nearby_bees(&mut self, at: [i32; 3]) { + pub(super) fn anger_nearby_bees(&mut self, at: [i32; 3]) { let min = Vec3::new( f64::from(at[0]) - 8.0, f64::from(at[1]) - 6.0, diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 106e0e1a1..91cf5c61b 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -31,6 +31,10 @@ pub(super) struct CombatTracker { /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, + /// The blast now going off comes from a primed TNT, creeper, wither + /// skull, wither or TNT minecart, the sources that empty a hive they + /// destroy (`BeehiveBlock.getDrops`). + pub(super) hive_emptying_blast: bool, /// The player's fall distance before this tick's movement (as of the /// end of the last one). fall_before: f64, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..6e6610dcc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -915,7 +915,15 @@ impl Game<'_> { self.note_attacker("minecraft:explosion", id); } self.combat.explosion_source = source_mob; - let result = self.explode(at, radius); + // Only a creeper or a wither empties the hives it blows up. + let empties_hives = source_mob + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .is_some_and(|m| matches!(m.species(), Species::Creeper | Species::Wither)); + let result = if empties_hives { + self.with_hive_emptying_blast(|g| g.explode(at, radius)) + } else { + self.explode(at, radius) + }; self.combat.explosion_source = None; result? } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..805e4ebff 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -489,6 +489,15 @@ impl Game<'_> { ); } } + /// Runs an explosion whose source empties the hives it destroys + /// (`BeehiveBlock.getDrops`: primed TNT, creeper, wither skull, wither, + /// TNT minecart). + pub(super) fn with_hive_emptying_blast(&mut self, blast: impl FnOnce(&mut Self) -> R) -> R { + self.combat.hive_emptying_blast = true; + let result = blast(self); + self.combat.hive_emptying_blast = false; + result + } /// `Level.explode` on the server: positions, entities, blocks, fire; then /// the client's explosion sound. pub(super) fn server_explode( @@ -600,6 +609,22 @@ impl Game<'_> { // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); + let is_hive = matches!(&*name, "minecraft:beehive" | "minecraft:bee_nest"); + // BeehiveBlock.getDrops: the bees of a hive blown up by TNT, a + // creeper, a wither skull, a wither or a TNT minecart come out. + if is_hive && self.combat.hive_emptying_blast { + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + self.empty_hive( + pos, + horizon_client::beehive::facing_step(facing.as_deref()), + horizon_client::beehive::Release::Emergency, + ); + } if let Some(entity) = self.world.block_entities.get(&key).cloned() { let custom = self.world.block_names.get(&key).cloned(); self.pending.record(pos, &entity, &name, custom); @@ -631,6 +656,10 @@ impl Game<'_> { } self.pending.clear(pos); self.level_set(pos, self.world.air)?; + // BeehiveBlock.onExplosionHit: the bees about turn on the player. + if is_hive { + self.anger_nearby_bees(pos); + } // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then // getRandomShortFuse(80); no game event. if is_tnt && self.ui.rules.bool("tnt_explodes") { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..d21c99a55 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -640,7 +640,9 @@ impl Game<'_> { // The cart is the explosion's source: it is gone before the blast // looks for entities, so it can't hit itself. self.carts.retain(|x| x.id != c.id); - let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); + let _ = self.with_hive_emptying_blast(|g| { + g.server_explode(at, power, BlockInteraction::Destroy, false) + }); } /// `MinecartHopper.suckInItems`: items above, into the five slots. fn hopper_cart_pickup(&mut self, c: &mut Minecart) { diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 6bd2ae956..14d80c90e 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -178,7 +178,9 @@ impl Game<'_> { ]; self.tnts.remove(i); count -= 1; - self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?; + self.with_hive_emptying_blast(|g| { + g.server_explode(center, 4.0, BlockInteraction::Destroy, false) + })?; } else { i += 1; } diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 8084425ca..789e5cf68 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -130,7 +130,7 @@ impl Game<'_> { if let Some(id) = owner { self.note_attacker("minecraft:explosion", id); } - self.explode(at, 1.0) + self.with_hive_emptying_blast(|g| g.explode(at, 1.0)) } } /// Wither skulls drawn as the skull model, blue when dangerous. From a5fa40d2eea6609a3c567601059cdcf29415c4a3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:12:48 +0100 Subject: [PATCH 024/195] Fire the villager_trade trigger so What a Deal! can be earned --- .../horizon-client/src/game/advancements.rs | 21 ++++++++++++++ crates/horizon-client/src/game/lan_trading.rs | 7 ++++- crates/horizon-client/src/game/trading.rs | 28 +++++++++++++++---- 3 files changed, 50 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..f7bafd767 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -708,6 +708,27 @@ impl Game<'_> { let it = item_view(stack); self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); } + /// `TradeTrigger`: the villager and the item the trade gave. + pub(super) fn trigger_trade(&mut self, villager: &EntityView, stack: &ItemStack) { + let me = self.player_entity(); + let villager = villager.clone(); + let it = item_view(stack); + self.trigger("minecraft:villager_trade", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let vctx = adv::Entities { + this: Some(&villager), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::conditions(&c["villager"], &vctx, w) + && adv::item(&c["item"], &it, w) + }); + } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { let Some(definition) = self.pack.assets.registry.state(state).cloned() else { diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 1bec9809d..9e8fa55b3 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -276,7 +276,12 @@ impl Game<'_> { g.carried = menu.carried.take(); } self.register_exploration_maps(made); - gm.merchant.session = self.merchant_apply(session, gm.merchant.mob); + let (session, traded) = self.merchant_apply(session, gm.merchant.mob); + gm.merchant.session = session; + if !traded.is_empty() { + // The guest's own statistic and advancements. + self.as_guest(host, conn, |g| g.merchant_traded(gm.merchant.mob, &traded)); + } self.drop_guest_items(host, gi, dropped); self.lan_send_offers(host, conn, &mut gm, false); self.lan_send_merchant_content(host, conn, &mut gm); diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 87e0c18c6..4eaf00ec9 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -398,18 +398,21 @@ impl Game<'_> { .as_ref() .and_then(|s| s.merchant.as_ref()) .and_then(|m| m.mob); - let session = self.merchant_apply(session, mob); + let (session, traded) = self.merchant_apply(session, mob); + self.merchant_traded(mob, &traded); if let Some(m) = self.station.as_mut().and_then(|s| s.merchant.as_mut()) { m.session = session; } } - /// What a menu click's session did, applied to the world and its mob. + /// What a menu click's session did, applied to the world and its mob; + /// with the result of each trade made, for `merchant_traded`. pub(super) fn merchant_apply( &mut self, session: Box, mob: Option, - ) -> Box { + ) -> (Box, Vec) { let mut session = session; + let mut traded = Vec::new(); let events = std::mem::take(&mut session.events); let (villager, origin) = (session.villager, session.origin); if let Some(m) = mob.and_then(|id| self.mobs.iter_mut().find(|m| m.id == id)) { @@ -438,11 +441,26 @@ impl Game<'_> { }; self.audio.play(sound, Some(origin), 1.0, pitch); } - merchant::Event::Traded(_) => self.stats.custom("traded_with_villager", 1), + merchant::Event::Traded(index) => { + traded.extend(session.offers.get(index).map(|o| o.result.clone())); + } merchant::Event::TradeSound => {} } } - session + (session, traded) + } + /// `MerchantResultSlot.checkTakeAchievements` and `AbstractVillager.notifyTrade` + /// for each trade made: the statistic and the `villager_trade` trigger. + pub(super) fn merchant_traded(&mut self, mob: Option, results: &[ItemStack]) { + for result in results { + self.stats.custom("traded_with_villager", 1); + let villager = mob + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| self.mob_entity(m)); + if let Some(villager) = villager { + self.trigger_trade(&villager, result); + } + } } /// `Villager.customServerAiStep`: the TRADE reputation event of the last /// trade, a tick later; the prices follow the new reputation. From 00e2cfec294cae389cb742de5e022f2e43f4ae10 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:12:57 +0100 Subject: [PATCH 025/195] Let tadpoles be fed slime balls to grow up faster --- crates/horizon-client/src/game/creatures.rs | 13 +++++++++++++ crates/horizon-client/src/game/remote_mob_use.rs | 7 +++++-- crates/horizon-client/src/mobs/species.rs | 2 +- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..fb3cea6bb 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2797,6 +2797,19 @@ impl Game<'_> { self.trigger_entity("minecraft:tame_animal", "entity", &view); } } + // Tadpole.feed: frog food ages it by a tenth of the time left to + // grow into a frog (it grows on its next tick once past 24000). + Species::Tadpole if is_food && !m.extra.age_locked => { + consume = true; + let left = 24_000 - m.extra.age; + m.extra.age += ((left / 20) as f32 * 0.1) as i32 * 20; + // One happy villager particle at rest about the body. + self.particles_around_mob( + self.mobs[index].id, + "happy_villager", + horizon_client::particles::Burst::HORSE_EATING, + ); + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs index 9575cf925..bd38c7301 100644 --- a/crates/horizon-client/src/game/remote_mob_use.rs +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -66,8 +66,11 @@ impl Game<'_> { | Species::Salmon | Species::TropicalFish | Species::Pufferfish - | Species::Axolotl - | Species::Tadpole => item == "minecraft:water_bucket", + | Species::Axolotl => item == "minecraft:water_bucket", + // Tadpole.mobInteract: frog food, else the bucket. + Species::Tadpole => { + item == "minecraft:water_bucket" || m.kind.food.iter().any(|f| f.as_str() == item) + } Species::Armadillo => item == "minecraft:brush", // ZombieVillager.mobInteract: CONSUME for a golden apple. Species::ZombieVillager => item == "minecraft:golden_apple", diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index f48a21fe9..3f3ff4e31 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1581,7 +1581,7 @@ impl Def { S::Bee => "bee_food", S::Turtle => "turtle_food", S::Armadillo => "armadillo_food", - S::Frog => "frog_food", + S::Frog | S::Tadpole => "frog_food", S::Axolotl => "axolotl_food", S::Hoglin => "hoglin_food", S::Strider => "strider_food", From a4d0f76edd735cc6bcb5a9452679759564ebb3b8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:08 +0100 Subject: [PATCH 026/195] Count movement statistics as vanilla does Fall distance is counted once per landing from 2 blocks or more instead of on every downward tick. Riding counts only for the mounts vanilla lists (pig, horse family by full distance, strider, happy ghast, nautilus, boat, minecart), and airborne sideways moves over 25 cm count as flying. --- crates/horizon-client/src/game.rs | 4 +++ crates/horizon-client/src/game/lan_actions.rs | 7 ++++ crates/horizon-client/src/game/stats.rs | 32 +++++++++++++------ 3 files changed, 33 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..5ac53d7df 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4421,6 +4421,10 @@ impl Game<'_> { }; self.audio.play(name, Some(feet), volume, pitch); } + // Player.causeFallDamage: a fall of 2 blocks or more counts. + MotionEvent::Fall(horizon_client::landing::FallEvent::Statistic(cm)) => { + self.stats.custom("fall_one_cm", cm) + } MotionEvent::Fall(event) => self.landing_block_updates(&event), MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0ad14bbcc..644ec7785 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2252,6 +2252,13 @@ impl Game<'_> { // ServerEntity.sendChanges sends it as it is after this travel. let marked = std::mem::take(&mut player.health.sync_velocity); let velocity = marked.then_some(player.velocity); + // Player.causeFallDamage: a fall of 2 blocks or more counts. + for event in &events { + if let MotionEvent::Fall(horizon_client::landing::FallEvent::Statistic(cm)) = event + { + game.stats.custom("fall_one_cm", *cm); + } + } game.record_combat(&events); (events, velocity) }); diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index 7f64c6bb2..68a574eb1 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -256,9 +256,8 @@ impl Game<'_> { .fluid == horizon_client::blocks::Fluid::Water; let on_ground = p.ground.on_ground; - let (sprinting, flying, gliding, swimming) = ( + let (sprinting, gliding, swimming) = ( p.sprinting, - p.flying, p.fall_flying, p.pose == horizon_client::pose::Pose::Swimming, ); @@ -272,15 +271,27 @@ impl Game<'_> { }); let s = &mut self.stats; match riding { - Some(Ok(horizon_client::mobs::Species::Pig)) => s.custom("pig_one_cm", total), - Some(Ok(horizon_client::mobs::Species::Strider)) => s.custom("strider_one_cm", total), - Some(Ok(sp)) if horizon_client::mobs::equine::is_equine(sp) => { - s.custom("horse_one_cm", horizontal) + Some(Ok(sp)) => { + use horizon_client::mobs::Species; + // `checkRidingStatistics`: only these mounts count, the horse + // family by the full 3D distance; any other mount nothing. + match sp { + Species::Pig => s.custom("pig_one_cm", total), + Species::Strider => s.custom("strider_one_cm", total), + Species::HappyGhast => s.custom("happy_ghast_one_cm", total), + Species::Nautilus | Species::ZombieNautilus => { + s.custom("nautilus_one_cm", total) + } + sp if horizon_client::mobs::equine::is_equine(sp) => { + s.custom("horse_one_cm", total) + } + _ => {} + } } - Some(_) => { + Some(Err(())) => { if self.boats.iter().any(|b| Some(b.id) == self.riding) { s.custom("boat_one_cm", total) - } else { + } else if self.carts.iter().any(|c| Some(c.id) == self.riding) { s.custom("minecart_one_cm", total) } } @@ -300,8 +311,9 @@ impl Game<'_> { } } None if gliding => s.custom("aviate_one_cm", total), - None if flying => s.custom("fly_one_cm", horizontal), - None if d.y < 0.0 => s.custom("fall_one_cm", (-d.y * 100.0).round() as i32), + // Airborne and not gliding: more than 25 cm sideways per move + // (creative flight, or a long jump), not only flying. + None if horizontal > 25 => s.custom("fly_one_cm", horizontal), None => {} } } From 2a0824cf5f532d1671e71b878dd03673be6ec0a2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:15 +0100 Subject: [PATCH 027/195] Invisible players are harder for mobs to notice Mobs now scale their detection range by 0.7 times the worn armor fraction (at least 0.1) when the player has Invisibility, like vanilla's getVisibilityPercent. --- .../horizon-client/examples/probe/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/lan_mobs.rs | 1 + crates/horizon-client/src/mobs.rs | 15 +++++++++++++++ crates/horizon-client/src/mobs/animal_brain.rs | 3 +-- crates/horizon-client/src/mobs/goals.rs | 5 +---- crates/horizon-client/src/mobs/happy_ghast.rs | 3 +-- 7 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index ecdf02901..033ef6faa 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1050,6 +1050,7 @@ pub fn main() -> horizon_client::Result<()> { off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..ae31d23dd 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -186,6 +186,7 @@ impl Game<'_> { off_hand: None, head: self.armor[0].as_ref().map(|s| s.item.clone()), armor_cover: self.armor.iter().filter(|a| a.is_some()).count() as f32 / 4.0, + invisible: self.potions.effects.get("invisibility").is_some(), spectator: self.spectator(), gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..88632c7aa 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -363,6 +363,7 @@ mod tests { off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..ba9d63080 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1448,6 +1448,8 @@ pub struct PlayerView { pub off_hand: Option>, pub head: Option>, pub armor_cover: f32, + /// The Invisibility effect (`isInvisible`). + pub invisible: bool, pub spectator: bool, /// `PiglinAi.isWearingSafeArmor`: some golden armour. pub gold_armor: bool, @@ -1468,6 +1470,19 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +impl PlayerView { + /// `LivingEntity.getVisibilityPercent` without the worn-skull scaling. + pub fn visibility_percent(&self) -> f64 { + let mut visibility = 1.0; + if self.sneaking { + visibility *= 0.8; + } + if self.invisible { + visibility *= 0.7 * f64::from(self.armor_cover).max(0.1); + } + visibility + } +} #[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index bd0eb9c90..d928c34ee 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -625,8 +625,7 @@ fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { // TargetingConditions.forNonCombat(): in range (scaled by the // player's visibility, at least 2) and in sight. let Some(p) = &w.player else { return false }; - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let r = (range * visibility).max(2.0); + let r = (range * p.visibility_percent()).max(2.0); p.alive && !p.spectator && m.distance_sqr(p.position) <= r * r && m.sees(w, who) } Who::Mob(id) => { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 7f73e32c4..c44614571 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -601,10 +601,7 @@ impl Mob { return false; } // LivingEntity.getVisibilityPercent - let mut visibility = 1.0; - if p.sneaking { - visibility *= 0.8; - } + let mut visibility = p.visibility_percent(); if let Some(head) = &p.head { let skull = match self.species() { Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index bd4c5b1f3..efcbf5246 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -364,8 +364,7 @@ impl Goal for GhastTempt { let Some(p) = &cx.w.player else { return false }; // getNearestPlayer(TargetingConditions.forNonCombat() // .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too. - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let range = (16.0_f64 * visibility).max(2.0); + let range = (16.0_f64 * p.visibility_percent()).max(2.0); p.alive && !p.spectator && (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand)) From e2a399aff0ee5463e9059a9a3dd49cb67e5167db Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:19 +0100 Subject: [PATCH 028/195] Reopen signs on right click and apply dyes, ink sacs and honeycomb Right-clicking a placed sign opened an empty inventory screen. It now opens the editor for the side the player faces, or plays the waxed-sign fail sound. Dyes, glow ink sacs, ink sacs and honeycomb change the colour, glow or wax of the side the player faces and are used up. --- crates/horizon-client/src/game.rs | 9 ++ crates/horizon-client/src/game/sign_edit.rs | 152 +++++++++++++++++++- 2 files changed, 160 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..35371a766 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3014,6 +3014,11 @@ impl Game<'_> { self.open_command_block(key); return; } + // SignBlock.useWithoutItem: the text editor, not a container. + if horizon_client::signs::sign_kind(&name).is_some() { + self.use_sign_empty_hand(pos); + return; + } if &*name == "minecraft:crafting_table" { self.craft_size = 3; self.craft_table = Some(pos); @@ -3519,6 +3524,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_sign_applicator(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(true); + } if self.use_jukebox(hit.pos, held.as_ref()) { self.swing_arm(); return Ok(true); diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 2f50ad9ab..ea0abad3e 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -5,7 +5,8 @@ use super::{Game, lan::LanHost}; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, - signs::wood_type, + items::ItemStack, + signs::{DYE_TEXT, wood_type}, }; use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use std::time::Instant; @@ -22,6 +23,155 @@ pub(super) struct SignEditor { } impl Game<'_> { + /// `SignBlockEntity.getSlotPlayerIsFacing`: whether the player stands in + /// front of the sign's text (within 90 degrees of its facing). + fn facing_sign_front(&self, pos: (i32, i32, i32)) -> bool { + let Some(player) = self.player.as_ref() else { + return true; + }; + let state = self.world.block(pos.0, pos.1, pos.2); + let Some(state) = self.pack.assets.registry.state(state) else { + return true; + }; + let prop = |key: &str| state.properties.get(key).map(String::as_str); + // getYRotationDegrees: a wall sign's `Direction.toYRot`, a standing or + // ceiling sign's rotation segment. + let y_rot = if state.name.contains("_wall_") { + match prop("facing") { + Some("west") => 90.0, + Some("north") => 180.0, + Some("east") => 270.0, + _ => 0.0, + } + } else { + prop("rotation") + .and_then(|r| r.parse::().ok()) + .unwrap_or(0.0) + * 22.5 + }; + // getSignHitboxCenterPosition: only a wall sign's board is off-centre, + // against the wall it hangs on. + let centre = if state.name.ends_with("_wall_sign") { + match y_rot as i32 { + 90 => (0.9375, 0.5), + 180 => (0.5, 0.9375), + 270 => (0.0625, 0.5), + _ => (0.5, 0.0625), + } + } else { + (0.5, 0.5) + }; + let xd = player.position.x - (f64::from(pos.0) + centre.0); + let zd = player.position.z - (f64::from(pos.2) + centre.1); + let player_y_rot = (zd.atan2(xd).to_degrees() - 90.0) as f32; + // Mth.degreesDifferenceAbs. + let diff = (player_y_rot - y_rot).rem_euclid(360.0); + let diff = if diff >= 180.0 { 360.0 - diff } else { diff }; + diff <= 90.0 + } + /// `SignBlock.useWithoutItem` (the block's `OpenMenu` effect): a waxed + /// sign plays the failed-interaction sound; otherwise a player who may + /// build edits the side they face. + pub(super) fn use_sign_empty_hand(&mut self, pos: [i32; 3]) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&key) else { + return; + }; + if sign.waxed { + self.audio.play( + "minecraft:block.sign.waxed_interact_fail", + Some(pos.map(|v| f64::from(v) + 0.5)), + 1.0, + 1.0, + ); + } else if self.may_build() { + let front = self.facing_sign_front(key); + self.open_sign_editor(key, front); + } + } + /// `SignBlock.useItemOn` with a `SignApplicator` in hand (dyes, ink sacs, + /// honeycomb): the item changes the side the player faces and is used up. + /// Whether it did; a sign it does not apply to goes on to the empty hand. + pub(super) fn use_sign_applicator(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + let Some(stack) = held else { + return false; + }; + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&key) else { + return false; + }; + if sign.waxed || !self.may_build() { + return false; + } + let item = &*stack.item; + let dye = if item.ends_with("_dye") { + self.res + .items() + .get(&stack.item) + .and_then(|i| i.dye.clone()) + } else { + None + }; + let colour = dye.and_then(|d| DYE_TEXT.iter().position(|(n, _)| *n == d)); + if !matches!( + item, + "minecraft:honeycomb" | "minecraft:glow_ink_sac" | "minecraft:ink_sac" + ) && colour.is_none() + { + return false; + } + let front = self.facing_sign_front(key); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return false; + }; + let centre = pos.map(|v| f64::from(v) + 0.5); + let sound = if item == "minecraft:honeycomb" { + // HoneycombItem.tryApplyToSign: waxes any sign, empty or not. + sign.waxed = true; + "minecraft:item.honeycomb.wax_on" + } else { + let side = if front { + &mut sign.front + } else { + &mut sign.back + }; + // SignApplicator.canApplyToSign: the side must have text. + if side.is_empty() { + return false; + } + match colour { + Some(c) if side.color != c as u8 => { + side.color = c as u8; + "minecraft:item.dye.use" + } + None if item == "minecraft:glow_ink_sac" && !side.glowing => { + side.glowing = true; + "minecraft:item.glow_ink_sac.use" + } + None if item == "minecraft:ink_sac" && side.glowing => { + side.glowing = false; + "minecraft:item.ink_sac.use" + } + _ => return false, + } + }; + if item == "minecraft:honeycomb" { + self.level_event_at(3003, pos, 0); + } + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.mark_block_entity_updated(key); + let state = self.world.block(pos[0], pos[1], pos[2]); + self.post_block_game_event( + "minecraft:block_change", + pos, + self.sculk_actor(), + Some(state), + ); + self.stats.add("used", &stack.item, 1); + self.consume_held(); + self.trigger_block("minecraft:item_used_on_block", pos, stack); + true + } /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { self.sign_edit = Some(SignEditor { From 329ce1b724aa72ee67dc1cfeeaeb884acb541399 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:27 +0100 Subject: [PATCH 029/195] Make armadillos shed scutes on their own Armadillos never dropped scutes because nothing ran their shed timer. Follow Armadillo.customServerAiStep: count down 5 to 10 minutes, then drop a scute, play the sound and post the entity_place game event. --- crates/horizon-client/src/game/creatures.rs | 18 +++++++++++++++ crates/horizon-client/src/mobs.rs | 6 +++++ crates/horizon-client/src/mobs/ai.rs | 25 +++++++++++++++++++++ 3 files changed, 49 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..9a78bc2e5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1221,6 +1221,24 @@ impl Game<'_> { m.ai.aggressive |= aggressive; } } + MobEvent::ShedScute { mob, at, pitch } => { + // shouldDropLoot: the `mob_drops` rule. + if self.ui.rules.bool("mob_drops") { + let table = "minecraft:gameplay/armadillo_shed"; + let drops = self.sequence_loot(table, table, None); + for d in drops { + self.spawn_at_location(Vec3::new(at[0], at[1], at[2]), 0.0, d); + } + self.audio.play( + "minecraft:entity.armadillo.scute_drop", + Some(at), + 1.0, + pitch, + ); + let ctx = self.who_context(Some(Who::Mob(mob)), None); + self.post_game_event("minecraft:entity_place", at, ctx); + } + } MobEvent::GiftLoot { table, at } => { let drops = self.res diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..315bfdce2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1131,6 +1131,12 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// `Armadillo.customServerAiStep`: the armadillo sheds a scute. + ShedScute { + mob: u32, + at: [f64; 3], + pitch: f32, + }, /// A lead snaps or loses its holder: the lead item drops when asked. LeashBreak { mob: u32, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..8259ddccb 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -307,6 +307,10 @@ fn generic(m: &mut Mob) { g.add(5, Stroll::avoiding_water(if rabbit { 0.6 } else { 1.0 })); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); + if m.kind.species == Species::Armadillo { + // Armadillo's constructor: pickNextScuteDropTime. + m.extra.egg_time = next_scute_time(m); + } } } /// Subclasses of `net.minecraft.world.entity.monster.Monster`. @@ -930,9 +934,30 @@ fn server_ai_step( } m.jump_control_tick(); } +/// `Armadillo.pickNextScuteDropTime`: 5 to 10 minutes. +fn next_scute_time(m: &mut Mob) -> i32 { + m.random.next_int_bound(20 * 60 * 5).unwrap_or(0) + 20 * 60 * 5 +} +/// `Armadillo.customServerAiStep`: the scute timer. A baby only resets it +/// (`shouldDropLoot`); the game checks the `mob_drops` rule. +fn armadillo_server_ai_step(m: &mut Mob, events: &mut Vec) { + m.extra.egg_time -= 1; + if m.alive() && m.extra.egg_time <= 0 { + if !m.is_baby() { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + events.push(MobEvent::ShedScute { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + pitch, + }); + } + m.extra.egg_time = next_scute_time(m); + } +} fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { match m.species() { Species::Rabbit => super::rabbit::server_ai_step(m), + Species::Armadillo => armadillo_server_ai_step(m, cx.events), Species::Sheep => {} Species::Zombie | Species::Husk From 84aba7b3d494f6d1315214c41a27464e14e8be87 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:27 +0100 Subject: [PATCH 030/195] Count talking to villagers under vanilla's statistic name The statistic was written as talk_to_villager, but vanilla's key is talked_to_villager, so the statistics screen and scoreboard criteria always showed 0. Wandering traders already count through the same code. --- crates/horizon-client/src/game/trading.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 87e0c18c6..bd43e5af2 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -245,7 +245,7 @@ impl Game<'_> { self.handle_mob_events(events)?; return Ok(true); } - self.stats.custom("talk_to_villager", 1); + self.stats.custom("talked_to_villager", 1); self.ensure_offers(index); let m = &self.mobs[index]; let trade = m.extra.trade.as_deref().cloned().unwrap_or_default(); From 5fa423169f8fe5791f4cf31ee5b97e485806e46a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:51 +0100 Subject: [PATCH 031/195] Fire player_hurt_entity and entity_hurt_player advancement triggers --- crates/horizon-client/src/advancements.rs | 46 ++++++++++++ crates/horizon-client/src/game.rs | 9 +++ .../horizon-client/src/game/advancements.rs | 71 +++++++++++++++++++ crates/horizon-client/src/game/creatures.rs | 35 +++++++++ crates/horizon-client/src/game/trident.rs | 13 +++- 5 files changed, 173 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..62e7f365f 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -703,6 +703,52 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo } true } +/// A damage event as `DamagePredicate` sees it. +#[derive(Clone, Debug, Default)] +pub struct DamageView { + /// The damage type id (`minecraft:arrow`). + pub kind: String, + /// `DamageSource.getDirectEntity` and `getEntity`. + pub direct: Option, + pub source: Option, + /// `DamageSource.isDirect`: the direct entity is the causing one. + pub is_direct: bool, + /// The damage before and after the shield took its share. + pub original: f32, + pub actual: f32, + pub blocked: bool, +} +/// `DamagePredicate`, with its `DamageSourcePredicate` as `type`. +pub fn damage(v: &Value, d: &DamageView, w: &dyn World, origin: [f64; 3]) -> bool { + if v.is_null() { + return true; + } + let by = |key: &str, e: &Option| { + v[key].is_null() || e.as_ref().is_some_and(|e| entity(&v[key], e, w, origin)) + }; + if !range_f(&v["dealt"], f64::from(d.original)) + || !range_f(&v["taken"], f64::from(d.actual)) + || !by("source_entity", &d.source) + || v["blocked"].as_bool().is_some_and(|b| b != d.blocked) + { + return false; + } + let ty = &v["type"]; + let tags_ok = ty["tags"].as_array().into_iter().flatten().all(|t| { + let tag = t["id"].as_str().unwrap_or(""); + let tag = tag.strip_prefix('#').unwrap_or(tag); + w.in_tag("damage_type", tag, &d.kind) == t["expected"].as_bool().unwrap_or(true) + }); + let direct_ok = ty["direct_entity"].is_null() + || d.direct + .as_ref() + .is_some_and(|e| entity(&ty["direct_entity"], e, w, origin)); + let source_ok = ty["source_entity"].is_null() + || d.source + .as_ref() + .is_some_and(|e| entity(&ty["source_entity"], e, w, origin)); + tags_ok && direct_ok && source_ok && ty["is_direct"].as_bool().is_none_or(|b| b == d.is_direct) +} /// The entities a loot-style condition list may refer to. pub struct Entities<'a> { pub this: Option<&'a EntityView>, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..44ae588cb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7602,6 +7602,15 @@ impl Game<'_> { None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic), }; let landed = self.hurt_by_player(index, amount, source); + if landed { + let victim = self.mob_entity(&self.mobs[index]); + self.player_hit( + &victim, + creatures::damage_type(source.kind, true), + None, + amount, + ); + } if let Some(p) = self.player.as_mut() { if p.attack_log.len() >= 64 { p.attack_log.remove(0); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..ab783cbfa 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -180,6 +180,14 @@ impl adv::World for View<'_, '_> { "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), "entity_type" => self.0.res.mob_data().entity_has(tag, id), "worldgen/biome" => self.0.res.mob_data().biome_has(tag, id), + "damage_type" => self + .0 + .res + .stations() + .enchantments + .damage_tags + .get(tag) + .is_some_and(|t| t.contains(id)), _ => false, } } @@ -681,6 +689,69 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w) }); } + /// `PlayerHurtEntityTrigger`: the player, the damage and the victim. + pub(super) fn trigger_player_hurt_entity( + &mut self, + victim: &EntityView, + damage: &adv::DamageView, + ) { + let me = self.player_entity(); + let (victim, damage) = (victim.clone(), damage.clone()); + self.trigger("minecraft:player_hurt_entity", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let vctx = adv::Entities { + this: Some(&victim), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + && adv::conditions(&c["entity"], &vctx, w) + }); + } + /// The player's hit on `victim` as `LivingEntity.hurtServer` reports it: + /// `kind` damage of `amount` from `direct` (the player's own hand when + /// `None`), nothing blocked. + pub(super) fn player_hit( + &mut self, + victim: &EntityView, + kind: &str, + direct: Option, + amount: f32, + ) { + let me = self.player_entity(); + self.trigger_player_hurt_entity( + victim, + &adv::DamageView { + kind: kind.to_owned(), + is_direct: direct.is_none(), + direct: direct.or_else(|| Some(me.clone())), + source: Some(me), + original: amount, + actual: amount, + blocked: false, + }, + ); + } + /// `EntityHurtPlayerTrigger`: the player and the damage it took. + pub(super) fn trigger_entity_hurt_player(&mut self, damage: &adv::DamageView) { + let me = self.player_entity(); + let damage = damage.clone(); + self.trigger("minecraft:entity_hurt_player", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + }); + } /// A player condition plus one item (`item` key). pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) { let me = self.player_entity(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..e7395c3f0 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1544,6 +1544,23 @@ impl Game<'_> { self.hurt_armor(amount); self.thorns(from); } + // LivingEntity.hurtServer: ENTITY_HURT_PLAYER, unless it returned + // early (invulnerable, or inside the hurt cooldown). + if outcome.hurt || outcome.sound { + let source = attacker + .or(owner) + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| self.mob_entity(m)); + self.trigger_entity_hurt_player(&horizon_client::advancements::DamageView { + kind: damage_type.to_owned(), + direct: source.clone().filter(|_| !projectile), + is_direct: !projectile, + source, + original: amount, + actual: amount - outcome.blocked, + blocked: outcome.blocked > 0.0, + }); + } if raised { self.after_block(outcome, amount, attacker, projectile); } @@ -2111,6 +2128,24 @@ impl Game<'_> { .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { self.last_hurt_by_player.insert(id, self.lan_acting); + if hurt && let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let spectral = p.arrow.as_ref().is_some_and(|a| { + &*a.pickup_item.item == "minecraft:spectral_arrow" + }); + let direct = horizon_client::advancements::EntityView { + kind: if spectral { + "minecraft:spectral_arrow" + } else { + "minecraft:arrow" + } + .into(), + position: [p.position.x, p.position.y, p.position.z], + ..Default::default() + }; + self.player_hit(&victim, "minecraft:arrow", Some(direct), amount); + } } hurt } diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index c31094596..04a1be415 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -311,9 +311,10 @@ impl Game<'_> { }); let damage = 8.0 + if aquatic { 2.5 * impaling } else { 0.0 }; t.dealt_damage = true; + let mut hurt = false; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { let from = Some([t.position.x, t.position.y, t.position.z]); - m.damage( + hurt = m.damage( damage, Damage { kind: DamageKind::Arrow, @@ -322,6 +323,16 @@ impl Game<'_> { }, ); } + if hurt && let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let direct = horizon_client::advancements::EntityView { + kind: "minecraft:trident".into(), + position: [t.position.x, t.position.y, t.position.z], + ..Default::default() + }; + self.player_hit(&victim, "minecraft:trident", Some(direct), damage); + } self.audio.play( "minecraft:item.trident.hit", Some([t.position.x, t.position.y, t.position.z]), From 8d77913ea524f60ea52c7ac22ccba3092f5d7409 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:10 +0100 Subject: [PATCH 032/195] Note blocks play on a left click, and take mob heads on top Mining a note block now plays its note and counts the play_noteblock statistic. A mob head used on the top face is placed instead of tuning the block. --- crates/horizon-client/src/game.rs | 8 +++-- crates/horizon-world/src/level/interact.rs | 35 ++++++++++++++++++---- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..3548bf15a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2510,9 +2510,13 @@ impl Game<'_> { self.process_level_events() } fn attack_block(&mut self, pos: [i32; 3]) -> Result<()> { - self.with_level(|b, level, ticks| { - b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])); + let note = self.with_level(|b, level, ticks| { + b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])) }); + // NoteBlock.attack awards the statistic. + if note { + self.stats.custom("play_noteblock", 1); + } self.process_level_events() } /// Track which chunks are ticking (Ticks needs chunk load/unload). diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 7b2195c34..ed7c03dfb 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -513,20 +513,26 @@ impl Behaviours { sim.game_event_state(pos, "minecraft:block_change", next); } - /// The state change of `RedStoneOreBlock.attack` when mining begins. + /// `BlockBehaviour.attack` when mining begins: `RedStoneOreBlock.attack` + /// lights the ore, `NoteBlock.attack` plays the note. True for a note + /// block, whose player also earns the `play_noteblock` statistic. pub fn attack_block( &self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, - ) { + ) -> bool { let mut sim = self.sim(level, ticks); let state = sim.state(pos); - if self.data(state).chain.contains(&Class::RedStoneOre) - && !self.table.bool(state, self.props.lit) - { + let chain = &self.data(state).chain; + if chain.contains(&Class::Note) { + sim.note_play(pos, state); + return true; + } + if chain.contains(&Class::RedStoneOre) && !self.table.bool(state, self.props.lit) { sim.set_block_and_update(pos, self.table.set_bool(state, self.props.lit, true)); } + false } /// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and @@ -595,6 +601,25 @@ impl Behaviours { if self.data(state).chain.contains(&Class::CopperGolemStatue) { return self.turn_statue(level, ticks, pos, state, item); } + // NoteBlock.useItemOn: a mob head on the top face is placed, not tuned + // (`#minecraft:noteblock_top_instruments`). + if face == Direction::Up + && self.data(state).chain.contains(&Class::Note) + && item.is_some_and(|i| { + matches!( + i, + "minecraft:zombie_head" + | "minecraft:skeleton_skull" + | "minecraft:creeper_head" + | "minecraft:dragon_head" + | "minecraft:wither_skeleton_skull" + | "minecraft:piglin_head" + | "minecraft:player_head" + ) + }) + { + return InteractionResult::Pass; + } self.use_without_item(level, ticks, pos, face, hit, player) } From 79bfb8fcb81860893bd4664d4f3e86effd015eef Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:26 +0100 Subject: [PATCH 033/195] Let a brush take a scute off an armadillo Right-clicking an adult armadillo with a brush did nothing. Follow Armadillo.mobInteract: drop a scute from the brush loot table, play the brush sound, post the entity_interact game event and wear the brush by 16. --- crates/horizon-client/src/game/creatures.rs | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..0d4e94601 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2507,6 +2507,14 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.interact_armadillo(index, &item) { + if let Some(stack) = &held { + let target = self.mob_entity(&self.mobs[index]); + self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target); + } + self.swing_arm(); + return Ok(true); + } if self.interact_copper_golem(index, &item) { self.swing_arm(); return Ok(true); @@ -2876,6 +2884,50 @@ impl Game<'_> { } Ok(true) } + /// `Armadillo.mobInteract`: a brush brushes a scute off an adult + /// (`brushOffScute`) and loses 16 durability. + fn interact_armadillo(&mut self, index: usize, item: &str) -> bool { + let m = &self.mobs[index]; + if item != "minecraft:brush" + || m.species() != Species::Armadillo + || !m.alive() + || m.is_baby() + { + return false; + } + let (id, at) = (m.id, m.position); + let feet = [at.x, at.y, at.z]; + let tool = self.held().cloned(); + let table = "minecraft:brush/armadillo"; + for d in self.sequence_loot(table, table, tool.as_ref()) { + self.spawn_at_location(at, 0.0, d); + } + self.audio + .play("minecraft:entity.armadillo.brush", Some(feet), 1.0, 1.0); + let ctx = self.who_context(Some(Who::Mob(id)), None); + self.post_game_event("minecraft:entity_interact", feet, ctx); + // ItemStack.hurtAndBreak(16). + if !self.creative + && let Some(stack) = tool + { + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); + if max > 0 { + let loss = self.durability_loss(&stack, 16); + let slot = self.held_slot(); + if let Some(held) = self.stack_in_mut(slot).as_mut() { + held.damage += loss; + if held.damage >= max { + *self.stack_in_mut(slot) = None; + } + } + } + } + true + } pub(super) fn damage_held_tool(&mut self) { if self.creative { return; From 8691d9a8e88dcdd3f25783a42f24cd00af293eaa Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:34 +0100 Subject: [PATCH 034/195] Let players harvest a full beehive with shears or a glass bottle --- crates/horizon-client/src/game.rs | 4 + crates/horizon-client/src/game/beehives.rs | 107 +++++++++++++++++++++ 2 files changed, 111 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..01442b5c4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3539,6 +3539,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_beehive(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } match self.use_respawn_anchor(hit.pos, held.as_ref())? { respawn_anchor::AnchorUse::Charged => { self.swing_arm(); diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index b7f7efb1a..dfd4382a8 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -3,8 +3,10 @@ //! player breaks the hive or fire reaches it. use super::Game; use horizon_client::{ + Result, beehive::{self, Beehive, HiveHost, Release}, containers::BlockEntity, + items::ItemStack, mobs::{Mob, Who, bee}, }; use horizon_core::{ @@ -194,6 +196,111 @@ impl Game<'_> { } self.anger_nearby_bees(at); } + /// `BeehiveBlock.useItemOn` with `held` in the acting hand: shears take + /// the honeycombs and a glass bottle a honey bottle from a full hive + /// (honey level 5), then the honey level resets and, unless a campfire + /// smokes the hive, the bees come out angry. True when it took the click. + pub(super) fn use_beehive(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> Result { + let Some(held) = held else { return Ok(false) }; + let shears = &*held.item == "minecraft:shears"; + if !shears && &*held.item != "minecraft:glass_bottle" { + return Ok(false); + } + let state = self.world.block(pos[0], pos[1], pos[2]); + if !matches!( + &*self.res.facts().get(state).name, + "minecraft:beehive" | "minecraft:bee_nest" + ) { + return Ok(false); + } + let prop = |key: &str| { + self.pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key).cloned()) + }; + if prop("honey_level").and_then(|v| v.parse::().ok()) != Some(5) { + return Ok(false); + } + let facing = beehive::facing_step(prop("facing").as_deref()); + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + if shears { + // dropHoneycomb (harvest/beehive), the shear sound, hurtAndBreak. + for stack in self.sequence_loot( + "minecraft:harvest/beehive", + "minecraft:harvest/beehive", + Some(held), + ) { + self.pop_resource(pos, stack); + } + self.audio + .play("minecraft:block.beehive.shear", at, 1.0, 1.0); + self.damage_held(1); + self.post_block_game_event("minecraft:shear", pos, self.sculk_actor(), None); + } else { + // shrink(1), then the honey bottle in the hand, the inventory or + // on the ground. + self.audio.play("minecraft:item.bottle.fill", at, 1.0, 1.0); + let cell = self.held_mut(); + if let Some(s) = cell.as_mut() { + s.count -= 1; + if s.count == 0 { + *cell = None; + } + } + let bottle = ItemStack::new("minecraft:honey_bottle", 1); + if self.held().is_none() { + *self.held_mut() = Some(bottle); + } else if let Some(rest) = self.give(bottle) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + self.post_block_game_event("minecraft:fluid_pickup", pos, self.sculk_actor(), None); + } + self.stats.add("used", &held.item, 1); + let smokey = beehive::smokey(&self.mob_world_base(&[]), pos); + let key = (pos[0], pos[1], pos[2]); + if !smokey + && matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.bees.is_empty()) + { + self.anger_nearby_bees(pos); + } + // resetHoneyLevel. + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set(pos, reset)?; + } + if !smokey + && let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) + { + // emptyAllLivingFromHive: the bees within 4 blocks of the player + // go for them. + let released = hive.release_all( + pos, + facing, + None, + Release::Emergency, + &mut GameHive { game: self }, + ); + self.world + .block_entities + .put(key, BlockEntity::Beehive(hive)); + if let Some(p) = self.player_view().map(|p| p.position) { + for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) { + if m.distance_sqr(p) <= 16.0 { + m.ai.target = Some(Who::Player); + } + } + } + } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, held); + Ok(true) + } /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) /// without a target go for a player in the same box. fn anger_nearby_bees(&mut self, at: [i32; 3]) { From 4c72a3a44f41278aa0481f95acf0d184bf540421 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:42 +0100 Subject: [PATCH 035/195] Make a detector rail's comparator read the minecart on it --- crates/horizon-client/src/game.rs | 43 +++++++++++++++++++++ crates/horizon-client/src/game/minecarts.rs | 29 +++++++++++++- 2 files changed, 71 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..cc8cf7f1d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -541,6 +541,8 @@ struct GameLevel<'w> { player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, + /// Each minecart's kind and comparator signal, in `cart_boxes` order. + cart_signals: Vec<(minecarts::CartKind, i32)>, /// The other entities that keep blocks from being placed into them. blockers: Blockers<'w>, biomes: &'w Biomes, @@ -609,6 +611,37 @@ impl EntityObstructionWorld for BuildingObstruction { } } impl GameLevel<'_> { + /// `DetectorRailBlock.getAnalogOutputSignal`: a powered rail reads the + /// minecart on it, a command block cart first (its success count, which + /// is 0 here), else the first container cart's fullness. + fn detector_rail_signal(&self, pos: BlockPos, powered: bool) -> i32 { + if !powered { + return 0; + } + let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); + let area = Aabb::new( + Vec3::new(x + 0.2, y, z + 0.2), + Vec3::new(x + 0.8, y + 0.8, z + 0.8), + ); + let mut container = None; + for ((lo, hi), &(kind, signal)) in self.cart_boxes.iter().zip(&self.cart_signals) { + let cart = Aabb::new( + Vec3::new(lo[0], lo[1], lo[2]), + Vec3::new(hi[0], hi[1], hi[2]), + ); + if !area.intersects(cart) { + continue; + } + match kind { + minecarts::CartKind::CommandBlock => return 0, + minecarts::CartKind::Chest | minecarts::CartKind::Hopper => { + container = container.or(Some(signal)); + } + _ => {} + } + } + container.unwrap_or(0) + } /// Every entity box that blocks building: the players who aren't /// spectators, the minecarts and the `Blockers` (a removed mob or a marker /// armor stand, whose box is empty, doesn't). @@ -666,6 +699,14 @@ impl LevelAccess for GameLevel<'_> { state: BlockStateId, _direction: Direction, ) -> i32 { + if let Some(s) = self.registry.state(state) + && s.name == "minecraft:detector_rail" + { + return self.detector_rail_signal( + pos, + s.properties.get("powered").is_some_and(|v| v == "true"), + ); + } if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) { return signal; } @@ -2448,6 +2489,7 @@ impl Game<'_> { ) }) .collect(); + let cart_signals = self.cart_signals(); let guest_boxes = self.lan_block_trigger_boxes(); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, @@ -2465,6 +2507,7 @@ impl Game<'_> { }; let mut level = GameLevel { cart_boxes, + cart_signals, blockers, world: &mut self.world, facts: self.res.facts(), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..08eb20e02 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -9,7 +9,7 @@ use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, containers::BlockEntity, - items::ItemStack, + items::{ItemStack, Items}, mesher::Vertex, mobs::{Part, anim::Poses}, particles::{ParticleOptions, ParticleType}, @@ -194,6 +194,17 @@ impl Minecart { fn horizontal(&self) -> f64 { self.velocity.x.hypot(self.velocity.z) } + /// `AbstractContainerMenu.getRedstoneSignalFromContainer` of `slots`. + fn container_signal(slots: &[Option], items: &Items) -> i32 { + let mut total = 0.0f32; + for s in slots.iter().flatten() { + let max = items.get(&s.item).map_or(64, |i| i.max_stack).min(64); + total += s.count as f32 / max as f32; + } + total /= slots.len().max(1) as f32; + // Mth.lerpDiscrete(total, 0, 15) + (total * 14.0).floor() as i32 + i32::from(total > 0.0) + } } pub(super) struct CartModels { pub models: HashMap, @@ -1046,6 +1057,22 @@ impl Game<'_> { } best } + /// Each cart's kind and comparator signal, for the detector rail + /// (`DetectorRailBlock.getAnalogOutputSignal`). A cart whose menu is open + /// counts the items in that menu. + pub(super) fn cart_signals(&self) -> Vec<(CartKind, i32)> { + self.carts + .iter() + .map(|c| { + let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); + let slots = match self.world.block_entities.get(&key) { + Some(BlockEntity::Chest(open)) => open, + _ => &c.items, + }; + (c.kind, Minecart::container_signal(slots, self.res.items())) + }) + .collect() + } /// `interact`: ride, open, fuel or ignite the cart under the crosshair. pub(super) fn interact_cart(&mut self) -> bool { let Some((i, d)) = self.cart_hit() else { From 5b9a66089e9bcabcad2a9f864be534fd35f841a7 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:43 +0100 Subject: [PATCH 036/195] Give a partial item pickup the random pitch of a full pickup --- crates/horizon-client/src/game.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..57f817a00 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2390,8 +2390,14 @@ impl Game<'_> { pickups::Taken::Item(Box::new(item.clone())), pickups::Collector::Player, ); + // handleTakeItemEntity: the random pitch of a full pickup. + let pitch = ((self.world.random.next_float() + - self.world.random.next_float()) + * 0.7 + + 1.0) + * 2.0; self.audio - .play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); + .play("minecraft:entity.item.pickup", Some(feet), 0.2, pitch); } item.stack = rest; } From c273a7271ed3dbc53c28ad50784f2cbb69d04e76 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:59 +0100 Subject: [PATCH 037/195] Make breeze shots follow the world difficulty and aim higher at riders --- .../examples/probe/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/lan_mobs.rs | 1 + crates/horizon-client/src/mobs.rs | 5 +++++ crates/horizon-client/src/mobs/monster_brain.rs | 16 ++++++++++++---- crates/horizon-client/src/mobs/spawning.rs | 4 ++++ crates/horizon-client/src/mobs/world.rs | 4 ++++ 7 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index ecdf02901..d3b091490 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1060,6 +1060,7 @@ pub fn main() -> horizon_client::Result<()> { uuid: PLAYER_UUID, allies: Default::default(), remote: false, + passenger: false, } }); let mut scratch = LegacyRandom::new(0); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..17d518c3a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -196,6 +196,7 @@ impl Game<'_> { uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), remote: false, + passenger: self.riding.is_some(), }) } /// Biome facts at a position for finalizeSpawn and variant rules. diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..746a712a4 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -373,6 +373,7 @@ mod tests { uuid: [0; 4], allies: Default::default(), remote: false, + passenger: false, } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..240ab4218 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1223,6 +1223,8 @@ pub struct Seen { pub active_raid: bool, /// A copper golem's `openedChestPos` (`ContainerUser.hasContainerOpen`). pub opened_chest: Option<[i32; 3]>, + /// `isPassenger`. + pub passenger: bool, /// A villager's reputation of the player (`getPlayerReputation`). pub player_rep: i32, /// `isPushable` and pushed by others (`Entity.push(Entity)` moves it). @@ -1298,6 +1300,7 @@ impl Mob { hurt_by: m.ai.last_hurt_by.map(|w| (w, m.ai.last_hurt_by_time)), active_raid: raider::has_active_raid(m), opened_chest: m.extra.opened_chest, + passenger: m.extra.mount.is_some(), player_rep: match (villager, player) { (true, Some(uuid)) => villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid)), _ => 0, @@ -1467,6 +1470,8 @@ pub struct PlayerView { /// A LAN guest: its own client moves it, and touching mobs push it there /// (`EntitySelector.pushableBy` on the client). pub remote: bool, + /// `isPassenger`. + pub passenger: bool, } #[derive(Clone)] pub struct MobWorld<'a> { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 9456c00a1..827360406 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -1137,6 +1137,7 @@ struct Quarry { position: Vec3, head_yaw: f32, height: f64, + passenger: bool, } fn quarry(w: &MobWorld, who: Who) -> Option { let t = w.target_info(who)?; @@ -1148,6 +1149,7 @@ fn quarry(w: &MobWorld, who: Who) -> Option { position: t.position, head_yaw, height: t.bounds.max_position().y - t.bounds.min_position().y, + passenger: t.passenger, }) } /// `BreezeUtil.randomPointBehindTarget`. @@ -1233,7 +1235,8 @@ fn shoot_tick(m: &mut Mob, cx: &mut Bx) { let firing = super::breeze::firing_y(m); let (xd, yd, zd) = ( q.position.x - m.position.x, - q.position.y + q.height * 0.3 - firing, + // target.getY(target.isPassenger() ? 0.8 : 0.3). + q.position.y + q.height * if q.passenger { 0.8 } else { 0.3 } - firing, q.position.z - m.position.z, ); let start = Vec3::new(m.position.x, firing, m.position.z); @@ -1242,14 +1245,19 @@ fn shoot_tick(m: &mut Mob, cx: &mut Bx) { start, Some(Who::Mob(m.id)), ); - // The new entity's own random spreads the shot (5 - difficulty * 4 at - // normal): not the breeze's. + // The new entity's own random spreads the shot (5 - difficulty id * 4): + // not the breeze's. let mut own = LegacyRandom::new( cx.now .wrapping_mul(0x5DEE_CE66) .wrapping_add(i64::from(m.id)), ); - p.shoot(&mut own, [xd, yd, zd], 0.7, -3.0); + p.shoot( + &mut own, + [xd, yd, zd], + 0.7, + 5.0 - f32::from(cx.w.difficulty.id) * 4.0, + ); cx.events.push(MobEvent::Projectile(p)); breeze_sound(m, cx, "entity.breeze.shoot", 1.5); } diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..bbb8e2e46 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -37,6 +37,8 @@ pub struct LocalDifficulty { pub effective: f32, /// The world difficulty is hard. pub hard: bool, + /// `Difficulty.getId`: 0 peaceful to 3 hard. + pub id: u8, } /// `DimensionType.MOON_BRIGHTNESS_PER_PHASE`. pub const MOON_BRIGHTNESS: [f32; 8] = [1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75]; @@ -49,6 +51,7 @@ impl LocalDifficulty { return Self { effective: 0.0, hard, + id: base, }; } let global = ((total as f32 - 72000.0) / 1_440_000.0).clamp(0.0, 1.0) * 0.25; @@ -61,6 +64,7 @@ impl LocalDifficulty { Self { effective: f32::from(base) * (0.75 + global + local), hard, + id: base, } } /// `getSpecialMultiplier`. diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 7836a49ef..0fb80d9e9 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -25,6 +25,8 @@ pub struct TargetInfo { pub can_be_seen_as_enemy: bool, pub is_player: bool, pub creative: bool, + /// `isPassenger`. + pub passenger: bool, } impl MobWorld<'_> { /// The biome's base temperature at a position. @@ -201,6 +203,7 @@ impl MobWorld<'_> { can_be_seen_as_enemy: true, is_player: true, creative: p.creative, + passenger: p.passenger, }), Who::Mob(id) => self.seen(id).map(|s| TargetInfo { position: s.position, @@ -210,6 +213,7 @@ impl MobWorld<'_> { can_be_seen_as_enemy: !s.playing_dead, is_player: false, creative: false, + passenger: s.passenger, }), } } From c418034f10e15eb6dccba6e4d9a18365eb08a3f0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:07 +0100 Subject: [PATCH 038/195] Let goats breed, follow wheat and be milked Goats only strolled and panicked, so wheat did nothing after the love hearts and a bucket gave no milk. Give them the GoatAi core and idle behaviours that exist here (panic 2.0, breed, tempt 1.25, baby follow 1.25) and Goat.mobInteract's milking with the goat milk sounds. --- crates/horizon-client/src/game/creatures.rs | 10 ++++++++++ crates/horizon-client/src/mobs/ai.rs | 14 ++++++++++++++ 2 files changed, 24 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..0fe0f4210 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2548,6 +2548,16 @@ impl Game<'_> { consume = true; sound = Some("entity.cow.milk"); } + // Goat.mobInteract: a bucket on an adult gives milk. + Species::Goat if item == "minecraft:bucket" && !m.is_baby() => { + give = Some("minecraft:milk_bucket"); + consume = true; + sound = Some(if m.extra.screaming { + "entity.goat.screaming.milk" + } else { + "entity.goat.milk" + }); + } Species::Mooshroom if item == "minecraft:bowl" && !m.is_baby() => { give = Some("minecraft:mushroom_stew"); consume = true; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..e194d0132 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -301,6 +301,20 @@ fn generic(m: &mut Mob) { m.ai.targets.add(1, HurtByTarget::new()); m.ai.targets.add(2, NearestTarget::player(true)); } else { + if m.kind.species == Species::Goat { + // GoatAi's idle and core behaviours (the ram and long jump + // activities are not here): panic 2.0, AnimalMakeLove, tempting + // with goat_food and baby follow at 1.25, then stroll. + g.add(0, Float); + g.add(1, Panic::new(2.0)); + g.add(2, Breed::new(1.0)); + g.add(3, Tempt::new(1.25, m.kind.food.clone(), false)); + g.add(4, FollowParent::new(1.25)); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); + return; + } g.add(0, Float); let rabbit = m.kind.species == Species::Rabbit; g.add(1, Panic::new(if rabbit { 2.2 } else { 1.25 })); From 06fb03567e4f124315872936eced832c6d47afde Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:11 +0100 Subject: [PATCH 039/195] Count the block interaction statistics Eating a cake slice, using a cauldron (fill, use, clean armor, banner or shulker box), tuning a note block, ringing a bell, opening an ender chest and putting a record in a jukebox now add to their statistics, which stayed at 0 before. --- crates/horizon-client/src/cauldron.rs | 31 +++++++++++++++++------ crates/horizon-client/src/game.rs | 21 +++++++++++++++ crates/horizon-client/src/game/jukebox.rs | 1 + 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index 03fb0676d..25a709e26 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -40,6 +40,8 @@ pub struct Interaction { /// The cauldron's new state. pub block: Option, pub sound: Option<&'static str>, + /// The custom statistic the player earns (`use_cauldron`, ...). + pub stat: Option<&'static str>, } fn state(name: &str, level: Option) -> BlockState { @@ -57,6 +59,7 @@ fn pass() -> Interaction { outcome: Outcome::Pass, block: None, sound: None, + stat: None, } } @@ -117,11 +120,12 @@ fn lowered(cauldron: &BlockState) -> BlockState { } } -fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { +fn changed(block: BlockState, sound: Option<&'static str>, stat: &'static str) -> Interaction { Interaction { outcome: Outcome::Success, block: Some(block), sound, + stat: Some(stat), } } @@ -179,18 +183,22 @@ pub fn interact( stack.data_mut().dyed_color = None; stack.tidy(); } - return changed(lowered(cauldron), None); + return changed(lowered(cauldron), None, "clean_armor"); } let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| { if !can_fill { return pass(); } filled(player, ItemStack::new(new, 1), true); - changed(state("minecraft:cauldron", None), Some(sound)) + changed( + state("minecraft:cauldron", None), + Some(sound), + "use_cauldron", + ) }; let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| { filled(player, ItemStack::new("minecraft:bucket", 1), true); - changed(block, Some(sound)) + changed(block, Some(sound), "fill_cauldron") }; match item { "minecraft:lava_bucket" => { @@ -199,6 +207,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -221,6 +230,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -241,6 +251,7 @@ pub fn interact( changed( state("minecraft:water_cauldron", Some(1)), Some("minecraft:item.bottle.empty"), + "use_cauldron", ) } ("water", "minecraft:bucket") => fill_bucket( @@ -255,7 +266,11 @@ pub fn interact( ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"), true, ); - changed(lowered(cauldron), Some("minecraft:item.bottle.fill")) + changed( + lowered(cauldron), + Some("minecraft:item.bottle.fill"), + "use_cauldron", + ) } ("water", "minecraft:potion") => { if level == 3 || !water_potion { @@ -266,7 +281,7 @@ pub fn interact( // BlockState.cycle on a 1..=3 property next.properties .insert("level".into(), (level % 3 + 1).to_string()); - changed(next, Some("minecraft:item.bottle.empty")) + changed(next, Some("minecraft:item.bottle.empty"), "use_cauldron") } ("water", name) if name @@ -283,7 +298,7 @@ pub fn interact( cleaned.data_mut().banner_patterns.pop(); cleaned.tidy(); filled(player, cleaned, false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_banner") } ("water", name) if name @@ -292,7 +307,7 @@ pub fn interact( .is_some_and(|c| COLORS.contains(&c)) => { filled(player, held.transmute("minecraft:shulker_box", 1), false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_shulker_box") } ("lava", "minecraft:bucket") => fill_bucket( player, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..175c10447 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2915,6 +2915,8 @@ impl Game<'_> { // Popped as the behaviour emits it (GameLevel::emit). PlayerEffect::DropItem(_) => {} PlayerEffect::EatCake => { + // CakeBlock.eat + self.stats.custom("eat_cake_slice", 1); if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; food.food = (food.food + 2).min(20); @@ -3019,6 +3021,8 @@ impl Game<'_> { self.craft_table = Some(pos); } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); + // EnderChestBlock.useWithoutItem + self.stats.custom("open_enderchest", 1); self.container_opener_event(key, true); let at = [ f64::from(key.0) + 0.5, @@ -3574,6 +3578,20 @@ impl Game<'_> { ) }); self.process_level_events()?; + // NoteBlock.useWithoutItem (tuned) and BellBlock.onHit (rung). + if result == horizon_world::level::InteractionResult::Success { + let name = self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) + .name + .clone(); + match &*name { + "minecraft:note_block" => self.stats.custom("tune_noteblock", 1), + "minecraft:bell" => self.stats.custom("bell_ring", 1), + _ => {} + } + } if result.consumes_action() { self.swing_arm(); return Ok(true); @@ -8477,6 +8495,9 @@ impl Game<'_> { if result.outcome == Outcome::Pass { return Ok(false); } + if let Some(stat) = result.stat { + self.stats.custom(stat, 1); + } if let Some(block) = result.block && let Ok(new) = registry.resolve(&block) { diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index c3ed75ebb..61caea0c8 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -79,6 +79,7 @@ impl Game<'_> { if !self.creative { self.consume_held(); } + self.stats.custom("play_record", 1); self.world.block_entities.insert( (pos[0], pos[1], pos[2]), BlockEntity::Jukebox(Jukebox { From fd0f09d6f6530e8c442906a953d80414dc8dcb64 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:20 +0100 Subject: [PATCH 040/195] End the Absorption effect once the absorption is used up The effect used to stay in the list until its timer ran out, even with no absorption hearts left. --- crates/horizon-client/src/effects.rs | 15 +++++++++------ crates/horizon-client/src/game/potions.rs | 4 +++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 17dce93ab..5f8649642 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -213,8 +213,9 @@ impl PlayerEffects { } /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` - /// (on its last tick). Returns the actions to apply, in order, and - /// whether Raid Omen was newly added. + /// (on its last tick); `absorption_empty` is `AbsorptionMobEffect`'s + /// answer: the effect ends once the absorption is used up. Returns the + /// actions to apply, in order, and whether Raid Omen was newly added. /// /// Bad Omen turning into a new Raid Omen adds an entry to the map being /// iterated: vanilla's iterator then throws a @@ -224,6 +225,7 @@ impl PlayerEffects { pub fn tick_with( &mut self, omen: &mut dyn FnMut(&EffectInstance) -> OmenTick, + absorption_empty: bool, ) -> (Vec, bool) { self.tick_count = self.tick_count.wrapping_add(1); let mut actions = Vec::new(); @@ -246,6 +248,7 @@ impl PlayerEffects { let answer = match e.id { "bad_omen" => omen(e), "raid_omen" if t == 1 => omen(e), + "absorption" if absorption_empty => OmenTick::Remove, _ => OmenTick::Continue, }; match answer { @@ -465,13 +468,13 @@ mod tests { }; // The first tick adds Raid Omen and stops there (the iterator's // ConcurrentModificationException): Bad Omen and Speed stay as they were. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(added); assert_eq!(fx.get("bad_omen").unwrap().duration, 100); assert_eq!(fx.get("speed").unwrap().duration, 50); assert_eq!(fx.get("raid_omen").unwrap().duration, 600); // The second refreshes Raid Omen and drops Bad Omen. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(!added); assert!(fx.get("bad_omen").is_none()); assert_eq!(fx.get("speed").unwrap().duration, 49); @@ -486,9 +489,9 @@ mod tests { seen.push(e.duration); OmenTick::Remove }; - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_some()); - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_none()); assert_eq!(seen, vec![1]); } diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index b28c2fb4d..e023ca4b2 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -381,8 +381,10 @@ impl Game<'_> { } // The omens act from inside the effect tick (BadOmenMobEffect, // RaidOmenMobEffect). + let absorption_empty = player.health.absorption() <= 0.0; let mut effects = std::mem::take(&mut self.potions.effects); - let (actions, raid_omen_added) = effects.tick_with(&mut |e| self.omen_tick(e)); + let (actions, raid_omen_added) = + effects.tick_with(&mut |e| self.omen_tick(e), absorption_empty); self.potions.effects = effects; if raid_omen_added { self.raid_omen_added(); From 85a6ce09214e684be1810ee6530e85c4476407b3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:30 +0100 Subject: [PATCH 041/195] Lightning scrapes oxidation off copper A struck copper block goes back to unoxidized, and 3 to 5 random walks take one step of oxidation off the weathering copper around it. Waxed blocks stay as they are but still start the walks. --- crates/horizon-client/src/game/lightning.rs | 11 +++ crates/horizon-world/src/level/tick.rs | 83 +++++++++++++++++++++ 2 files changed, 94 insertions(+) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..55e867f87 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -221,6 +221,7 @@ impl Game<'_> { if !b.visual_only { self.bolt_fire(b.at, 4); self.strike_rod(b.at); + self.bolt_clear_copper(b.at); } } b.life -= 1; @@ -278,6 +279,16 @@ impl Game<'_> { self.level_event_at(3002, p, axis); } } + /// `LightningBolt.clearCopperOnLightningStrike` at the block the bolt struck. + fn bolt_clear_copper(&mut self, at: [f64; 3]) { + let p = BlockPos::new( + at[0].floor() as i32, + (at[1] - 1.0e-6).floor() as i32, + at[2].floor() as i32, + ); + self.with_level(|b, level, ticks| b.lightning_clear_copper(level, ticks, p)); + let _ = self.process_level_events(); + } /// `thunderHit` for entities within 3 blocks (up to 9 above). fn thunder_hit(&mut self, b: &mut Bolt) { let at = b.at; diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..3cb8c2d2e 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -1479,6 +1479,80 @@ impl Sim<'_, L> { let block = b.table.block_by_name(&format!("minecraft:{next}"))?; Some(b.table.with_properties_of(block, state)) } + /// `WeatheringCopper.getPrevious` (and `getFirst` by repeating it) by + /// registry naming: the block one oxidation step back. + fn copper_previous_name(path: &str) -> Option { + if let Some(rest) = path.strip_prefix("oxidized_") { + Some(format!("weathered_{rest}")) + } else if let Some(rest) = path.strip_prefix("weathered_") { + Some(format!("exposed_{rest}")) + } else { + path.strip_prefix("exposed_").map(|rest| { + if rest == "copper" { + "copper_block".to_owned() + } else { + rest.to_owned() + } + }) + } + } + fn copper_stepped(&self, state: BlockStateId, all_the_way: bool) -> Option { + let b = self.b; + let name = &*b.table.info(b.block(state)).name; + let mut path = Self::copper_previous_name(name.strip_prefix("minecraft:")?)?; + while all_the_way && let Some(earlier) = Self::copper_previous_name(&path) { + path = earlier; + } + let block = b.table.block_by_name(&format!("minecraft:{path}"))?; + Some(b.table.with_properties_of(block, state)) + } + /// `LightningBolt.clearCopperOnLightningStrike`: the struck copper goes + /// back to unoxidized, then 3 to 5 random walks of up to 8 steps each + /// scrape one step of oxidation off the weathering copper they land on. + /// A waxed block is left as it is but still starts the walks. + pub(crate) fn lightning_clear_copper(&mut self, struck: BlockPos) { + let b = self.b; + let state = self.state(struck); + let weathering = b + .data(state) + .implements(super::classes::Interface::WeatheringCopper); + let waxed = b.table.name(state).starts_with("minecraft:waxed_"); + if !(weathering || waxed) { + return; + } + if weathering && let Some(first) = self.copper_stepped(state, true) { + self.set_block_and_update(struck, first); + } + for _ in 0..self.rand_int(3) + 3 { + let mut at = struck; + for _ in 0..self.rand_int(8) + 1 { + // randomStepCleaningCopper: up to 10 random blocks in the + // 3x3x3 cube around the walk's position. + let mut next = None; + for _ in 0..10 { + let x = at.x - 1 + self.rand_int(3); + let y = at.y - 1 + self.rand_int(3); + let z = at.z - 1 + self.rand_int(3); + let candidate = BlockPos::new(x, y, z); + let state = self.state(candidate); + if b.data(state) + .implements(super::classes::Interface::WeatheringCopper) + { + if let Some(previous) = self.copper_stepped(state, false) { + self.set_block_and_update(candidate, previous); + } + self.level_event(3002, candidate, -1); + next = Some(candidate); + break; + } + } + match next { + Some(p) => at = p, + None => break, + } + } + } + } } /// `Biome.Precipitation` at a position. @@ -1662,6 +1736,15 @@ impl Behaviours { ) { self.sim(level, ticks).random_tick_at(pos); } + /// `LightningBolt.clearCopperOnLightningStrike` for the block at `struck`. + pub fn lightning_clear_copper( + &self, + level: &mut L, + ticks: &mut Ticks, + struck: BlockPos, + ) { + self.sim(level, ticks).lightning_clear_copper(struck); + } /// Run one scheduled block tick at `pos` immediately (no queue check). pub fn scheduled_block_tick( &self, From 53501ab94ea4ad6e91003b14e2ae37106498ce2a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:55 +0100 Subject: [PATCH 042/195] Merge a mob's repeated effects like vanilla A stronger effect now replaces the old one with its own duration, instead of taking the longer duration and the higher level separately. --- crates/horizon-client/src/mobs.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..6a220d63d 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1854,8 +1854,15 @@ impl Mob { } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - e.1 = e.1.max(ticks); - e.2 = e.2.max(amplifier); + // MobEffectInstance.update: a stronger effect replaces with its + // own duration, an equal one only extends it; a weaker one is + // ignored (vanilla keeps it hidden behind the active one). + if amplifier > e.2 { + e.1 = ticks; + e.2 = amplifier; + } else if amplifier == e.2 && e.1 != -1 && (ticks == -1 || e.1 < ticks) { + e.1 = ticks; + } } else { self.extra.effects.push((effect, ticks, amplifier)); } From 728bf14aa7db38211cd50d751f38486194d28de3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:06 +0100 Subject: [PATCH 043/195] Use vanilla ambient sound intervals for guardians, hoglins, shulkers and allays A happy ghast with a passenger waits six times as long. --- crates/horizon-client/src/mobs.rs | 12 +++++++++++- crates/horizon-client/src/mobs/ai.rs | 2 +- crates/horizon-client/src/mobs/species.rs | 6 ++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..b2028f964 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1778,7 +1778,7 @@ impl Mob { let dead = !self.alive(); let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }]; if !dead { - self.ambient_timer = -self.kind.ambient_interval; + self.ambient_timer = -self.ambient_interval(); } if !sound.is_empty() { let pitch = self.voice_pitch(); @@ -1874,6 +1874,16 @@ impl Mob { let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, 1.0, 1.0)); } + /// `Mob.getAmbientSoundInterval`; `HappyGhast` waits six times as long + /// while it carries a passenger. + pub fn ambient_interval(&self) -> i32 { + let ridden = self.rider.is_some() || self.extra.rider.is_some(); + if self.species() == Species::HappyGhast && ridden { + self.kind.ambient_interval * 6 + } else { + self.kind.ambient_interval + } + } /// LivingEntity.getVoicePitch. pub fn voice_pitch(&mut self) -> f32 { let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..e6508b448 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -547,7 +547,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let t = m.ambient_timer; m.ambient_timer += 1; if roll < t { - m.ambient_timer = -m.kind.ambient_interval; + m.ambient_timer = -m.ambient_interval(); play_ambient(m, w, events); } } diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index f48a21fe9..6630ea4c5 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1658,6 +1658,12 @@ impl Def { | S::Camel | S::CamelHusk => 400, S::Ocelot => 900, + // Guardian.getAmbientSoundInterval (the elder too). + S::Guardian | S::ElderGuardian => 160, + // Hoglin extends Animal; Shulker extends AbstractGolem. + S::Hoglin | S::Shulker => 120, + // Allay is a PathfinderMob: the Mob default. + S::Allay => 80, S::Squid | S::GlowSquid | S::Cod From 273729aac8e7d6f6de6730688b900663efce2d8c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:34 +0100 Subject: [PATCH 044/195] Count the combat statistics damage_resisted, damage_absorbed and damage_blocked_by_shield now add up when Resistance, absorption hearts or a shield take damage, and a player who lands the killing blow on another player gets player_kills. --- crates/horizon-client/src/game/combat.rs | 10 ++++++++++ crates/horizon-client/src/game/lan_pvp.rs | 22 ++++++++++++++++++++++ crates/horizon-client/src/game/shield.rs | 7 +++++++ 3 files changed, 39 insertions(+) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 106e0e1a1..197c77f17 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -73,6 +73,16 @@ impl Game<'_> { self.recheck_combat(); for e in events { let (name, amount) = match e { + // LivingEntity.getDamageAfterMagicAbsorb (Resistance) and + // Player.actuallyHurt (absorption hearts), in tenths. + MotionEvent::Health(HealthEvent::Statistic { name, amount }) => { + match *name { + "resisted" => self.stats.custom("damage_resisted", *amount), + "absorbed" => self.stats.custom("damage_absorbed", *amount), + _ => {} + } + continue; + } MotionEvent::Health(HealthEvent::RecordedDamage { source, amount }) => { let Some(d) = self.motion.health.damage.definition(*source) else { continue; diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index c7c6b6525..a2ff13444 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -253,6 +253,28 @@ impl Game<'_> { Victim::Host => land(self), Victim::Guest(conn) => self.guest_struck_by(host, conn, land).unwrap_or(false), }; + // ServerPlayer.awardKillScore: the blow that kills a player. + if hurt { + let died = match victim { + Victim::Host => self + .player + .as_ref() + .is_some_and(|p| p.health.dead_or_dying()), + Victim::Guest(conn) => host + .hub + .guest(conn) + .and_then(|g| g.motion.as_deref()) + .is_some_and(|p| p.health.dead_or_dying()), + }; + if died { + match s.attacker { + Some(conn) => { + self.as_guest(host, conn, |g| g.stats.custom("player_kills", 1)); + } + None => self.stats.custom("player_kills", 1), + } + } + } if hurt && s.crit { let target = match victim { Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index c4f7f98d1..f4642f272 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -121,6 +121,13 @@ impl Game<'_> { attacker: Option, projectile: bool, ) { + // LivingEntity.hurtServer: the damage the shield took, in tenths. + if outcome.blocked > 0.0 { + self.stats.custom( + "damage_blocked_by_shield", + (outcome.blocked * 10.0).round() as i32, + ); + } let Some((slot, _)) = self.using else { return }; let Some(stack) = self.stack_in(slot).cloned() else { return; From dd3697bb4d0f6acd161fc18aaa7eeab3bafbfea5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:43 +0100 Subject: [PATCH 045/195] Hopper minecarts take from the container above, one item per tick --- crates/horizon-client/src/game/machines.rs | 144 ++++++++++++++------ crates/horizon-client/src/game/minecarts.rs | 48 +------ 2 files changed, 106 insertions(+), 86 deletions(-) diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 8742962e9..55e47aa67 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -624,46 +624,8 @@ impl Game<'_> { /// `HopperBlockEntity.suckInItems`: from the container above, or item entities. fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool { let above = (pos.0, pos.1 + 1, pos.2); - let c = self.containers(); - if let Some(source) = c.view(above, false) { - if let Kind::Composter(level) = source.kind { - if level != 8 { - return false; - } - // tryTakeInItemFromSlot on the OutputContainer: removeItem calls - // its setChanged, which empties the composter, and so does the - // second setChanged after the move or, when the hopper has no - // room, the setItem putting the bone meal back into the detached - // container (whose bone meal is lost with it). - let bone_meal = c.bone_meal.clone(); - let at = BlockPos::new(above.0, above.1, above.2); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - let moved = self.add_item(None, hopper, bone_meal, None).is_none(); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - self.world.modified.insert((above.0 >> 4, above.2 >> 4)); - return moved; - } - let source_hopper = (source.kind == Kind::Hopper).then_some(above); - for slot in source.slots_for_face(Some(Direction::Down)) { - let c = self.containers(); - let Some(stack) = c.get(&source, slot) else { - continue; - }; - if !c.can_take(&source, slot, stack, Direction::Down) { - continue; - } - let Some(one) = self.take_one(&source, slot) else { - continue; - }; - match self.add_item(source_hopper, hopper, one, None) { - None => { - self.view_changed(&source); - return true; - } - Some(rest) => self.put_back(&source, slot, rest), - } - } - return false; + if let Some(took) = self.suck_from_container(above, hopper) { + return took; } let above_state = self.world.block(above.0, above.1, above.2); let blocked = self.res.facts().get(above_state).full_collision @@ -693,6 +655,56 @@ impl Game<'_> { { return false; } + self.suck_item_entities(hopper, min, max) + } + /// The container half of `HopperBlockEntity.suckInItems`: one item from the + /// container at `above`, through its bottom face. `None` when there is no + /// container there. + fn suck_from_container(&mut self, above: Pos, hopper: &View) -> Option { + let c = self.containers(); + let source = c.view(above, false)?; + if let Kind::Composter(level) = source.kind { + if level != 8 { + return Some(false); + } + // tryTakeInItemFromSlot on the OutputContainer: removeItem calls + // its setChanged, which empties the composter, and so does the + // second setChanged after the move or, when the hopper has no + // room, the setItem putting the bone meal back into the detached + // container (whose bone meal is lost with it). + let bone_meal = c.bone_meal.clone(); + let at = BlockPos::new(above.0, above.1, above.2); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + let moved = self.add_item(None, hopper, bone_meal, None).is_none(); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + self.world.modified.insert((above.0 >> 4, above.2 >> 4)); + return Some(moved); + } + let source_hopper = (source.kind == Kind::Hopper).then_some(above); + for slot in source.slots_for_face(Some(Direction::Down)) { + let c = self.containers(); + let Some(stack) = c.get(&source, slot) else { + continue; + }; + if !c.can_take(&source, slot, stack, Direction::Down) { + continue; + } + let Some(one) = self.take_one(&source, slot) else { + continue; + }; + match self.add_item(source_hopper, hopper, one, None) { + None => { + self.view_changed(&source); + return Some(true); + } + Some(rest) => self.put_back(&source, slot, rest), + } + } + Some(false) + } + /// The item half of `HopperBlockEntity.suckInItems` (`getItemsAtAndAbove`): + /// adds the item entities that meet the box, until one is taken whole. + fn suck_item_entities(&mut self, hopper: &View, min: [f64; 3], max: [f64; 3]) -> bool { let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -717,6 +729,58 @@ impl Game<'_> { } false } + /// `MinecartHopper.tick`'s `tryConsumeItems` (`suckInItems`) for an enabled + /// hopper minecart: one item from the container above, else the item + /// entities over it or touching it, each tick without a cooldown. + pub(super) fn hopper_cart_suck(&mut self, cart: &mut super::minecarts::Minecart) { + // The cart's slots are edited as a container under the placeholder key + // its menu uses; when that menu is open the placeholder is the live copy. + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, cart.id as i32); + let open = self.world.block_entities.contains_key(&key); + if !open { + let items = BlockEntity::Chest(std::mem::take(&mut cart.items)); + self.world.block_entities.insert(key, items); + } + let size = self + .world + .block_entities + .get(&key) + .map_or(0, |e| e.slots().len()); + let view = View { + parts: vec![(key, size)], + kind: Kind::Generic, + }; + let p = cart.position; + // getLevelY is the cart's y + 0.5, so the container is the block at + // y + 1.5, and Hopper.SUCK_AABB (moved by getLevel - 0.5) starts 11/16 + // above the cart. + let above = ( + p.x.floor() as i32, + (p.y + 1.5).floor() as i32, + p.z.floor() as i32, + ); + let took = match self.suck_from_container(above, &view) { + Some(took) => took, + None => self.suck_item_entities( + &view, + [p.x - 0.5, p.y + 11.0 / 16.0, p.z - 0.5], + [p.x + 0.5, p.y + 2.0, p.z + 0.5], + ), + }; + if !took { + // The cart's own box, inflated by 0.25 sideways. + let b = cart.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + self.suck_item_entities( + &view, + [lo.x - 0.25, lo.y, lo.z - 0.25], + [hi.x + 0.25, hi.y, hi.z + 0.25], + ); + } + if !open && let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) { + cart.items = items; + } + } // ---- dispensers and droppers ---- diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index a19b6df73..33e08a922 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -642,50 +642,6 @@ impl Game<'_> { self.carts.retain(|x| x.id != c.id); let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); } - /// `MinecartHopper.suckInItems`: items above, into the five slots. - fn hopper_cart_pickup(&mut self, c: &mut Minecart) { - if !c.enabled { - return; - } - let p = c.position; - let zone = Aabb::new( - Vec3::new(p.x - 0.5, p.y - 0.5 + 0.0, p.z - 0.5), - Vec3::new(p.x + 0.5, p.y + 1.5, p.z + 0.5), - ); - let mut i = 0; - while i < self.dropped.len() { - let e = &self.dropped[i]; - if e.pickup_delay > 0 || !zone.contains(e.position) { - i += 1; - continue; - } - let mut stack = e.stack.clone(); - for slot in c.items.iter_mut() { - match slot { - None => { - *slot = Some(stack.clone()); - stack.count = 0; - } - Some(s) if s.same_item_same_components(&stack) => { - let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack); - let moved = stack.count.min(max.saturating_sub(s.count)); - s.count += moved; - stack.count -= moved; - } - _ => {} - } - if stack.count == 0 { - break; - } - } - if stack.count == 0 { - self.dropped.remove(i); - } else { - self.dropped[i].stack = stack; - i += 1; - } - } - } /// `AbstractMinecart.push` from each player walking into a cart /// (`LivingEntity.pushEntities`): the window's player and every server /// player (single player's own on its server thread, LAN guests). A @@ -823,8 +779,8 @@ impl Game<'_> { } let mut c = self.carts[i].clone(); let alive = self.tick_cart(&mut c, [0.0; 2]); - if c.kind == CartKind::Hopper { - self.hopper_cart_pickup(&mut c); + if c.kind == CartKind::Hopper && c.enabled { + self.hopper_cart_suck(&mut c); } let Some(i) = self.carts.iter().position(|c| c.id == id) else { continue; From 601e7918a844884574222a26ec75d05169499386 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:43 +0100 Subject: [PATCH 046/195] Lightning scrapes one oxidation step off a copper golem A copper golem hit by a bolt goes back one weathering step, and its weathering timer (or wax) is reset. --- crates/horizon-client/src/game/lightning.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 916bd2a0a..b4e2c587c 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -16,7 +16,7 @@ pub(super) struct Bolt { flashes: i32, seed: i64, visual_only: bool, - /// Mooshrooms switch colour once per bolt. + /// Mooshrooms and copper golems change once per bolt. converted: Vec, } impl Game<'_> { @@ -337,6 +337,17 @@ impl Game<'_> { continue; } Species::Creeper => m.extra.charged = true, + // CopperGolem.thunderHit (after Entity.thunderHit's fire and + // damage): once per bolt, an oxidized golem goes back one step + // and its weathering timer (or wax, -2) is reset to -1. + Species::CopperGolem if !b.converted.contains(&m.id) => { + b.converted.push(m.id); + if m.extra.variant > 0 { + m.extra.vector[0] = -1.0; + m.extra.variant = + horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); + } + } _ => {} } // Entity.thunderHit: burning (8 seconds) and 5 lightning damage. From 13144a82a15291da42e1449741ae15d63c33d4a9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:28 +0100 Subject: [PATCH 047/195] Pull the third-person camera back further when riding a happy ghast --- crates/horizon-client/src/game/perspective.rs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index caf49883b..2d5c6b05c 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -218,11 +218,20 @@ impl Game<'_> { _ => None, }) }); - // A living mount at the default scale and camera distance. + // Camera.setup: the living mount's scale and camera distance + // attributes (the happy ghast's is 8, the default 4). let mount = self .riding .and_then(|id| self.mobs.iter().find(|m| m.id == id)) - .map(|_| (1.0, 4.0)); + .map(|m| { + let attribute = |name: &str, default: f64| { + m.kind.attributes.get(name).copied().unwrap_or(default) + }; + ( + attribute("minecraft:scale", 1.0) as f32, + attribute("minecraft:camera_distance", 4.0), + ) + }); // AbstractBoat.positionRider turns a passenger by the boat's // deltaRotation after its yRotO was saved, and LocalPlayer.getViewYRot // interpolates a passenger's yaw: the boat's turn is spread over the From 8c8f857313bd5fbe82cb47af8d339640460ac174 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:17:42 +0100 Subject: [PATCH 048/195] Fire item_used_on_block when an axe, honeycomb, disc or vault key is used on a block --- crates/horizon-client/src/game.rs | 4 ++++ crates/horizon-client/src/game/jukebox.rs | 2 ++ crates/horizon-client/src/game/vault.rs | 2 ++ 3 files changed, 8 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..fa7f0c133 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8586,6 +8586,8 @@ impl Game<'_> { else { return Ok(false); }; + // BlockTransformer.transformBlock: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", pos, stack); self.level_set(pos, new)?; // BlockTransformer.TransformParticle.send. self.transform_particle(&particle, pos); @@ -8832,6 +8834,8 @@ impl Game<'_> { if let Some(waxed) = old.and_then(|old| self.res.transformers().waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) { + // HoneycombItem.useOn: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", hit.pos, stack); self.level_set(hit.pos, state)?; self.level_event_at(3003, hit.pos, 0); self.audio.play( diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index c3ed75ebb..bd130ce9b 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -90,6 +90,8 @@ impl Game<'_> { self.set_has_record(pos, true); self.start_song(pos, &song); self.jukebox_changed(pos); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, stack); true } /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index f3edfddb3..18430daf6 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -169,6 +169,8 @@ impl Game<'_> { self.consume_held(); } } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &stack); Ok(true) } fn vault_events(&mut self, key: Pos, events: Vec) -> Result<()> { From b913dab5e52e179e73c3bdebe1ee77266e92a34f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:17:53 +0100 Subject: [PATCH 049/195] Walk, follow and flee at the camel's real AI speeds --- crates/horizon-client/src/mobs/camel.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/mobs/camel.rs b/crates/horizon-client/src/mobs/camel.rs index 21ebe9e16..703c8fa8f 100644 --- a/crates/horizon-client/src/mobs/camel.rs +++ b/crates/horizon-client/src/mobs/camel.rs @@ -24,12 +24,13 @@ pub fn register(m: &mut Mob) { m.extra.tame = true; let tempt = m.kind.tempt.clone(); let g = &mut m.ai.goals; + // CamelAi speed modifiers (times the 0.09 movement speed attribute). g.add(0, Float); - g.add(1, CamelPanic(Panic::new(4.0 * 0.25))); + g.add(1, CamelPanic(Panic::new(4.0))); g.add(2, Breed::new(1.0)); - g.add(3, Tempt::new(2.5 * 0.25, tempt, false)); - g.add(4, FollowParent::new(2.5 * 0.25)); - g.add(5, Stroll::new(2.0 * 0.25)); + g.add(3, Tempt::new(2.5, tempt, false)); + g.add(4, FollowParent::new(2.5)); + g.add(5, Stroll::new(2.0)); g.add(5, RandomSitting); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); From aff673a08dbec0ababc2e70c51abe1706cd32c5e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:20:10 +0100 Subject: [PATCH 050/195] Give the Ender Dragon its ambient sound --- crates/horizon-client/src/game/dragon.rs | 25 ++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index f28049fd5..96c8ef478 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -26,6 +26,8 @@ pub(super) const SPECIAL: u32 = u32::MAX - 4096; const CRYSTAL_IDS: u32 = SPECIAL + 16; const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat"; const MAX_HEALTH: f32 = 200.0; +/// `Mob.getAmbientSoundInterval`. +const AMBIENT_INTERVAL: i32 = 80; #[derive(Default)] pub(super) struct Fight { @@ -269,6 +271,8 @@ pub(super) struct Dragon { flame_count: i32, sitting_damage: f32, growl: i32, + /// `Mob.ambientSoundTime`. + ambient_time: i32, ticks: i32, /// DragonFlightHistory: (y, yRot) samples, newest at `head`. history: [(f64, f32); 64], @@ -396,6 +400,7 @@ impl Dragon { flame_count: 0, sitting_damage: 0.0, growl: 100, + ambient_time: 0, ticks: 0, history: [(position.y, yaw); 64], head: 0, @@ -986,6 +991,8 @@ impl Game<'_> { }; let hurt = d.hurt(part, damage, counts, arrow); if hurt == (Hurt::Landed { full: true }) { + // Mob.playHurtSound: the ambient sound clock starts again. + d.ambient_time = -AMBIENT_INTERVAL; let at = [d.position.x, d.position.y, d.position.z]; let pitch = 0.8 + self.world.random.next_float() * 0.3; self.audio @@ -1656,6 +1663,24 @@ impl Game<'_> { self.tick_dragon_death(); return; } + // Mob.baseTick: the ambient sound, rarer right after one. + let roll = d.random.next_int_bound(1000).unwrap_or(999); + let waited = d.ambient_time; + d.ambient_time += 1; + if roll < waited { + d.ambient_time = -AMBIENT_INTERVAL; + let at = [d.position.x, d.position.y, d.position.z]; + // LivingEntity.getVoicePitch. + let r = &mut self.world.random; + let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.ender_dragon.ambient", + Some(at), + 5.0, + pitch, + ); + } + let d = self.dragon.as_mut().expect("dragon"); // Flapping, growls and the flap sound. let flap_was = (d.old_flap * std::f32::consts::TAU).cos(); let v = d.velocity; From 26626e8c2759f6cd7fef2535dd7ae915168af805 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:45:51 +0100 Subject: [PATCH 051/195] Give frogs vanilla's smooth swimming move control --- crates/horizon-client/src/mobs/ai.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..50f1f335b 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -183,6 +183,18 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Rabbit { super::rabbit::register(m); } + if m.species() == Species::Frog { + // `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). + // The speed attribute is 1.0, so the controller's scaling is + // what keeps a frog at a walking pace on land. + m.ai.mov.kind = super::control::MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + }; + } } Family::Inert => {} Family::Witch => super::witch::register(m), From 9e71837df99a26c8ec77922d2718e8daeb46b2bd Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:56:15 +0000 Subject: [PATCH 052/195] Keep server logging from panicking on a closed stdout pipe Co-Authored-By: OpenAI GPT-6.1 Sol --- crates/horizon-client/src/game/dedicated.rs | 112 +++++++++++++++++++- 1 file changed, 111 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..4a3b5b4ca 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -24,6 +24,7 @@ use horizon_client::{ use horizon_protocol::text::translatable; use horizon_world::nbt::{JavaString, Tag}; use std::{ + io::Write, path::PathBuf, sync::{Arc, Mutex, OnceLock, mpsc}, time::{Duration, Instant}, @@ -89,7 +90,9 @@ fn log_from(thread: &str, level: &str, message: &str) { } }); // Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log. - println!( + // The launcher can close its stdout pipe while the server keeps running. + let _ = writeln!( + std::io::stdout().lock(), "[{}] [{thread}/{level}]: {message}", chrono::Local::now().format("%H:%M:%S") ); @@ -1308,3 +1311,110 @@ fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?); Some((w, h)) } + +#[cfg(test)] +mod tests { + use super::{capture_log, log, log_from}; + use std::{ + fs, + io::{self, BufRead, BufReader, Read, Write}, + process::{Command, Stdio}, + time::{SystemTime, UNIX_EPOCH}, + }; + + const LOGIN: &str = "Player[/127.0.0.1:0] logged in with entity id 2 at (0.5, 115.0, 0.5)"; + const WARNING: &str = "Authentication warning"; + const READY: &str = "horizon-console-log-ready\n"; + const CHILD_HOME: &str = "HORIZON_TEST_CONSOLE_LOG_HOME"; + + fn assert_log_lines(text: &str) { + let expected = [ + format!("] [Server thread/INFO]: {LOGIN}"), + format!("] [User Authenticator #1/WARN]: {WARNING}"), + ]; + assert_eq!(text.lines().count(), expected.len()); + for (line, suffix) in text.lines().zip(expected) { + assert!(line.starts_with('[')); + assert!(chrono::NaiveTime::parse_from_str(&line[1..9], "%H:%M:%S").is_ok()); + assert_eq!(&line[9..], suffix); + } + } + + #[test] + fn console_logging_survives_closed_stdout() { + if let Some(home) = std::env::var_os(CHILD_HOME) { + horizon_client::logging::init(std::path::Path::new(&home), "Server thread"); + // Let the parent close the real stdout pipe only after libtest's startup output. + io::stdout().write_all(READY.as_bytes()).unwrap(); + io::stdout().flush().unwrap(); + io::stdin().read_exact(&mut [0]).unwrap(); + std::thread::Builder::new() + .name("Server thread".into()) + .spawn(|| { + let captured = capture_log(|| { + log("INFO", LOGIN); + log_from("User Authenticator #1", "WARN", WARNING); + }); + assert_eq!(captured, [LOGIN, WARNING]); + horizon_client::logging::flush(); + }) + .unwrap() + .join() + .unwrap(); + // Libtest's final status also writes to stdout; only the game logger is under test. + std::process::exit(0); + } + + for closed_stdout in [false, true] { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let home = std::env::temp_dir().join(format!( + "horizon-console-log-test-{}-{unique}", + std::process::id() + )); + fs::create_dir(&home).unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "game::dedicated::tests::console_logging_survives_closed_stdout", + "--nocapture", + ]) + .env(CHILD_HOME, &home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + loop { + let mut line = String::new(); + assert!( + stdout.read_line(&mut line).unwrap() > 0, + "child was not ready" + ); + if line.ends_with(READY) { + break; + } + } + if closed_stdout { + drop(stdout); // No reader remains: the next console write gets EPIPE. + } else { + child.stdout = Some(stdout.into_inner()); + } + child.stdin.take().unwrap().write_all(&[1]).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "closed_stdout={closed_stdout}: {}", + String::from_utf8_lossy(&output.stderr) + ); + if !closed_stdout { + assert_log_lines(std::str::from_utf8(&output.stdout).unwrap()); + } + assert_log_lines(&fs::read_to_string(home.join("logs/latest.log")).unwrap()); + fs::remove_dir_all(home).unwrap(); + } + } +} From 2f3dade42ffd73511b597f8993b3f94b564ca310 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:19:53 +0100 Subject: [PATCH 053/195] Show the firework trail on a boosting rocket and hide its sprite On a server-thread client an elytra boost rocket drew no spark trail and showed up as a static item sprite. The client now follows the entity the rocket is attached to, spawns the trail each tick like FireworkRocketEntity.tick, and does not draw an attached rocket. --- crates/horizon-client/src/game/fireworks.rs | 9 ++- .../src/game/remote_projectiles.rs | 61 +++++++++++++------ 2 files changed, 50 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index e6b4eb136..4f61d728a 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -21,7 +21,7 @@ pub(super) struct Rocket { /// The entity id a server tracks it by (0 until it is tracked). pub id: u32, pub(super) position: Vec3, - previous: Vec3, + pub(super) previous: Vec3, pub(super) velocity: Vec3, life: i32, lifetime: i32, @@ -369,7 +369,12 @@ impl Game<'_> { /// lit at the rocket's light probe. pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let orientation = glam::Mat4::from_quat(self.camera_orientation()); - for r in self.rockets.iter().filter(|r| !r.attached) { + // shouldRender: not while attached to an entity (`isAttachedToEntity`). + for r in self + .rockets + .iter() + .filter(|r| !r.attached && r.attached_to.is_none()) + { // FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks; // EntityRenderer.shouldRender: its 0.25 box in the view. if !self.standing_entity_in_view( diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index a117b1b7c..41631c4f1 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,8 +3,11 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; -use horizon_client::projectiles::{Projectile, ProjectileKind}; -use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_client::{ + particles::{ParticleOptions, ParticleType}, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; @@ -273,8 +276,9 @@ impl Game<'_> { let id = t.id; t.remote_step(|at| step(id, at)); } - // FireworkRocketEntity.tick: a rocket attached to the gliding local - // player boosts it client-side too (attachedToEntity.isFallFlying). + // FireworkRocketEntity.tick: a rocket attached to an entity follows it + // and boosts it client-side too (attachedToEntity.isFallFlying), and + // every rocket leaves its spark trail on a client. let me = self .remote .as_ref() @@ -282,21 +286,42 @@ impl Game<'_> { for r in &mut self.rockets { let id = r.id; r.remote_step(|at| step(id, at)); - if me.is_some() - && r.attached_to == me - && let Some(p) = self.player.as_mut() - && p.fall_flying - { - let look = view_vector(self.yaw, self.pitch); - let m = p.velocity; - p.velocity = Vec3::new( - m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, - m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, - m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, - ); - r.position = p.position; - r.velocity = p.velocity; + if let Some(target) = r.attached_to { + if me == Some(target) { + if let Some(p) = self.player.as_mut() { + if p.fall_flying { + let look = view_vector(self.yaw, self.pitch); + let m = p.velocity; + p.velocity = Vec3::new( + m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, + m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, + m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, + ); + } + r.position = p.position; + r.velocity = p.velocity; + } + } else if let Some(m) = self.mobs.iter().find(|m| m.id == target) { + // Another player's motion is not known here: its step. + r.velocity = Vec3::new( + m.position.x - r.previous.x, + m.position.y - r.previous.y, + m.position.z - r.previous.z, + ); + r.position = m.position; + } } + let g = |g: &mut horizon_core::random::LegacyRandom| g.next_gaussian() * 0.05; + let v = [ + g(&mut self.world.random), + -r.velocity.y * 0.5, + g(&mut self.world.random), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Firework), + [r.position.x, r.position.y, r.position.z], + v, + ); } for c in &mut self.crystals { c.time += 1; From 47654b62a3b3f64ff163590ec1c29d16c341d50d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:24:26 +0100 Subject: [PATCH 054/195] Save the armadillo scute timer and reset it only when a scute can drop --- .../examples/probe/mob_ai_probe.rs | 1 + crates/horizon-client/src/entity_nbt.rs | 10 +++++++ crates/horizon-client/src/game/creatures.rs | 29 +++++++++---------- crates/horizon-client/src/mobs.rs | 2 ++ crates/horizon-client/src/mobs/ai.rs | 27 ++++++++--------- 5 files changed, 41 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index ecdf02901..81c739464 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1097,6 +1097,7 @@ pub fn main() -> horizon_client::Result<()> { block_tags: &items.block_tags, biomes: &biomes, mob_griefing: true, + mob_drops: true, difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0), end: false, world_seed: 0, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 00576ea02..91ede9110 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -445,6 +445,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new())); } } + // Armadillo.addAdditionalSaveData: the time left to the next scute. + "minecraft:armadillo" => { + map.insert("scute_time".into(), Tag::Int(m.extra.egg_time)); + } "minecraft:ravager" => { map.insert("AttackTick".into(), Tag::Int(m.extra.counter)); map.insert("StunTick".into(), Tag::Int(m.extra.counter2)); @@ -876,6 +880,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - st.vibration = crate::sculk::Data::from_nbt(listener); } } + // Armadillo.readAdditionalSaveData: keeps the constructor's time when absent. + if m.species() == crate::mobs::Species::Armadillo + && let Some(t) = number(tag.get("scute_time")) + { + m.extra.egg_time = t as i32; + } if m.species() == crate::mobs::Species::Ravager { m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32; m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 9a78bc2e5..56215fe9c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -416,6 +416,7 @@ impl Game<'_> { block_tags: &self.res.items().block_tags, biomes: self.res.biomes(), mob_griefing: self.ui.rules.bool("mob_griefing"), + mob_drops: self.ui.rules.bool("mob_drops"), end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, @@ -1222,22 +1223,20 @@ impl Game<'_> { } } MobEvent::ShedScute { mob, at, pitch } => { - // shouldDropLoot: the `mob_drops` rule. - if self.ui.rules.bool("mob_drops") { - let table = "minecraft:gameplay/armadillo_shed"; - let drops = self.sequence_loot(table, table, None); - for d in drops { - self.spawn_at_location(Vec3::new(at[0], at[1], at[2]), 0.0, d); - } - self.audio.play( - "minecraft:entity.armadillo.scute_drop", - Some(at), - 1.0, - pitch, - ); - let ctx = self.who_context(Some(Who::Mob(mob)), None); - self.post_game_event("minecraft:entity_place", at, ctx); + // The mob already checked `shouldDropLoot` (a baby, `mob_drops`). + let table = "minecraft:gameplay/armadillo_shed"; + let drops = self.sequence_loot(table, table, None); + for d in drops { + self.spawn_at_location(Vec3::new(at[0], at[1], at[2]), 0.0, d); } + self.audio.play( + "minecraft:entity.armadillo.scute_drop", + Some(at), + 1.0, + pitch, + ); + let ctx = self.who_context(Some(Who::Mob(mob)), None); + self.post_game_event("minecraft:entity_place", at, ctx); } MobEvent::GiftLoot { table, at } => { let drops = diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 315bfdce2..c276c1e66 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1501,6 +1501,8 @@ pub struct MobWorld<'a> { pub biomes: &'a crate::biome::Biomes, /// The `mob_griefing` game rule. pub mob_griefing: bool, + /// The `mob_drops` game rule (`shouldDropLoot`). + pub mob_drops: bool, /// `getCurrentDifficultyAt` near the player. pub difficulty: spawning::LocalDifficulty, /// The End (its dimension type's monster spawn light rules). diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8259ddccb..90337e416 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -938,26 +938,27 @@ fn server_ai_step( fn next_scute_time(m: &mut Mob) -> i32 { m.random.next_int_bound(20 * 60 * 5).unwrap_or(0) + 20 * 60 * 5 } -/// `Armadillo.customServerAiStep`: the scute timer. A baby only resets it -/// (`shouldDropLoot`); the game checks the `mob_drops` rule. -fn armadillo_server_ai_step(m: &mut Mob, events: &mut Vec) { +/// `Armadillo.customServerAiStep`: the scute timer keeps counting down and is +/// only reset once `shouldDropLoot` (not a baby, `mob_drops` on) lets it shed. +fn armadillo_server_ai_step(m: &mut Mob, mob_drops: bool, events: &mut Vec) { + if !m.alive() { + return; + } m.extra.egg_time -= 1; - if m.alive() && m.extra.egg_time <= 0 { - if !m.is_baby() { - let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; - events.push(MobEvent::ShedScute { - mob: m.id, - at: [m.position.x, m.position.y, m.position.z], - pitch, - }); - } + if m.extra.egg_time <= 0 && !m.is_baby() && mob_drops { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + events.push(MobEvent::ShedScute { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + pitch, + }); m.extra.egg_time = next_scute_time(m); } } fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { match m.species() { Species::Rabbit => super::rabbit::server_ai_step(m), - Species::Armadillo => armadillo_server_ai_step(m, cx.events), + Species::Armadillo => armadillo_server_ai_step(m, cx.w.mob_drops, cx.events), Species::Sheep => {} Species::Zombie | Species::Husk From b28108128d23ac61783b160a922f00b320133d98 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:33:08 +0100 Subject: [PATCH 055/195] Keep a hopper minecart's items in sync with a leftover menu copy --- crates/horizon-client/src/game/machines.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 55e47aa67..0562af8cd 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -777,7 +777,15 @@ impl Game<'_> { [hi.x + 0.25, hi.y, hi.z + 0.25], ); } - if !open && let Some(BlockEntity::Chest(items)) = self.world.block_entities.remove(&key) { + // The cart's own items stay the one source of truth: a menu copy that + // is still around (open, or left by a guest's close) gets the pulled + // items back into `cart.items`, so reopening never restores a stale copy. + let slots = if open { + self.world.block_entities.get(&key).cloned() + } else { + self.world.block_entities.remove(&key) + }; + if let Some(BlockEntity::Chest(items)) = slots { cart.items = items; } } From cfd2dc83922ce606c518b085443d634f3931b23e Mon Sep 17 00:00:00 2001 From: Senjin Date: Mon, 26 Oct 2026 16:45:57 +0100 Subject: [PATCH 056/195] HDR: present HDR10 (PQ) where the surface offers it, scRGB otherwise HDR10 is what games usually present and what the display receives: a compositor composes in it or converts to it anyway. The NVIDIA driver offers it on Wayland next to scRGB. A 10-bit swapchain also halves the last pass's bandwidth; the frame before it is 8-bit, so nothing is lost. hdr.wgsl converts the same linear light to BT.2020 (BT.2087) and encodes it with the ST 2084 curve. HORIZON_HDR_OUTPUT=pq or scrgb allows only that one, for comparing them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 34 ++++----- crates/horizon-client/src/gfx/hdr.rs | 99 +++++++++++++++++++++++---- crates/horizon-client/src/graphics.rs | 2 +- crates/horizon-client/src/hdr.wgsl | 25 ++++++- docs/graphics.md | 2 +- 5 files changed, 127 insertions(+), 35 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 904370c04..86df94c0c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -505,10 +505,10 @@ pub struct Renderer { occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). world_post: world_post::Post, - /// HDR output (Horizon setting): `Some` while the swapchain is scRGB. + /// HDR output (Horizon setting): `Some` while the swapchain is HDR. hdr: Option, - /// Whether the window's surface can present scRGB. - hdr_capable: bool, + /// The HDR output the window's surface can present. + hdr_output: Option, /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, /// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s. @@ -1057,7 +1057,7 @@ impl Renderer { let info = adapter.get_info(); crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info)); let size = window.inner_size(); - let (config, present_modes, hdr_capable) = if let Some(surface) = &surface { + let (config, present_modes, hdr_output) = if let Some(surface) = &surface { let mut config = surface .get_default_config(&adapter, size.width.max(1), size.height.max(1)) .ok_or("surface has no supported configuration")?; @@ -1085,7 +1085,7 @@ impl Renderer { )); } surface.configure(&device, &config); - (config, caps.present_modes.clone(), hdr::supported(&caps)) + (config, caps.present_modes.clone(), hdr::output(&caps)) } else { let format = wgpu::TextureFormat::Bgra8Unorm; let config = wgpu::SurfaceConfiguration { @@ -1099,7 +1099,7 @@ impl Renderer { view_formats: vec![format], color_space: wgpu::SurfaceColorSpace::default(), }; - (config, Vec::new(), false) + (config, Vec::new(), None) }; let offscreen = surface .is_none() @@ -2441,7 +2441,7 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, hdr: None, - hdr_capable, + hdr_output, pack_post: None, native: None, pass_timing: pack_timing::PassTiming::logging(), @@ -2961,24 +2961,24 @@ impl Renderer { } } /// The swapchain's configuration: `config` (what every pipeline draws in), or - /// scRGB while HDR output is on. + /// HDR10 or scRGB while HDR output is on. fn surface_config(&self) -> wgpu::SurfaceConfiguration { let mut config = self.config.clone(); - if self.hdr.is_some() { - config.format = hdr::FORMAT; - config.view_formats = vec![hdr::FORMAT]; - config.color_space = hdr::COLOR_SPACE; + if let Some(hdr) = &self.hdr { + config.format = hdr.output.format(); + config.view_formats = vec![hdr.output.format()]; + config.color_space = hdr.output.color_space(); config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT; } config } - /// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's + /// HDR output (Horizon setting): HDR10 or scRGB at `paper_white` nits, the world's /// highlights expanded up to `peak` nits. Off where the surface can't present it. pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) { - let on = on && self.hdr_capable && self.surface.is_some(); - if on != self.hdr.is_some() { - self.hdr = - on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix())); + let output = self.hdr_output.filter(|_| on && self.surface.is_some()); + if output.is_some() != self.hdr.is_some() { + let format = self.config.format.remove_srgb_suffix(); + self.hdr = output.map(|output| hdr::Hdr::new(&self.device, format, output)); self.configure_surface(); } if let Some(hdr) = &mut self.hdr diff --git a/crates/horizon-client/src/gfx/hdr.rs b/crates/horizon-client/src/gfx/hdr.rs index 11deed546..8b9df7af0 100644 --- a/crates/horizon-client/src/gfx/hdr.rs +++ b/crates/horizon-client/src/gfx/hdr.rs @@ -1,17 +1,50 @@ //! HDR output (Horizon setting, off by default): the frame renders exactly as //! without it, into an 8-bit target in vanilla's gamma space, and one pass -//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white, -//! expanding the world's highlights towards their peak brightness. The world -//! is copied aside before the hand and HUD so only it is expanded. +//! (`hdr.wgsl`) writes it to an HDR10 or scRGB swapchain at the player's paper +//! white, expanding the world's highlights towards their peak brightness. The +//! world is copied aside before the hand and HUD so only it is expanded. -/// The swapchain format and colour space HDR output presents in. -pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; -pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear; +/// The swapchain HDR output presents to. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Output { + /// HDR10: 10-bit BT.2020 with the PQ curve, the display's own signal. + Pq, + /// scRGB: linear 16-bit float, BT.709 primaries, 1.0 = 80 nits. + ScRgb, +} -/// Whether `caps` can present scRGB. -pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool { - caps.color_spaces(FORMAT) - .contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR) +impl Output { + pub fn format(self) -> wgpu::TextureFormat { + match self { + Self::Pq => wgpu::TextureFormat::Rgb10a2Unorm, + Self::ScRgb => wgpu::TextureFormat::Rgba16Float, + } + } + pub fn color_space(self) -> wgpu::SurfaceColorSpace { + match self { + Self::Pq => wgpu::SurfaceColorSpace::Bt2100Pq, + Self::ScRgb => wgpu::SurfaceColorSpace::ExtendedSrgbLinear, + } + } + fn space(self) -> wgpu::SurfaceColorSpaces { + match self { + Self::Pq => wgpu::SurfaceColorSpaces::BT2100_PQ, + Self::ScRgb => wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR, + } + } +} + +/// The HDR output `caps` can present: HDR10 where offered, else scRGB. +/// `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only that one. +pub fn output(caps: &wgpu::SurfaceCapabilities) -> Option { + pick(caps, std::env::var("HORIZON_HDR_OUTPUT").ok().as_deref()) +} +fn pick(caps: &wgpu::SurfaceCapabilities, only: Option<&str>) -> Option { + [(Output::Pq, "pq"), (Output::ScRgb, "scrgb")] + .into_iter() + .filter(|(_, name)| only.is_none_or(|o| o == *name)) + .map(|(output, _)| output) + .find(|o| caps.color_spaces(o.format()).contains(o.space())) } struct Targets { @@ -25,6 +58,7 @@ pub struct Hdr { layout: wgpu::BindGroupLayout, pipeline: wgpu::RenderPipeline, params: wgpu::Buffer, + pub output: Output, /// The frame's format: what every other pipeline draws in. format: wgpu::TextureFormat, targets: Option, @@ -36,7 +70,7 @@ pub struct Hdr { } impl Hdr { - pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, output: Output) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon HDR"), source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()), @@ -90,7 +124,7 @@ impl Hdr { entry_point: Some("fs_hdr"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { - format: FORMAT, + format: output.format(), blend: None, write_mask: wgpu::ColorWrites::ALL, })], @@ -100,7 +134,7 @@ impl Hdr { }); let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Horizon HDR parameters"), - size: 16, + size: 32, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -108,6 +142,7 @@ impl Hdr { layout, pipeline, params, + output, format, targets: None, debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"), @@ -198,6 +233,10 @@ impl Hdr { (self.peak / paper).max(1.0), f32::from(u8::from(world)), f32::from(u8::from(self.debug)), + f32::from(u8::from(self.output == Output::Pq)), + 0.0, + 0.0, + 0.0, ]; queue.write_buffer(&self.params, 0, bytemuck::cast_slice(¶ms)); let view = target.create_view(&Default::default()); @@ -220,3 +259,37 @@ impl Hdr { pass.draw(0..3, 0..1); } } + +#[cfg(test)] +mod tests { + use super::{Output, pick}; + use wgpu::{SurfaceColorSpaces as S, TextureFormat as F}; + + fn caps(offered: &[(F, S)]) -> wgpu::SurfaceCapabilities { + wgpu::SurfaceCapabilities { + format_capabilities: offered + .iter() + .map(|&(format, color_spaces)| wgpu::SurfaceFormatCapabilities { + format, + color_spaces, + }) + .collect(), + ..Default::default() + } + } + + #[test] + fn hdr10_first_then_scrgb() { + let both = caps(&[ + (F::Bgra8UnormSrgb, S::SRGB), + (F::Rgb10a2Unorm, S::BT2100_PQ | S::BT2100_HLG), + (F::Rgba16Float, S::EXTENDED_SRGB_LINEAR), + ]); + assert_eq!(pick(&both, None), Some(Output::Pq)); + assert_eq!(pick(&both, Some("scrgb")), Some(Output::ScRgb)); + let scrgb = caps(&[(F::Rgba16Float, S::EXTENDED_SRGB_LINEAR)]); + assert_eq!(pick(&scrgb, None), Some(Output::ScRgb)); + assert_eq!(pick(&scrgb, Some("pq")), None); + assert_eq!(pick(&caps(&[(F::Bgra8UnormSrgb, S::SRGB)]), None), None); + } +} diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 4f6f04bc0..7a2f5e225 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -255,7 +255,7 @@ pub struct Graphics { pub resolution_scale: u32, /// FXAA over the world. pub fxaa: bool, - /// HDR output (scRGB), where the display path offers it. + /// HDR output (HDR10, or scRGB), where the display path offers it. pub hdr: bool, /// HDR paper white (where SDR white sits), in nits. pub hdr_paper_white: u32, diff --git a/crates/horizon-client/src/hdr.wgsl b/crates/horizon-client/src/hdr.wgsl index bf6c27cca..8f6c25d12 100644 --- a/crates/horizon-client/src/hdr.wgsl +++ b/crates/horizon-client/src/hdr.wgsl @@ -1,6 +1,6 @@ // Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma -// space, decoded to linear light at the paper white and written to the scRGB -// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the +// space, decoded to linear light at the paper white and written to the swapchain: +// HDR10 (BT.2020, PQ) or scRGB (1.0 = 80 nits). Bright pixels of light sources that still show the // world as it was before the hand and HUD are expanded towards the peak. @group(0) @binding(0) var frame: texture_2d; @group(0) @binding(1) var world: texture_2d; @@ -14,6 +14,8 @@ struct Params { world: f32, // 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1). debug: f32, + // 1 for an HDR10 swapchain, 0 for scRGB. + pq: f32, }; @group(0) @binding(2) var params: Params; @@ -40,6 +42,19 @@ fn shows_world(c: vec3, w: vec3) -> bool { return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03)); } +// Linear BT.709 to BT.2020 (ITU-R BT.2087), columns first. +const BT709_TO_BT2020 = mat3x3( + vec3(0.6274, 0.0691, 0.0164), + vec3(0.3293, 0.9195, 0.0880), + vec3(0.0433, 0.0114, 0.8956), +); + +// SMPTE ST 2084: nits (up to 10000) to the PQ signal. +fn pq(nits: vec3) -> vec3 { + let y = pow(clamp(nits / 10000.0, vec3(0.0), vec3(1.0)), vec3(0.1593017578125)); + return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), vec3(78.84375)); +} + @vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); return vec4(p * 2.0 - 1.0, 0.0, 1.0); @@ -65,5 +80,9 @@ fn shows_world(c: vec3, w: vec3) -> bool { } } } - return vec4(light * params.paper, 1.0); + let scrgb = light * params.paper; + if params.pq > 0.5 { + return vec4(pq(BT709_TO_BT2020 * scrgb * 80.0), 1.0); + } + return vec4(scrgb, 1.0); } diff --git a/docs/graphics.md b/docs/graphics.md index dcba29773..79c969d90 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -29,7 +29,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi **Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are. -**HDR** (Display, off by default) presents to an scRGB swapchain (`Rgba16Float`, extended linear sRGB) on displays and compositors that offer it. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain. +**HDR** (Display, off by default) presents to an HDR10 swapchain (`Rgb10a2Unorm`, BT.2020 with the PQ curve) or, where only that is offered, an scRGB one (`Rgba16Float`, extended linear sRGB), on displays and compositors that offer either; `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only one. The frame is drawn exactly as in SDR, in vanilla's gamma space, and a last pass (`hdr.wgsl`) decodes it to linear light at the **Paper White** and lifts light sources (blocks that emit light, lava, the sun and the moon) towards the **Peak Brightness**; everything else stays as in SDR. The mesher puts the light a block's face emits in its vertex colour's alpha (`EMISSION_BITS`), the frame's alpha carries the mark, and only pixels that still show the world before the hand and HUD are lifted. On Vulkan, `horizon-hdr` sends HDR metadata (MaxCLL, mastering luminance), which wgpu doesn't: without it a compositor may clip everything above SDR white. KWin maps the content's reference white onto the desktop's SDR brightness, so on Linux the default Paper White matches SDR mode. `HORIZON_HDR_DEBUG=1` paints lifted pixels magenta. Not lifted yet: glowing particles, distant LOD terrain. Which settings each screen shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); `graphics_style.rs` draws them. From 49ad61035b285c0d24bca0cde1027fd3bf60b41e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:47:11 +0100 Subject: [PATCH 057/195] Count shield damage only for accepted hits and skip kills saved by a totem --- crates/horizon-client/src/game/combat.rs | 5 ++++- crates/horizon-client/src/game/lan_pvp.rs | 4 +++- crates/horizon-client/src/game/shield.rs | 7 ------- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 197c77f17..fee887f97 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -74,11 +74,14 @@ impl Game<'_> { for e in events { let (name, amount) = match e { // LivingEntity.getDamageAfterMagicAbsorb (Resistance) and - // Player.actuallyHurt (absorption hearts), in tenths. + // Player.actuallyHurt (absorption hearts) and + // LivingEntity.hurtServer (the shield, only for an accepted + // hit), in tenths. MotionEvent::Health(HealthEvent::Statistic { name, amount }) => { match *name { "resisted" => self.stats.custom("damage_resisted", *amount), "absorbed" => self.stats.custom("damage_absorbed", *amount), + "blocked" => self.stats.custom("damage_blocked_by_shield", *amount), _ => {} } continue; diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index a2ff13444..276a33c83 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -256,10 +256,12 @@ impl Game<'_> { // ServerPlayer.awardKillScore: the blow that kills a player. if hurt { let died = match victim { + // A totem that fired is applied on the next tick_totem, so the + // host is still at zero health but is not dying. Victim::Host => self .player .as_ref() - .is_some_and(|p| p.health.dead_or_dying()), + .is_some_and(|p| p.health.dead_or_dying() && !p.health.totem_used), Victim::Guest(conn) => host .hub .guest(conn) diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index f4642f272..c4f7f98d1 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -121,13 +121,6 @@ impl Game<'_> { attacker: Option, projectile: bool, ) { - // LivingEntity.hurtServer: the damage the shield took, in tenths. - if outcome.blocked > 0.0 { - self.stats.custom( - "damage_blocked_by_shield", - (outcome.blocked * 10.0).round() as i32, - ); - } let Some((slot, _)) = self.using else { return }; let Some(stack) = self.stack_in(slot).cloned() else { return; From 36ef05b0b9470051b8a5e9e01ce0ba4811a30e0a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:51:22 +0100 Subject: [PATCH 058/195] Keep infinite mob effects through the effect tick --- crates/horizon-client/src/mobs/ai.rs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 8335cb745..68d5caee5 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1455,25 +1455,31 @@ fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); for (effect, ticks, amp) in &mut effects { let interval = |base: i32| (base >> (*amp).max(0)).max(1); + // MobEffectInstance.tickServer: an infinite (-1) effect times its + // ticks by the mob's tickCount and never counts down. + let infinite = *ticks == -1; + let count = if infinite { m.age as i32 } else { *ticks }; match *effect { "minecraft:poison" - if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => + if count % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } - "minecraft:wither" if *ticks % interval(40) == 0 => { + "minecraft:wither" if count % interval(40) == 0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } "minecraft:regeneration" - if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => + if count % interval(50) == 0 && !m.kind.flags.undead && m.alive() => { m.health = (m.health + 1.0).min(m.attrs.max_health); } _ => {} } - *ticks -= 1; + if !infinite { + *ticks -= 1; + } } - effects.retain(|e| e.1 > 0); + effects.retain(|e| e.1 > 0 || e.1 == -1); m.extra.effects = effects; } From 5d3e9d218dc9a74b712a91d0fe504b0ca532852d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 17:05:35 +0100 Subject: [PATCH 059/195] Clean copper for a skeleton trap's visual lightning too --- crates/horizon-client/src/game/lightning.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 55e867f87..7daab2ef8 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -221,6 +221,12 @@ impl Game<'_> { if !b.visual_only { self.bolt_fire(b.at, 4); self.strike_rod(b.at); + } + // LightningBolt.tick runs clearCopperOnLightningStrike for + // every server bolt, a skeleton trap's visual one included; + // a client's copy of a server bolt (spawn_remote_bolt) only + // flashes. + if self.remote.is_none() { self.bolt_clear_copper(b.at); } } From ba3b567f54ef63c6c3d00d93b9a81c04e80a411e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 17:15:29 +0100 Subject: [PATCH 060/195] Predict a full beehive reacting to shears and glass bottles on the client --- crates/horizon-client/src/game/remote.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..b0a466d9d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4084,6 +4084,16 @@ impl Game<'_> { if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { return (false, DryUse::default()); } + // BeehiveBlock.useItemOn: shears or a glass bottle on a full hive + // (honey level 5) is SUCCESS, so the click ends after UseItemOn and + // no UseItem follows (the server does the harvest, see `use_beehive`). + if held.is_some_and(|s| matches!(&*s.item, "minecraft:shears" | "minecraft:glass_bottle")) + && self + .hive_state(hit.pos) + .is_some_and(|(honey, _)| honey == Some(5)) + { + return (true, DryUse::default()); + } use horizon_core::geometry::Direction; let face = match hit.face { [0, 1, 0] => Direction::Up, From b62095dfcb58d5bd3b77bd40b1cdea70e4766de4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 17:25:37 +0100 Subject: [PATCH 061/195] Run the trident player_hurt_entity trigger as the thrower --- crates/horizon-client/src/game/trident.rs | 27 ++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 04a1be415..74525e69a 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -30,6 +30,8 @@ pub(super) struct ThrownTrident { pub(super) no_physics: bool, returning: u32, creative_only: bool, + /// The guest that threw it (`Projectile.getOwner`); `None` for the host. + guest: Option, } impl ThrownTrident { /// A trident a server sent (`handleAddEntity`): placed and moved by it. @@ -49,6 +51,7 @@ impl ThrownTrident { no_physics: false, returning: 0, creative_only: false, + guest: None, } } /// One tick of a server's client: the previous position, then `step`. @@ -240,11 +243,33 @@ impl Game<'_> { no_physics: false, returning: 0, creative_only: self.creative, + guest: self.lan_acting, }); self.player_projectile_shot(); self.audio .play("minecraft:item.trident.throw", at, 1.0, 1.0); } + /// The thrower's `PLAYER_HURT_ENTITY` for a trident hit: run as the + /// guest that threw it, and not at all once they have left. + fn thrower_hit( + &mut self, + guest: Option, + victim: &horizon_client::advancements::EntityView, + direct: horizon_client::advancements::EntityView, + damage: f32, + ) { + let Some(conn) = guest.filter(|c| self.lan_acting != Some(*c)) else { + self.player_hit(victim, "minecraft:trident", Some(direct), damage); + return; + }; + let Some(mut host) = self.lan.take() else { + return; + }; + self.as_guest(&mut host, conn, |g| { + g.player_hit(victim, "minecraft:trident", Some(direct), damage) + }); + self.lan = Some(host); + } pub(super) fn tick_tridents(&mut self) { let Some(eye) = self.eye_position() else { return; @@ -331,7 +356,7 @@ impl Game<'_> { position: [t.position.x, t.position.y, t.position.z], ..Default::default() }; - self.player_hit(&victim, "minecraft:trident", Some(direct), damage); + self.thrower_hit(t.guest, &victim, direct, damage); } self.audio.play( "minecraft:item.trident.hit", From e50eb7c71f5e5e7e7b27e2d8047f136e90f0ddc7 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 12:36:46 -0400 Subject: [PATCH 062/195] Count leave_game for every player who leaves, owner included Vanilla's PlayerList.remove awards Stats.LEAVE_GAME to a player before saving them, and PlayerList.removeAll does it for everyone when the server stops. Horizon only counted it in the in-frame path, so on the default server thread the owner never got it, and guests who left or were removed at shutdown did not either. LanHost::award_leave_game counts it once per guest (a guest is saved more than once on the way out) and runs where a guest leaves, when the integrated server stops, and when LAN closes. Part of #2095 (item 4 of the report). The signal handling and the remote-world disconnect are #2116's. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/integrated.rs | 2 ++ crates/horizon-client/src/game/lan.rs | 31 +++++++++++++++++++ crates/horizon-client/src/game/lan_actions.rs | 3 ++ 3 files changed, 36 insertions(+) diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index dd1c04e23..6758c7c89 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -408,6 +408,8 @@ impl Game<'_> { s.flags.published.store(0, Ordering::Relaxed); } if let Some(mut host) = self.lan.take() { + // PlayerList.removeAll: the owner and every guest leave the game. + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9f468db9f..9226240bd 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -78,6 +78,33 @@ pub(super) struct LanHost { states: lan::entity::States, } +impl LanHost { + /// `PlayerList.remove`: `player.awardStat(Stats.LEAVE_GAME)` before the + /// player is saved. Once per guest, however often they are saved. + pub(super) fn award_leave_game(&mut self, conn: u32) { + if let Some(play) = self.play.get_mut(&conn) + && !play.left_game + { + play.left_game = true; + play.stats.custom("leave_game", 1); + } + } + + /// `PlayerList.removeAll`: every player who joined leaves with the world. + pub(super) fn award_leave_game_to_all(&mut self) { + let conns: Vec = self + .hub + .guests + .iter() + .filter(|g| g.placed) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.award_leave_game(conn); + } + } +} + /// The player who owns an integrated server's world: a guest whose state is /// the world's own player (`players/data/.dat`), as in /// single player. @@ -634,6 +661,7 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } @@ -1016,6 +1044,9 @@ impl Game<'_> { } } self.lan_crafting_left(&mut host, &mut guest); + if guest.placed { + host.award_leave_game(guest.conn); + } self.save_guest(&host, &guest); host.models.remove(&guest.conn); host.play.remove(&guest.conn); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index e1a13881c..dffb0177e 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -74,6 +74,9 @@ pub(super) struct GuestPlay { potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, + /// `Stats.LEAVE_GAME` is counted: a guest is saved more than once on the + /// way out, the statistic is awarded once (`LanHost::award_leave_game`). + pub(super) left_game: bool, last_inventory: u64, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, From 2a98f584dfaf78561ffde4643b4e20fc8fe1d9a7 Mon Sep 17 00:00:00 2001 From: Eshayat Al-Wasiu Date: Mon, 26 Oct 2026 22:40:12 +0600 Subject: [PATCH 063/195] Send cushion breaking particles to nearby multiplayer clients Co-Authored-By: Codex --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/cushions.rs | 24 +++--- crates/horizon-client/src/game/lan.rs | 29 ++++++++ tests/test_cushion_particles.py | 87 ++++++++++++++++++++++ tools/lan_e2e.py | 6 ++ 5 files changed, 135 insertions(+), 13 deletions(-) create mode 100644 tests/test_cushion_particles.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..f05be393a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1584,6 +1584,7 @@ struct Game<'a> { guest_use: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_cushion_breaks: Vec<(horizon_world::registry::BlockStateId, [f64; 3])>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, @@ -12477,6 +12478,7 @@ impl<'a> Game<'a> { forced_hit: None, guest_use: None, lan_events: Vec::new(), + lan_cushion_breaks: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), lan_critical_hits: Vec::new(), diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs index 0847321d6..30af72104 100644 --- a/crates/horizon-client/src/game/cushions.rs +++ b/crates/horizon-client/src/game/cushions.rs @@ -348,11 +348,15 @@ impl Game<'_> { let Some(state) = self.pack.assets.registry.default_state(&name) else { return; }; - let at = [ - c.position.x.floor() as i32, - c.position.y.floor() as i32, - c.position.z.floor() as i32, - ]; + let p = c.position; + // Entity.getY(2/3) is relative to the cushion's quarter-block height. + let particle_at = [p.x, p.y + 0.25 * (2.0 / 3.0), p.z]; + // Guest actions temporarily take self.lan; flush once the hub is back. + // Queue before resolving a sprite: a dedicated server has no renderer. + if self.audio.capture.is_some() { + self.lan_cushion_breaks.push((state, particle_at)); + } + let at = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; let Some((sprite, tint)) = self.particle_sprite(state, at) else { return; }; @@ -361,14 +365,8 @@ impl Game<'_> { sprite, tint, ); - let p = c.position; - self.particles.send_particles( - &options, - [p.x, p.y + 0.666_666_7, p.z], - [0.25, 0.0625, 0.25], - 0.05, - 10, - ); + self.particles + .send_particles(&options, particle_at, [0.25, 0.0625, 0.25], 0.05, 10); } /// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 63aea7e9f..75500ba79 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -21,6 +21,7 @@ use horizon_core::geometry::Vec3; use horizon_protocol::{ crypto::offline_uuid, entity_data::{Value, serializer}, + packets::play::{self, Clientbound as C}, }; use std::{ collections::HashMap, @@ -665,6 +666,7 @@ impl Game<'_> { self.audio.capture = None; self.lan_events.clear(); self.lan_critical_hits.clear(); + self.lan_cushion_breaks.clear(); self.streaming.extra.clear(); if announce { self.system_message(Text::translate( @@ -1229,6 +1231,33 @@ impl Game<'_> { /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { let critical_hits = std::mem::take(&mut self.lan_critical_hits); + for (state, at) in std::mem::take(&mut self.lan_cushion_breaks) { + if let Some(id) = host + .hub + .registry_id("minecraft:particle_type", "minecraft:block") + { + host.hub.broadcast_near( + at, + 32.0, + &C::LevelParticles(play::LevelParticles { + particle: horizon_protocol::entity_data::Particle { + id, + data: Some(horizon_protocol::entity_data::ParticleData::State( + state.0 as i32, + )), + }, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.25, 0.0625, 0.25], + max_speed: [0.05; 3], + count: 10, + randomization: 0, + }), + None, + ); + } + } for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { if kind == 2001 { host.broken diff --git a/tests/test_cushion_particles.py b/tests/test_cushion_particles.py new file mode 100644 index 000000000..adfbf2e00 --- /dev/null +++ b/tests/test_cushion_particles.py @@ -0,0 +1,87 @@ +"""Cushion particles must reach clients even when the server has no sprite atlas.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +@unittest.skipUnless(shutil.which("rustc"), "requires Rust") +class CushionParticlesTests(unittest.TestCase): + def test_headless_server_records_break_effect_before_sprite_lookup(self): + source = (ROOT / "crates/horizon-client/src/game/cushions.rs").read_text() + start = source.index(" fn cushion_break_particles(") + end = source.index(" /// `BlockAttachedEntity.tick`", start) + fixture = r''' +#![allow(dead_code)] +#[derive(Clone, Copy)] +struct Vec3 { x: f64, y: f64, z: f64 } +struct Cushion { position: Vec3 } +impl Cushion { fn color_name(&self) -> &str { "blue" } } +struct Registry; +impl Registry { + fn default_state(&self, name: &str) -> Option { + assert_eq!(name, "minecraft:blue_wool"); Some(123) + } +} +struct Assets { registry: Registry } +struct Pack { assets: Assets } +struct Audio { capture: Option<()> } +mod horizon_client { pub mod particles { + pub enum ParticleType { Block } + pub struct ParticleOptions; + impl ParticleOptions { + pub fn block(_: ParticleType, _: String, _: u32) -> Self { Self } + } +} } +#[derive(Default)] +struct Particles { count: u32 } +impl Particles { + fn send_particles(&mut self, _: &horizon_client::particles::ParticleOptions, + at: [f64; 3], spread: [f64; 3], speed: f64, count: u32) { + assert!((at[1] - (10.0 + 1.0/6.0)).abs() < 1e-12); + assert_eq!(spread, [0.25, 0.0625, 0.25]); + assert_eq!(speed, 0.05); assert_eq!(count, 10); self.count += count; + } +} +struct Game { + pack: Pack, audio: Audio, particles: Particles, headless: bool, + lan_cushion_breaks: Vec<(u32, [f64; 3])>, +} +impl Game { + fn particle_sprite(&self, _: u32, _: [i32; 3]) -> Option<(String, u32)> { + (!self.headless).then(|| ("block/blue_wool".into(), 0xffffff)) + } +METHOD +} +fn main() { + let cushion = Cushion { position: Vec3 { x: 1.5, y: 10.0, z: 2.5 } }; + for headless in [true, false] { + for serving in [true, false] { + let mut game = Game { + pack: Pack { assets: Assets { registry: Registry } }, + audio: Audio { capture: serving.then_some(()) }, + particles: Particles::default(), headless, lan_cushion_breaks: vec![], + }; + game.cushion_break_particles(&cushion); + assert_eq!(game.lan_cushion_breaks.len(), usize::from(serving)); + if serving { + let (state, at) = game.lan_cushion_breaks[0]; + assert_eq!(state, 123); + assert_eq!([at[0], at[2]], [1.5, 2.5]); + assert!((at[1] - (10.0 + 1.0/6.0)).abs() < 1e-12); + } + assert_eq!(game.particles.count, if headless { 0 } else { 10 }); + } + } +} +'''.replace("METHOD", source[start:end]) + with tempfile.TemporaryDirectory(prefix="cushion-particles-") as directory: + path = Path(directory) + (path / "main.rs").write_text(fixture) + subprocess.run(["rustc", "--edition=2024", str(path / "main.rs"), "-o", str(path / "probe")], + check=True, capture_output=True, text=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c508a67d6..6847f8322 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -7235,9 +7235,15 @@ def check_cushions(host, guest, out): assert player('status').get('riding') is None, seen player('command', command='gamemode creative') player.raw('look-at', at[0], at[1] + .125, at[2]) + before = {g.name: g('status').get('particles', {}).get('block', 0) for g in (host, guest)} player.raw('mouse', 'left', 'click') player.wait(10) assert not cushions(host) and not cushions(player), seen + seen[label]['break_particles'] = { + g.name: g('status').get('particles', {}).get('block', 0) - before[g.name] + for g in (host, guest) + } + assert all(n == 10 for n in seen[label]['break_particles'].values()), seen return seen From b37528f5d6e1f87ff59fdf40763c9ae3ce9f9cc1 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 17:51:54 +0100 Subject: [PATCH 064/195] Pause menu: server links ClientboundServerLinksPacket (configuration and play) decoded and kept, the pause menu gains its "Server Links..." button when a server sends links, opening the server_links dialog screen: scrollable link buttons, ConfirmLinkScreen on click (chatLinks/chatLinksPrompt honoured), and the custom-screens warning with its disconnect. A dedicated server sends its `bug-report-link` property as the BUG_REPORT link, like vanilla. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 32 ++ crates/horizon-client/src/game/agent.rs | 3 + crates/horizon-client/src/game/control.rs | 3 + crates/horizon-client/src/game/dedicated.rs | 16 + crates/horizon-client/src/game/packs.rs | 4 + crates/horizon-client/src/game/remote.rs | 9 + crates/horizon-client/src/game/screens.rs | 91 +++- .../horizon-client/src/game/server_links.rs | 487 ++++++++++++++++++ crates/horizon-client/src/lan/conn.rs | 10 + crates/horizon-client/src/lan/mod.rs | 5 + crates/horizon-client/src/net.rs | 9 + crates/horizon-client/src/options_ui.rs | 5 + crates/horizon-client/src/settings.rs | 4 + .../src/packets/configuration.rs | 61 +++ crates/horizon-protocol/src/packets/play.rs | 5 +- 15 files changed, 726 insertions(+), 18 deletions(-) create mode 100644 crates/horizon-client/src/game/server_links.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..ca9e7110a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -150,6 +150,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_links; mod server_mods; mod server_packs; mod server_travel; @@ -490,6 +491,12 @@ enum Screen { Friends, /// CommandBlockEditScreen (game/command_blocks.rs). CommandBlock, + /// ServerLinksDialogScreen: a server's links (game/server_links.rs). + ServerLinks, + /// ConfirmLinkScreen for a server link (game/server_links.rs). + ConfirmLink, + /// DialogScreen.WarningScreen: the note about custom screens. + DialogWarning, /// WinScreen: the end poem and the credits (game/win.rs). Win, /// A `ui` mod's own screen, or its settings page from Options > Mods @@ -1641,6 +1648,8 @@ struct Game<'a> { restore_player_state: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, + /// The Server Links screens' state (game/server_links.rs). + links_ui: server_links::LinksUi, camera_type: perspective::CameraType, fangs: fangs::FangState, /// The local player as a model (third person, the inventory). @@ -4765,6 +4774,9 @@ impl Game<'_> { | Screen::Advancements | Screen::WorldOptions | Screen::Friends + | Screen::ServerLinks + | Screen::ConfirmLink + | Screen::DialogWarning | Screen::CommandBlock ) || self.book.is_some() || self.win_screen_pauses()) @@ -5248,6 +5260,9 @@ impl Game<'_> { Screen::Advancements => self.draw_advancements(&mut batch), Screen::WorldOptions => self.draw_world_options(&mut batch), Screen::Friends => self.draw_friends_screen(&mut batch), + Screen::ServerLinks => self.draw_server_links(&mut batch), + Screen::ConfirmLink => self.draw_confirm_link(&mut batch), + Screen::DialogWarning => self.draw_dialog_warning(&mut batch), Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); @@ -10786,6 +10801,10 @@ impl Game<'_> { Screen::GameModeSwitcher => self.close_gamemode_switcher(false), Screen::Dead => {} Screen::Stats | Screen::Friends => self.screen = Screen::Paused, + Screen::ServerLinks => self.screen = Screen::Paused, + // ConfirmScreen.keyPressed: Escape answers no; both return to + // the Server Links screen they came from. + Screen::ConfirmLink | Screen::DialogWarning => self.screen = Screen::ServerLinks, Screen::Advancements => self.close_advancements(), Screen::WorldOptions => self.world_options_escape(), Screen::CommandBlock => self.close_command_block(), @@ -11465,6 +11484,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::WorldOptions && d != 0.0 { self.world_options_scroll(d); } + if self.screen == Screen::ServerLinks && d != 0.0 { + self.server_links_scroll(d); + } if self.screen == Screen::Advancements { self.advancements_scroll(scaled(raw_x) as f32, d); } @@ -11655,6 +11677,15 @@ impl ApplicationHandler for Game<'_> { Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } + Screen::ServerLinks if pressed && button == MouseButton::Left => { + self.server_links_click()? + } + Screen::ConfirmLink if pressed && button == MouseButton::Left => { + self.confirm_link_click() + } + Screen::DialogWarning if pressed && button == MouseButton::Left => { + self.dialog_warning_click()? + } Screen::WorldOptions if button == MouseButton::Left => { self.world_options_release() } @@ -12511,6 +12542,7 @@ impl<'a> Game<'a> { restore_player_state: true, stats_ui: Default::default(), adv_ui: Default::default(), + links_ui: Default::default(), camera_type: Default::default(), fangs: Default::default(), player_model: None, diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index fa9dbf3c6..0b82ac0b8 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -419,6 +419,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 3202b23f4..6c910ab8a 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -875,6 +875,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..10e10cd31 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -618,6 +618,22 @@ impl Game<'_> { log_ips: props.log_ips, }), resource_pack: props.resource_pack.clone(), + // DedicatedServer.serverLinks: `bug-report-link` as the only link + // (ServerLinks.KnownLinkType.BUG_REPORT is id 0). + server_links: if props.bug_report_link.is_empty() { + Vec::new() + } else if super::server_links::valid_untrusted_uri(&props.bug_report_link) { + vec![horizon_protocol::packets::configuration::ServerLink { + kind: horizon_protocol::packets::configuration::ServerLinkKind::Known(0), + link: props.bug_report_link.clone(), + }] + } else { + log( + "WARN", + &format!("Failed to parse bug link {}", props.bug_report_link), + ); + Vec::new() + }, }; let config = HubConfig { default_game_mode: game_mode, diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..e5026cd17 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -34,6 +34,10 @@ pub fn open_folder(dir: &Path) { log::warn!("Horizon: could not open {}: {e}", dir.display()); } } +/// `Util.getPlatform().openUri`: the system browser on the link. +pub fn open_uri(uri: &str) { + open_folder(Path::new(uri)); +} /// The resource root to load from, given the vanilla root, the selection and /// a server's packs, which go on top (`Pack.Position.TOP`, fixed). pub fn startup_root( diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3ef87c201..6e770aaeb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -212,6 +212,9 @@ pub(super) struct Remote { /// `ClientboundTransferPacket`'s target: when the connection ends the /// game connects here, the stored cookies carried over (`TransferState`). transfer: Option, + /// `ClientCommonPacketListenerImpl.serverLinks`: the links "Server + /// Links..." in the pause menu lists (only `http`/`https` URIs kept). + pub(super) server_links: Vec, } /// The time a frame spends on chunk packets before it leaves the rest of @@ -486,6 +489,7 @@ impl Game<'_> { chunk_center: (0, 0), backlog: VecDeque::new(), backlog_since: None, + server_links: Vec::new(), transfer: None, }); // The level's TickRateManager follows the server's ticking packets. @@ -862,6 +866,11 @@ impl Game<'_> { } Event::PackPush(p) => self.handle_pack_push(p), Event::PackPop(id) => self.handle_pack_pop(id), + Event::ServerLinks(links) => { + if let Some(r) = self.remote.as_mut() { + r.server_links = super::server_links::trusted(links); + } + } Event::ShowDialog(dialog) => self.show_dialog(&dialog), Event::ClearDialog => self.clear_dialog(), Event::DecodeError(e) => { diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index f8885f83a..750895adb 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -19,6 +19,9 @@ impl Screen { | Self::Advancements | Self::WorldOptions | Self::Friends + | Self::ServerLinks + | Self::ConfirmLink + | Self::DialogWarning | Self::Mod => true, Self::Playing | Self::GameModeSwitcher @@ -35,20 +38,35 @@ impl Screen { } /// PauseScreen buttons: (x, y, width, label key, action id, active). +/// `links`: the `minecraft:server_links` dialog's button, which the +/// `pause_screen_additions` tag (empty in vanilla) falls back to when the +/// server sent links — a full-width row that pushes the last two rows down. /// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen -fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { +fn pause_buttons( + w: f32, + h: f32, + remote: bool, + links: bool, +) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { // GridLayout of two 98px columns (padding 4), aligned at (0.5, 0.25). - let (grid_w, grid_h) = (212.0, 166.0); + let (grid_w, grid_h) = (212.0, 166.0 + if links { 24.0 } else { 0.0 }); let x0 = ((w - grid_w) * 0.5).floor(); let y0 = ((h - grid_h) * 0.25).floor(); - vec![ + let down = if links { 24.0 } else { 0.0 }; + let mut v = vec![ (x0 + 4.0, y0 + 50.0, 204.0, "menu.returnToGame", 0, true), (x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 4, true), (x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 3, true), - (x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true), + ]; + if links { + // CommonDialogData.computeExternalTitle of Dialogs.SERVER_LINKS. + v.push((x0 + 4.0, y0 + 122.0, 204.0, "menu.server_links", 11, true)); + } + v.extend([ + (x0 + 4.0, y0 + 122.0 + down, 98.0, "menu.options", 1, true), ( x0 + 110.0, - y0 + 122.0, + y0 + 122.0 + down, 98.0, "options.worldOptions.button", 9, @@ -56,7 +74,7 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s ), ( x0 + 4.0, - y0 + 146.0, + y0 + 146.0 + down, 204.0, if remote { "menu.disconnect" @@ -66,16 +84,17 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s 2, true, ), - ] + ]); + v } /// The icon row: report bugs, feedback, friends, player reporting. /// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's /// Play with Friends; the others stay inactive. const FRIENDS_ICON: usize = 2; -fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { +fn pause_icons(w: f32, h: f32, links: bool) -> [(f32, f32, &'static str); 4] { let x0 = ((w - 212.0) * 0.5).floor() + 60.0; - let y = ((h - 166.0) * 0.25).floor() + 98.0; + let y = ((h - 166.0 - if links { 24.0 } else { 0.0 }) * 0.25).floor() + 98.0; [ (x0, y, "gui/sprites/pause_menu/bug"), (x0 + 24.0, y, "gui/sprites/pause_menu/social_interactions"), @@ -120,7 +139,9 @@ impl Game<'_> { u32::MAX, true, ); - for (x, y, bw, key, _, active) in pause_buttons(w, h, self.external_server()) { + let links = !self.server_links().is_empty(); + let mut tooltip = None; + for (x, y, bw, key, id, active) in pause_buttons(w, h, self.external_server(), links) { let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); ui::button( batch, @@ -133,9 +154,12 @@ impl Game<'_> { active, hover, ); + // PauseScreen's customAdditions button: CUSTOM_OPTIONS_TOOLTIP. + if id == 11 && hover { + tooltip = Some(Text::translate("menu.custom_options.tooltip", &[])); + } } - let mut tooltip = None; - for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() { + for (i, (x, y, sprite)) in pause_icons(w, h, links).into_iter().enumerate() { let active = i == FRIENDS_ICON && friends; let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0); // The icon has no label: name it for controller focus and the @@ -168,7 +192,13 @@ impl Game<'_> { } // SpriteIconButton.withTootip: the label as a tooltip. if let Some(tip) = tooltip { - ui::tooltip(batch, atlas, &[tip], self.cursor); + let lines: Vec = atlas + .font + .split_lines(&tip, batch.width) + .into_iter() + .map(|(line, _)| line) + .collect(); + ui::tooltip(batch, atlas, &lines, self.cursor); } } pub(super) fn pause_click(&mut self) -> Result<()> { @@ -180,8 +210,9 @@ impl Game<'_> { let b = HudBatch::new(size); (b.width, b.height) }; - let friends = pause_icons(w, h)[FRIENDS_ICON]; - let hit = pause_buttons(w, h, self.external_server()) + let links = !self.server_links().is_empty(); + let friends = pause_icons(w, h, links)[FRIENDS_ICON]; + let hit = pause_buttons(w, h, self.external_server(), links) .into_iter() .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)) .map(|b| b.4) @@ -200,6 +231,11 @@ impl Game<'_> { Some(4) => self.open_advancements(true), Some(9) => self.open_world_options(), Some(10) => self.screen = Screen::Friends, + // DialogConnectionAccess.openDialog(Dialogs.SERVER_LINKS). + Some(11) => { + self.links_ui.scroll = 0.0; + self.screen = Screen::ServerLinks; + } Some(2) => self.close_world()?, _ => {} } @@ -357,7 +393,7 @@ impl Game<'_> { #[cfg(test)] mod tests { - use super::{Screen, pause_buttons}; + use super::{Screen, pause_buttons, pause_icons}; #[test] fn menu_blur_matches_vanilla_screen_backgrounds() { @@ -390,11 +426,32 @@ mod tests { #[test] fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() { for (remote, label) in [(false, "menu.returnToMenu"), (true, "menu.disconnect")] { - let buttons = pause_buttons(427.0, 240.0, remote); + let buttons = pause_buttons(427.0, 240.0, remote, false); let quit = buttons.iter().find(|b| b.4 == 2).unwrap(); assert_eq!(quit.3, label); assert!(quit.5); assert!(buttons.iter().any(|b| b.4 == 9 && b.5)); } } + + #[test] + fn server_links_adds_a_full_width_row_above_options() { + let with = pause_buttons(427.0, 240.0, true, true); + let without = pause_buttons(427.0, 240.0, true, false); + let links = with.iter().find(|b| b.4 == 11).unwrap(); + assert_eq!(links.2, 204.0); + assert_eq!(links.3, "menu.server_links"); + assert!(links.5); + // The icon row sits above it; Options and Disconnect move down 24. + let icons = pause_icons(427.0, 240.0, true); + let y0_icons = ((240.0f32 - 190.0) * 0.25).floor() + 98.0; + assert_eq!(icons[0].1, y0_icons); + assert!(links.1 > icons[0].1); + for b in &with { + if b.4 == 1 || b.4 == 9 || b.4 == 2 { + let same = without.iter().find(|o| o.4 == b.4).unwrap(); + assert_eq!(b.1, same.1 + 24.0 - 6.0, "{}", b.3); + } + } + } } diff --git a/crates/horizon-client/src/game/server_links.rs b/crates/horizon-client/src/game/server_links.rs new file mode 100644 index 000000000..85fda71d6 --- /dev/null +++ b/crates/horizon-client/src/game/server_links.rs @@ -0,0 +1,487 @@ +//! `ServerLinksDialogScreen`: the pause menu's "Server Links..." button opens +//! the `minecraft:server_links` dialog (the `pause_screen_additions` tag's +//! fallback when a server sent ClientboundServerLinksPacket): a scrollable +//! list of the server's links, each opened through `ConfirmLinkScreen` +//! (Screen.clickUrlAction), and the `dialog/warning_button`'s +//! DialogScreen.WarningScreen ("Note about custom screens"). +//! https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/dialog/ServerLinksDialogScreen +use super::{Game, Screen, packs::open_uri}; +use horizon_client::{Result, clipboard::Clipboard, hud::HudBatch, text::Text, ui}; +use horizon_protocol::packets::configuration::{ServerLink, ServerLinkKind}; + +/// HeaderAndFooterLayout's header and footer heights; the content wants to +/// start 30 pixels under the header (its `CONTENTS_MARGIN_TOP`). +const HEADER: f32 = 33.0; +const FOOTER: f32 = 33.0; +const CONTENT_TOP: f32 = HEADER + 30.0; +/// `server_links.json`: `columns` 1, `button_width` 310, `exit_action`'s 200. +const LINK_WIDTH: f32 = 310.0; +/// packControlsIntoColumns: rowSpacing 2 under the 20-pixel buttons. +const ROW: f32 = 22.0; +/// ScrollableLayout's BOTH reserve (scrollbarSpacing 4 + SCROLLBAR_WIDTH 6). +const SCROLL_RESERVE: f32 = 10.0; +/// DialogScreen's `dialog/warning_button` ImageButton. +const WARNING_BUTTON: f32 = 20.0; + +/// The ServerLinks screen's state: ScrollableLayout's scroll and the link +/// ConfirmLinkScreen is asking about (`Screen::ConfirmLink`). +#[derive(Default)] +pub(super) struct LinksUi { + pub scroll: f32, + pub confirm: Option, +} + +/// `Util.parseAndValidateUntrustedUri`: an absolute `http`/`https` URI +/// (java.net.URI's scheme then the allowlist; whitespace-free). +pub(super) fn valid_untrusted_uri(uri: &str) -> bool { + let Some(colon) = uri.find(':') else { + return false; + }; + let scheme = &uri[..colon]; + let mut chars = scheme.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + { + return false; + } + if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") { + return false; + } + !uri.chars().any(|c| c.is_control() || c == ' ') +} +/// `ClientCommonPacketListenerImpl.handleServerLinks`: keep only the links +/// that validate, warning about the dropped ones. +pub(super) fn trusted(links: Vec) -> Vec { + links + .into_iter() + .filter(|l| { + let ok = valid_untrusted_uri(&l.link); + if !ok { + log::warn!("Horizon: server sent an invalid link: {}", l.link); + } + ok + }) + .collect() +} +/// `ServerLinks.Entry.displayName`: `known_server_link.` for a known +/// type (ByIdMap.ZERO reads unknown ids as `report_bug`), the component else. +fn link_label(link: &ServerLink) -> Text { + const KNOWN: [&str; 10] = [ + "report_bug", + "community_guidelines", + "support", + "status", + "feedback", + "community", + "website", + "forums", + "news", + "announcements", + ]; + match &link.kind { + ServerLinkKind::Known(id) => Text::translate( + &format!( + "known_server_link.{}", + KNOWN.get(*id as usize).copied().unwrap_or(KNOWN[0]) + ), + &[], + ), + ServerLinkKind::Custom(tag) => { + horizon_client::scoreboard::comp_text(&horizon_client::scoreboard::tag_to_json(tag)) + } + } +} + +/// The scrolled column of link buttons: content height and, for a list that +/// fits, the `HeaderAndFooterLayout` contents frame's top. +fn list_height(n: usize) -> f32 { + n as f32 * ROW - 2.0 +} +fn list_top(h: f32, n: usize) -> f32 { + CONTENT_TOP.min(h - FOOTER - list_height(n).min(h - HEADER - FOOTER)) +} +fn scroll_limit(h: f32, n: usize) -> f32 { + (list_height(n) - (h - HEADER - FOOTER)).max(0.0) +} + +/// `ServerLinksScreen`'s buttons as (x, y) over the scrolled content, and the +/// footer `Back` button's corner. `top` includes the scroll. +fn link_buttons(w: f32, top: f32, n: usize) -> Vec<(f32, f32)> { + let x = ((w - LINK_WIDTH - 2.0 * SCROLL_RESERVE) / 2.0 + SCROLL_RESERVE).floor(); + (0..n).map(|i| (x, top + i as f32 * ROW)).collect() +} +/// The warning button beside the title (DialogScreen's title row: 10 pixels +/// apart), clamped onto the screen (makeSureWarningButtonIsInBounds). +fn warning_button(w: f32, h: f32, title_width: f32) -> (f32, f32) { + let x = ((w - title_width - 30.0) / 2.0).floor() + title_width + 10.0; + let y = ((HEADER - WARNING_BUTTON) / 2.0).floor(); + if x < 0.0 || y < 0.0 || x > w - WARNING_BUTTON || y > h - WARNING_BUTTON { + (0.0f32.max(w - 40.0), 5.0f32.min(h)) + } else { + (x, y) + } +} +fn back_button(w: f32, h: f32) -> (f32, f32) { + ( + ((w - 200.0) / 2.0).floor(), + h - FOOTER + ((FOOTER - 20.0) / 2.0).floor(), + ) +} + +impl Game<'_> { + /// `connection.serverLinks()`: the links the open server sent (empty for + /// a world without a connection or one that sent none). + pub(super) fn server_links(&self) -> &[ServerLink] { + self.remote + .as_ref() + .map_or(&[], |r| r.server_links.as_slice()) + } + /// DialogScreen over the pause menu: `menu.server_links.title`, the + /// scrollable link buttons and `gui.back` in the footer. + pub(super) fn draw_server_links(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let links = self.server_links().to_vec(); + self.links_ui.scroll = self + .links_ui + .scroll + .clamp(0.0, scroll_limit(h, links.len())); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + // The title row: the title, then 10 pixels on the warning button. + let title = Text::translate("menu.server_links.title", &[]); + let tw = atlas.font.width_text(&title); + let tx = ((w - tw - 30.0) / 2.0).floor(); + batch.text_styled(atlas, &title, tx, 12.0, u32::MAX, true); + let (wx, wy) = warning_button(w, h, tw); + let wh = ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON); + horizon_client::widgets::record( + "menu.custom_screen_info.tooltip", + [wx, wy, WARNING_BUTTON, WARNING_BUTTON], + true, + ); + batch.sprite_scaled( + atlas, + if wh { + "gui/sprites/dialog/warning_button_highlighted" + } else { + "gui/sprites/dialog/warning_button" + }, + wx, + wy, + WARNING_BUTTON, + WARNING_BUTTON, + u32::MAX, + ); + let first = batch.vertices.len(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + for (link, (x, y)) in links.iter().zip(link_buttons(w, top, links.len())) { + let hover = inside && ui::hovered(self.cursor, x, y, LINK_WIDTH, 20.0); + ui::button( + batch, + atlas, + x, + y, + LINK_WIDTH, + 20.0, + &link_label(link), + true, + hover, + ); + } + batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); + ui::scrollbar( + batch, + atlas, + (w / 2.0).floor() + 155.0 + 4.0, + HEADER, + h - FOOTER, + list_height(links.len()), + self.links_ui.scroll.trunc(), + ); + let (bx, by) = back_button(w, h); + let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); + ui::button( + batch, + atlas, + bx, + by, + 200.0, + 20.0, + &Text::translate("gui.back", &[]), + true, + hover, + ); + if wh { + ui::tooltip( + batch, + atlas, + &[Text::translate("menu.custom_screen_info.tooltip", &[])], + self.cursor, + ); + } + } + /// A click on `Screen::ServerLinks`: a link, the warning button or Back. + pub(super) fn server_links_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let links = self.server_links().to_vec(); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + if inside + && let Some(i) = link_buttons(w, top, links.len()) + .iter() + .position(|(x, y)| ui::hovered(self.cursor, *x, *y, LINK_WIDTH, 20.0)) + { + self.audio.play_button_click(); + self.click_link(&links[i].link); + return Ok(()); + } + let title = Text::translate("menu.server_links.title", &[]); + let tw = self.gui.atlas.font.width_text(&title); + let (wx, wy) = warning_button(w, h, tw); + if ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON) { + self.audio.play_button_click(); + self.screen = Screen::DialogWarning; + return Ok(()); + } + let (bx, by) = back_button(w, h); + if ui::hovered(self.cursor, bx, by, 200.0, 20.0) { + self.audio.play_button_click(); + self.screen = Screen::Paused; + } + Ok(()) + } + /// `Screen.clickUrlAction`: "Web Links" off ignores the click; "Prompt on + /// Links" asks with ConfirmLinkScreen, else the browser opens directly. + fn click_link(&mut self, url: &str) { + if !self.settings.chat_links { + return; + } + if self.settings.chat_links_prompt { + self.links_ui.confirm = Some(url.to_owned()); + self.screen = Screen::ConfirmLink; + } else { + open_uri(url); + } + } + /// `ScrollableLayout`'s mouse wheel over the links. + pub(super) fn server_links_scroll(&mut self, delta: f32) { + let (_, h) = self.gui_size(); + self.links_ui.scroll = (self.links_ui.scroll - delta * 10.0) + .clamp(0.0, scroll_limit(h, self.server_links().len())); + } + /// `ConfirmLinkScreen` (untrusted): "Are you sure you want to open the + /// following website?", the link, the red warning, and Yes / Copy Link to + /// Clipboard / No. + pub(super) fn draw_confirm_link(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(atlas, (w, h), &url); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let labels = ["gui.yes", "gui.copy_link_to_clipboard", "gui.no"]; + for ((x, y), key) in layout.buttons.iter().zip(labels) { + let hover = ui::hovered(self.cursor, *x, *y, 100.0, 20.0); + ui::button( + batch, + atlas, + *x, + *y, + 100.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// ConfirmLinkScreen's answer: yes opens the browser, the middle button + /// copies the link, no closes; all return to Server Links. + pub(super) fn confirm_link_click(&mut self) { + let (w, h) = self.gui_size(); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(&self.gui.atlas, (w, h), &url); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 100.0, 20.0) { + continue; + } + self.audio.play_button_click(); + match i { + 0 => open_uri(&url), + 1 => { + self.clipboard.set(&url); + } + _ => {} + } + self.screen = Screen::ServerLinks; + return; + } + } + /// `DialogScreen.WarningScreen`: the custom-screens note, a disconnect + /// button ("Custom screen rejected" is the shown reason) and Back. + pub(super) fn draw_dialog_warning(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let layout = dialog_warning_layout(atlas, (w, h)); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let quit = if self.external_server() { + "menu.disconnect" + } else { + "menu.returnToMenu" + }; + for ((x, y), key) in layout.buttons.into_iter().zip([quit, "gui.back"]) { + let hover = ui::hovered(self.cursor, x, y, 150.0, 20.0); + ui::button( + batch, + atlas, + x, + y, + 150.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// WarningScreen's answer: disconnect, or back to Server Links. + pub(super) fn dialog_warning_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let layout = dialog_warning_layout(&self.gui.atlas, (w, h)); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 150.0, 20.0) { + continue; + } + self.audio.play_button_click(); + if i == 0 { + // DialogConnectionAccess.disconnect: leave with the custom + // screens' reason. + let reason = self.translate( + "menu.custom_screen_info.disconnect", + "Custom screen rejected", + ); + self.leave_server(Some(reason))?; + } else { + self.screen = Screen::ServerLinks; + } + return Ok(()); + } + Ok(()) + } +} + +/// A confirm screen's laid-out text (title, message, extra warning lines) and +/// button corners; the whole column centred (ConfirmScreen.init). +struct ConfirmLayout { + lines: Vec<(Text, f32, f32)>, + buttons: Vec<(f32, f32)>, +} +/// `ConfirmScreen.init`: title, message wrapped to `width - 50` (15 rows at +/// most), the extra lines, then a button row `spacing` 4 with `paddingTop` 16. +fn confirm_layout( + font: &horizon_client::font::Font, + (w, h): (f32, f32), + title: &Text, + message: &Text, + extra: &[Text], + button_widths: &[f32], +) -> ConfirmLayout { + let message: Vec = font + .split_lines(message, w - 50.0) + .into_iter() + .take(15) + .map(|(line, _)| line) + .collect(); + // LinearLayout vertical spacing 8; the button row's children pad 16 on top. + let extra_h = 17.0 * extra.len() as f32; + let mh = 9.0 * message.len() as f32; + let total = 9.0 + 8.0 + mh + extra_h + 8.0 + 16.0 + 20.0; + let mut y = ((h - total) / 2.0).trunc(); + let mut lines = Vec::new(); + let mut push = |line: &Text, at: f32| { + let lw = font.width_text(line); + lines.push((line.clone(), ((w - lw) / 2.0).trunc(), at)); + }; + push(title, y); + y += 17.0; + for line in &message { + push(line, y); + y += 9.0; + } + for line in extra { + y += 8.0; + push(line, y); + y += 9.0; + } + let row_w: f32 = button_widths.iter().sum::() + 4.0 * (button_widths.len() - 1) as f32; + let by = y + 8.0 + 16.0; + let mut bx = ((w - row_w) / 2.0).trunc(); + let buttons = button_widths + .iter() + .map(|bw| { + let p = (bx, by); + bx += bw + 4.0; + p + }) + .collect(); + ConfirmLayout { lines, buttons } +} +fn confirm_link_layout( + atlas: &horizon_client::hud::HudAtlas, + size: (f32, f32), + url: &str, +) -> ConfirmLayout { + // ConfirmLinkScreen (untrusted): `chat.link.confirm`, the link as the + // message, `chat.link.warning` in its red (0xFFCCCC). + confirm_layout( + &atlas.font, + size, + &Text::translate("chat.link.confirm", &[]), + &Text::literal(url.to_owned()), + &[Text::translate("chat.link.warning", &[]).with_color(0xFFCCCC)], + &[100.0; 3], + ) +} +fn dialog_warning_layout(atlas: &horizon_client::hud::HudAtlas, size: (f32, f32)) -> ConfirmLayout { + confirm_layout( + &atlas.font, + size, + &Text::translate("menu.custom_screen_info.title", &[]), + &Text::translate("menu.custom_screen_info.contents", &[]), + &[], + &[150.0; 2], + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn untrusted_uris_are_http_or_https_with_a_scheme() { + for ok in [ + "https://example.net/x", + "http://example.net", + "HTTPS://EXAMPLE.NET", + ] { + assert!(valid_untrusted_uri(ok), "{ok}"); + } + for bad in [ + "example.net/no-scheme", + "ftp://example.net", + "file:///etc/passwd", + "javascript:alert(1)", + "https://exa mple.net", + "://example.net", + "", + ] { + assert!(!valid_untrusted_uri(bad), "{bad}"); + } + } +} diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index f2dcf701d..99b70e065 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -791,6 +791,16 @@ fn login_and_configure( }, }), )?; + // ServerConfigurationPacketListenerImpl.startConfiguration: links, only + // when there are any (MinecraftServer.serverLinks is empty elsewhere). + if !shared.config.server_links.is_empty() { + send( + c, + cfg::Clientbound::ServerLinks(cfg::ServerLinks { + links: shared.config.server_links.clone(), + }), + )?; + } send( c, cfg::Clientbound::UpdateEnabledFeatures(cfg::UpdateEnabledFeatures { diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 3e9b93cac..34c465ffa 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -142,6 +142,10 @@ pub struct NetConfig { /// server.properties `resource-pack`: offered to every player during /// configuration (a dedicated server's; MinecraftServer.getServerResourcePack). pub resource_pack: Option, + /// MinecraftServer.serverLinks (a dedicated server's `bug-report-link`): + /// sent in configuration when non-empty + /// (ServerConfigurationPacketListenerImpl.startConfiguration). + pub server_links: Vec, } impl NetConfig { /// MinecraftServer.enforceSecureProfile. @@ -168,6 +172,7 @@ impl NetConfig { online: None, log: None, resource_pack: None, + server_links: Vec::new(), } } } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 34daaf85c..93364ed91 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -68,6 +68,9 @@ pub enum Event { host: String, port: i32, }, + /// `ClientboundServerLinksPacket`: the links the pause menu's "Server + /// Links..." lists (ClientCommonPacketListenerImpl.handleServerLinks). + ServerLinks(Vec), /// The connection ended. `from_server`: the server gave the reason (or /// the connection was refused for good), rather than the connection /// failing (auto-reconnect retries only failures and shutdowns). @@ -565,6 +568,9 @@ fn receive_play( play::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + play::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } // ClientCommonPacketListenerImpl.handleTransfer: the connection // ends and the game connects to the other address. play::Clientbound::Transfer(p) => { @@ -644,6 +650,9 @@ fn configure( cfg::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + cfg::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } cfg::Clientbound::Transfer(p) => { let _ = send.send(Event::Transfer { host: p.host, diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..63c6165eb 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -56,6 +56,7 @@ pub enum Opt { ChatVisibility, ChatColors, ChatLinks, + ChatLinksPrompt, ChatOpacity, TextBackgroundOpacity, ChatScale, @@ -237,6 +238,7 @@ impl Opt { Opt::ChatVisibility => "options.chat.visibility", Opt::ChatColors => "options.chat.color", Opt::ChatLinks => "options.chat.links", + Opt::ChatLinksPrompt => "options.chat.links.prompt", Opt::ChatOpacity => "options.chat.opacity", Opt::TextBackgroundOpacity => "options.accessibility.text_background_opacity", Opt::ChatScale => "options.chat.scale", @@ -574,6 +576,7 @@ impl Opt { ][usize::from(s.chat_visibility.min(2))]), Opt::ChatColors => on_off(s.chat_colors), Opt::ChatLinks => on_off(s.chat_links), + Opt::ChatLinksPrompt => on_off(s.chat_links_prompt), Opt::AutoSuggestions => on_off(s.auto_suggestions), Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), @@ -743,6 +746,7 @@ impl Opt { Opt::ChatVisibility => s.chat_visibility = next(s.chat_visibility, 3), Opt::ChatColors => s.chat_colors = !s.chat_colors, Opt::ChatLinks => s.chat_links = !s.chat_links, + Opt::ChatLinksPrompt => s.chat_links_prompt = !s.chat_links_prompt, Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions, Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, @@ -1487,6 +1491,7 @@ impl OptionsUi { Opt::ChatVisibility, Opt::ChatColors, Opt::ChatLinks, + Opt::ChatLinksPrompt, Opt::ChatOpacity, Opt::TextBackgroundOpacity, Opt::ChatScale, diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 74c428923..c64cfcb33 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -149,6 +149,7 @@ pub struct Settings { pub chat_visibility: u8, pub chat_colors: bool, pub chat_links: bool, + pub chat_links_prompt: bool, pub chat_opacity: f32, pub text_background_opacity: f32, pub chat_scale: f32, @@ -234,6 +235,7 @@ impl Default for Settings { chat_visibility: 0, chat_colors: true, chat_links: true, + chat_links_prompt: true, chat_opacity: 1.0, text_background_opacity: 0.5, chat_scale: 1.0, @@ -427,6 +429,7 @@ impl Settings { chat_visibility: f.int("chatVisibility") as u8, chat_colors: f.bool("chatColors"), chat_links: f.bool("chatLinks"), + chat_links_prompt: f.bool("chatLinksPrompt"), chat_opacity: f.double("chatOpacity") as f32, text_background_opacity: f.double("textBackgroundOpacity") as f32, chat_scale: f.double("chatScale") as f32, @@ -510,6 +513,7 @@ impl Settings { put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility)); put_b(&mut f, "chatColors", self.chat_colors); put_b(&mut f, "chatLinks", self.chat_links); + put_b(&mut f, "chatLinksPrompt", self.chat_links_prompt); put_f(&mut f, "chatOpacity", self.chat_opacity); put_f( &mut f, diff --git a/crates/horizon-protocol/src/packets/configuration.rs b/crates/horizon-protocol/src/packets/configuration.rs index ced56dacf..22a8a1456 100644 --- a/crates/horizon-protocol/src/packets/configuration.rs +++ b/crates/horizon-protocol/src/packets/configuration.rs @@ -45,6 +45,54 @@ packet!( packet!(KnownPack { namespace: String => Str, id: String => Str, version: String => Str }); packet!(SelectKnownPacks { packs: Vec => List }); packet!(CodeOfConduct { text: String => Str }); + +/// ServerLinks.UntrustedEntry's `type` (Either): a +/// known link's id, or a custom label component. +#[derive(Clone, Debug, PartialEq)] +pub enum ServerLinkKind { + /// ServerLinks.KnownLinkType by id (ByIdMap: unknown ids read as 0). + Known(i32), + /// A custom label (TRUSTED_CONTEXT_FREE_STREAM_CODEC: a component in NBT). + Custom(Tag), +} +/// ServerLinks.UntrustedEntry: the label and the unchecked link string (the +/// client keeps only `http`/`https` URIs, Util.parseAndValidateUntrustedUri). +#[derive(Clone, Debug, PartialEq)] +pub struct ServerLink { + pub kind: ServerLinkKind, + pub link: String, +} +impl Codec for ServerLink { + fn read(r: &mut Reader) -> Result { + let kind = if Bool::read(r)? { + ServerLinkKind::Known(VarInt::read(r)?) + } else { + ServerLinkKind::Custom(Nbt::read(r)?) + }; + Ok(Self { + kind, + link: Str::read(r)?, + }) + } + fn write(v: &Self, w: &mut Writer) { + match &v.kind { + ServerLinkKind::Known(id) => { + Bool::write(&true, w); + VarInt::write(id, w); + } + ServerLinkKind::Custom(tag) => { + Bool::write(&false, w); + Nbt::write(tag, w); + } + } + Str::write(&v.link, w); + } +} +packet!( + /// ClientboundServerLinksPacket (a common packet: configuration and play). + /// Links the pause menu's "Server Links..." screen lists. + ServerLinks { links: Vec => List } +); packet!( /// ClientboundShowDialogPacket.CONTEXT_FREE_STREAM_CODEC: the dialog /// itself (`Dialog.DIRECT_CODEC` as NBT). @@ -89,6 +137,7 @@ packet_enum!(Clientbound, crate::ids::configuration::clientbound { UpdateTags(UpdateTags) = UPDATE_TAGS, SelectKnownPacks(SelectKnownPacks) = SELECT_KNOWN_PACKS, ClearDialog(Empty) = CLEAR_DIALOG, + ServerLinks(ServerLinks) = SERVER_LINKS, ShowDialog(ShowDialog) = SHOW_DIALOG, CodeOfConduct(CodeOfConduct) = CODE_OF_CONDUCT, }); @@ -236,6 +285,18 @@ mod tests { Clientbound::CodeOfConduct(CodeOfConduct { text: "Be nice".into(), }), + Clientbound::ServerLinks(ServerLinks { + links: vec![ + ServerLink { + kind: ServerLinkKind::Known(0), + link: "https://bugs.example.net".into(), + }, + ServerLink { + kind: ServerLinkKind::Custom(crate::text::literal("Custom link")), + link: "https://example.net".into(), + }, + ], + }), Clientbound::ShowDialog(ShowDialog { dialog: Tag::compound([("type", Tag::String("minecraft:notice".into()))]), }), diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bc09a84..a21171693 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -15,7 +15,7 @@ use crate::{ configuration::{ ClientInformation, CookieRequest, CookieResponse, CustomClickAction, CustomPayload, Disconnect, KeepAlive, Ping, ResourcePackPop, ResourcePackPush, ResourcePackResponse, - StoreCookie, Transfer, UpdateTags, + ServerLinks, StoreCookie, Transfer, UpdateTags, }, login::Property, }, @@ -1903,6 +1903,9 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { StopSound(StopSound) = STOP_SOUND, StartConfiguration(Empty) = START_CONFIGURATION, StoreCookie(StoreCookie) = STORE_COOKIE, + // A common packet: the same `configuration::ServerLinks` the + // configuration phase sends. + ServerLinks(ServerLinks) = SERVER_LINKS, SwingAnimation(SwingAnimation) = SWING_ANIMATION, SystemChat(SystemChat) = SYSTEM_CHAT, TabList(TabList) = TAB_LIST, From 5179f975826747290826b6453cc4f1be59899265 Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:01:04 +0100 Subject: [PATCH 065/195] Server packs: show a progress screen while a pushed pack's resources reload The download toast already matched vanilla, but once a server pack was downloaded the whole resource reload ran synchronously on the render thread: the frame froze on "Joining world" for seconds where vanilla's Minecraft.reloadResourcePacks shows a LoadingOverlay with a progress bar. The reload is split like the startup loader: a worker builds the overlay root, models and sprites, the menu bundle and the pack's tables while a progress screen (Preparing resources -> Loading assets -> Loading pack tables -> Applying resources) covers the frame, then the renderer swap and resource application land on the render thread and ServerPacks.reloaded drives the feedback replies, including the recovery reload on failure. The pack screen's own reload reuses the same staged load, so its behaviour is unchanged. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 35 +++- crates/horizon-client/src/game/packs.rs | 152 ++++++++++++++---- .../horizon-client/src/game/server_packs.rs | 105 ++++++++++-- docs/resource-packs.md | 3 +- 4 files changed, 236 insertions(+), 59 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..abaa639eb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10250,6 +10250,21 @@ impl Game<'_> { } return Ok(false); } + // A server pack's reload covers the frame with its progress + // (`LoadingOverlay`) until `tick_server_packs` applies it. + if let Some(reload) = &self.server_packs.reload { + if let Some(renderer) = &mut self.renderer { + let mut hud = HudBatch::new([renderer.config.width, renderer.config.height]); + horizon_client::level_loading::draw_progress( + &mut hud, + &self.gui.atlas, + reload.progress.line(), + reload.progress.fraction(), + ); + return renderer.render(&loading_frame(&hud)); + } + return Ok(false); + } let Some(size) = self .renderer .as_ref() @@ -12742,7 +12757,6 @@ const NUMERIC_KEYS: [KeyCode; 11] = [ KeyCode::Numpad9, ]; -const STAGES: u32 = 10; const STAGE_LINES: [&str; 10] = [ "Loading menu", "Loading assets", @@ -12758,19 +12772,28 @@ const STAGE_LINES: [&str; 10] = [ /// The background loader's checkpoint, read by the loading screen each frame. #[derive(Clone)] -struct Progress(Arc); +struct Progress { + value: Arc, + lines: &'static [&'static str], +} impl Progress { fn new() -> Self { - Self(Arc::new(AtomicU32::new(0))) + Self::with(&STAGE_LINES) + } + fn with(lines: &'static [&'static str]) -> Self { + Self { + value: Arc::new(AtomicU32::new(0)), + lines, + } } fn set(&self, stage: u32) { - self.0.store(stage, Ordering::Relaxed); + self.value.store(stage, Ordering::Relaxed); } fn fraction(&self) -> f32 { - self.0.load(Ordering::Relaxed) as f32 / (STAGES - 1) as f32 + self.value.load(Ordering::Relaxed) as f32 / (self.lines.len() - 1) as f32 } fn line(&self) -> &'static str { - STAGE_LINES[(self.0.load(Ordering::Relaxed) as usize).min(STAGE_LINES.len() - 1)] + self.lines[(self.value.load(Ordering::Relaxed) as usize).min(self.lines.len() - 1)] } } diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index ee57e9f2b..995ebc8ca 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -1,14 +1,23 @@ //! Resource pack selection bound to the game: the pack screen lists, and a //! full resource reload after a change, while playing. -use super::Game; +use super::{ + Game, PackResources, Resources, UiResources, build_renderer, prepare_renderer_textures, +}; use horizon_client::{ + assets::Assets, + gfx::PreparedTextures, hud::HudAtlas, lang, pack_screen::{self, Compat, PackInfo, Source as PackSource}, packs::{self, Pack, Position}, + streaming::WorkerContext, text::{Style, Text}, }; -use std::path::{Path, PathBuf}; +use std::{ + collections::BTreeSet, + path::{Path, PathBuf}, + sync::Arc, +}; /// Where overlay roots are built (beside options.txt). pub fn cache_dir() -> PathBuf { @@ -94,7 +103,7 @@ pub(super) fn pack_infos(vanilla: &Path) -> Vec { infos } impl Game<'_> { - fn vanilla_root(&self) -> PathBuf { + pub(super) fn vanilla_root(&self) -> PathBuf { if self.ui.vanilla_root.as_os_str().is_empty() { self.options.resources.clone() } else { @@ -134,35 +143,36 @@ impl Game<'_> { self.ui.options.resource_error = Some(e.to_string()); } } - /// Reload from the selected packs and the server's. - pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> { + /// The CPU half of the reload, safe on a worker (`PackReload` runs it): + /// `apply_staged_pack` finishes the GPU half and the swap. + pub(super) fn stage_selected_packs(&mut self) -> horizon_client::Result { let vanilla = self.vanilla_root(); if self.ui.vanilla_root.as_os_str().is_empty() { self.ui.vanilla_root = vanilla.clone(); } - let server = &self.server_packs.active; - let root = startup_root(&vanilla, &self.settings.resource_packs, server)?; - let root = - super::mods::content_root(&root, &self.settings.mods.enabled, &self.options.dev_mods); - self.reload_resources(&root) + stage_pack( + &vanilla, + &self.settings.resource_packs, + &self.server_packs.active, + &self.settings.mods.enabled, + &self.options.dev_mods, + &self.pack.assets, + &self.res, + &self.pack.context, + self.settings.force_unicode, + self.settings.japanese_glyphs, + &super::Progress::new(), + ) } - fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; - atlas.font.uniform = self.settings.force_unicode; - atlas.font.japanese = self.settings.japanese_glyphs; - let gui = super::UiResources { - atlas, - panorama: std::sync::Arc::new(horizon_client::gfx::panorama::Faces::load(root)), - }; - let pack = super::PackResources::load( + /// The render-thread half: the renderer on the new pack's textures, then + /// the swap (`ReloadInstance`'s application listeners). + pub(super) fn apply_staged_pack(&mut self, staged: StagedPack) -> horizon_client::Result<()> { + let StagedPack { root, - self.pack.assets.clone(), - render, - self.res.facts(), - self.pack.context.biomes.clone(), - self.pack.context.light.clone(), - )?; + gui, + pack, + textures, + } = staged; // Keep the working GPU resources, but release its exclusive window surface. if let Some(renderer) = &mut self.renderer { renderer.release_surface(); @@ -170,7 +180,17 @@ impl Game<'_> { let renderer = match self .window .clone() - .map(|window| self.renderer_for(window, &pack, &gui)) + .map(|window| { + build_renderer( + window, + self.options.offscreen, + &pack, + &gui, + self.renderer.as_ref(), + Some(textures), + self.settings.horizon.api, + ) + }) .transpose() { Ok(renderer) => renderer, @@ -186,18 +206,18 @@ impl Game<'_> { } }; // Everything loaded: switch over. - self.waypoint_styles = horizon_client::locator_bar::WaypointStyles::load(root); - self.armor_stand_assets.reload_trims(root); + self.waypoint_styles = horizon_client::locator_bar::WaypointStyles::load(&root); + self.armor_stand_assets.reload_trims(&root); self.random_tick_sections.clear(); self.portals.sections.clear(); - self.options.resources = root.to_path_buf(); + self.options.resources = root.clone(); let context = pack.context.clone(); self.pack = pack; self.gui = gui; // The atlas's sprites moved: the particle engine re-reads every rect // and the packs' sprite sets, or every particle draws a stale region. self.particles - .reload(root, &self.gui.atlas.sprites, &self.gui.atlas.translucent); + .reload(&root, &self.gui.atlas.sprites, &self.gui.atlas.translucent); horizon_client::ui_theme::reset_atlas(); // Villager hats come from the pack's texture metadata (shared data, swapped in place). *self @@ -206,11 +226,11 @@ impl Game<'_> { .villager_hats .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = - horizon_client::mobs::villager_hats::VillagerHats::load(root); - horizon_client::ui::load_metadata(root); - lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); + horizon_client::mobs::villager_hats::VillagerHats::load(&root); + horizon_client::ui::load_metadata(&root); + lang::set(lang::Language::load(&[&root], &lang::code())); self.refresh_remote_language(); - self.audio.reload(root); + self.audio.reload(&root); self.clear_lod(); self.streaming.reload_resources(&mut self.world, context); self.pending_uploads.clear(); @@ -223,4 +243,66 @@ impl Game<'_> { self.ui.chat.rescale(&self.gui.atlas); Ok(()) } + /// `Minecraft.reloadResourcePacks`: the reload staged on the spot, then + /// applied (`PackReload` runs the same two phases across frames). + pub(super) fn reload_selected_packs(&mut self) -> horizon_client::Result<()> { + let staged = self.stage_selected_packs()?; + self.apply_staged_pack(staged) + } +} + +/// The CPU half of `reload_selected_packs` (`PackReload` runs it on a +/// worker; `apply_staged_pack` does the GPU half and the swap): the overlay +/// root, the models and sprites, the menu bundle, the pack's tables and its +/// CPU mip chains. +pub(super) fn stage_pack( + vanilla_root: &Path, + selected: &[String], + server: &[Pack], + mods_enabled: &BTreeSet, + dev_mods: &[PathBuf], + assets: &Arc, + res: &Resources, + context: &WorkerContext, + force_unicode: bool, + japanese: bool, + progress: &super::Progress, +) -> horizon_client::Result { + let root = startup_root(vanilla_root, selected, server)?; + let root = super::mods::content_root(&root, mods_enabled, dev_mods); + progress.set(1); + let render = Arc::new(assets.reload(&root)?); + let mut atlas = HudAtlas::build_over(&root, vanilla_root)?; + atlas.font.uniform = force_unicode; + atlas.font.japanese = japanese; + let gui = UiResources { + atlas, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(&root)), + }; + progress.set(2); + let pack = PackResources::load( + &root, + assets.clone(), + render, + res.facts(), + context.biomes.clone(), + context.light.clone(), + )?; + let textures = prepare_renderer_textures(&pack); + progress.set(3); + Ok(StagedPack { + root, + gui, + pack, + textures, + }) +} + +/// Everything a pack reload builds on the CPU (`apply_staged_pack` finishes +/// it on the render thread). +pub(super) struct StagedPack { + pub root: PathBuf, + pub gui: UiResources, + pub pack: PackResources, + pub textures: PreparedTextures, } diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 58d25de0e..12b73f4f9 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -3,7 +3,7 @@ //! and `DownloadedPackSource` as `Minecraft` drives it): the prompt, the //! server list's setting, downloads into `downloads/`, and a resource reload //! with the server's packs on top of the player's own. -use super::Game; +use super::{Game, Progress}; use horizon_client::{ Result, confirm_screen::Confirm, @@ -82,6 +82,9 @@ pub(super) struct ServerPackState { pub(super) active: Vec, /// The download batches' notifiers, oldest first. notifiers: Vec, + /// A `tick`-asked reload staged on a worker (`LoadingOverlay`): the + /// frame draws its progress until `tick_server_packs` applies it. + pub(super) reload: Option, } /// `DownloadedPackSource.createDownloadNotifier`: one batch's progress in its /// own `SystemToast`. @@ -191,6 +194,21 @@ fn saves() -> PathBuf { std::env::current_dir().unwrap_or_default().join("saves") } +/// `LoadingOverlay`'s stage lines for a pack reload, indexed by `progress`. +const RELOAD_LINES: [&str; 4] = [ + "Preparing resources", + "Loading assets", + "Loading pack tables", + "Applying resources", +]; +/// A pack reload `ServerPacks::tick` asked for: the CPU half runs on a +/// worker while `progress` feeds the loading screen, then the apply lands +/// on the render thread. +pub(super) struct PackReload { + pub(super) progress: Progress, + handle: std::thread::JoinHandle>, +} + impl Game<'_> { /// `ConnectScreen`: the server's setting decides what its packs do /// (`configureForServerControl`); single player's own server takes them @@ -314,6 +332,7 @@ impl Game<'_> { if self.rest_loader.is_some() || self.world_loader.is_some() { return; } + self.drive_pack_reload(); let finished = self .server_packs .queue @@ -328,13 +347,8 @@ impl Game<'_> { if !tick.download.is_empty() { self.start_pack_downloads(tick.download); } - if let Some(mut load) = tick.reload { - while let Some(recovery) = { - let ok = self.reload_server_packs(&load); - self.server_packs.packs.reloaded(ok) - } { - load = recovery; - } + if let Some(load) = tick.reload { + self.start_pack_reload(&load); } } for (id, status) in self.server_packs.packs.take_replies() { @@ -379,24 +393,83 @@ impl Game<'_> { } } /// `DownloadedPackSource.startReload`: the packs on top of the player's - /// own, then `Minecraft.reloadResourcePacks`. False when a pack has no - /// readable `pack.mcmeta` or the reload failed. - fn reload_server_packs(&mut self, load: &[(u128, PathBuf)]) -> bool { - let packs: Option> = load + /// own, staged on a worker (`Minecraft.reloadResourcePacks` under a + /// `LoadingOverlay`); `drive_pack_reload` applies it. A pack with no + /// readable `pack.mcmeta` fails the reload at once, as `onFailure`. + fn start_pack_reload(&mut self, load: &[(u128, PathBuf)]) { + let server: Option> = load .iter() .map(|(id, path)| packs::server_pack(*id, path)) .collect(); - let Some(packs) = packs else { + let Some(server) = server else { log::warn!("Horizon: invalid pack metadata in a server pack, ignoring all"); - return false; + self.finish_pack_reload(false); + return; }; - self.server_packs.active = packs; - match self.reload_selected_packs() { + self.server_packs.active = server.clone(); + let vanilla = self.vanilla_root(); + if self.ui.vanilla_root.as_os_str().is_empty() { + self.ui.vanilla_root = vanilla.clone(); + } + let (selected, mods, dev_mods) = ( + self.settings.resource_packs.clone(), + self.settings.mods.enabled.clone(), + self.options.dev_mods.clone(), + ); + let (assets, res, context) = ( + self.pack.assets.clone(), + self.res.clone(), + self.pack.context.clone(), + ); + let (unicode, japanese) = (self.settings.force_unicode, self.settings.japanese_glyphs); + let progress = Progress::with(&RELOAD_LINES); + let worker = progress.clone(); + let handle = std::thread::Builder::new() + .name("server-pack-reload".into()) + .spawn(move || { + super::packs::stage_pack( + &vanilla, &selected, &server, &mods, &dev_mods, &assets, &res, &context, + unicode, japanese, &worker, + ) + .map_err(|e| e.to_string()) + }); + match handle { + Ok(handle) => self.server_packs.reload = Some(PackReload { progress, handle }), + Err(e) => { + log::error!("Horizon: could not start the pack reload worker: {e}"); + self.finish_pack_reload(false); + } + } + } + /// `PackReloadConfig.Callbacks`: applies the staged reload once its + /// worker is done; on failure the packs active before reload again. + fn drive_pack_reload(&mut self) { + let Some(reload) = &self.server_packs.reload else { + return; + }; + if !reload.handle.is_finished() { + return; + } + let reload = self.server_packs.reload.take().unwrap(); + let staged = reload + .handle + .join() + .unwrap_or_else(|_| Err("the pack reload worker panicked".into())); + let ok = match staged + .and_then(|staged| self.apply_staged_pack(staged).map_err(|e| e.to_string())) + { Ok(()) => true, Err(e) => { log::warn!("Horizon: server resource pack reload failed: {e}"); false } + }; + self.finish_pack_reload(ok); + } + /// `ServerPacks::reloaded` and the recovery reload it can ask for. + fn finish_pack_reload(&mut self, ok: bool) { + if let Some(recovery) = self.server_packs.packs.reloaded(ok) { + self.start_pack_reload(&recovery); } } diff --git a/docs/resource-packs.md b/docs/resource-packs.md index 783c381dd..69eee3393 100644 --- a/docs/resource-packs.md +++ b/docs/resource-packs.md @@ -33,7 +33,7 @@ harness named checks that loader against vanilla). | Overlays per format | `pack.mcmeta` `overlays` | works | `test_resource_pack_parity` (an overlay for 26.3 applied, an older one not) | | Filters | `pack.mcmeta` `filter` | works | `test_resource_pack_parity` (`packs/pattern.rs` regex subset) | | Folder and zip packs, order, built-in packs | `resourcepacks/` | works | `test_resource_pack_parity`, `test_pack_selection_parity` | -| Server resource packs: the prompt, the server list's Server Resource Packs setting, download (250 MiB, SHA-1, `downloads/` keeps 20), applied on top of the player's packs, removed on leaving | the server's `resource_pack_push`/`_pop` | works, no download toasts | `tools/server_pack_e2e.py` (against vanilla's server and Horizon's), unit tests in `server_packs.rs`; `test_server_resource_pack_parity` for Horizon's server | +| Server resource packs: the prompt, the server list's Server Resource Packs setting, download (250 MiB, SHA-1, `downloads/` keeps 20), download toasts, a progress screen while the packs reload, applied on top of the player's packs, removed on leaving | the server's `resource_pack_push`/`_pop` | works | `tools/server_pack_e2e.py` (against vanilla's server and Horizon's), unit tests in `server_packs.rs`; `test_server_resource_pack_parity` for Horizon's server | | Other namespaces | `assets//` | works | `test_resource_pack_parity` | | Block states: variants, multipart, weights, rotations, uvlock | `blockstates/` | works | `test_blockstate_model_parity`, `test_model_choice_parity`, `test_blockstate_transform_parity` | | Block models: parents, elements, rotations, faces, cullface, tint, shade, light emission, ambient occlusion | `models/block/` | works | `test_model_resolution_parity`, `test_model_baking_parity`, `test_section_mesh_parity` | @@ -84,7 +84,6 @@ shaders, the missing pieces are missing vanilla features too, and each vanilla p | Gap | Size | Where | | --- | --- | --- | | Animation `interpolate` | small | fix PR (`gfx.rs` `animate_sprites`) | -| Server pack download toasts (`download.pack.*`) | small | `game/server_packs.rs` | | GUI scaling `width`/`height`, `stretch_inner`, `tile`, `stretch` | small | next fix PR (`ui.rs`) | | Villager hats | small | [#334](https://github.com/ludovic111/horizon/issues/334) | | `blur`/`clamp` from packs | small | [#335](https://github.com/ludovic111/horizon/issues/335) | From 8526305faa2a15aa0b3f737ad5b0c4ea5d0e9bc2 Mon Sep 17 00:00:00 2001 From: Senjin Date: Mon, 26 Oct 2026 18:04:54 +0100 Subject: [PATCH 066/195] HDR: mark only the sun's and moon's discs, not their whole quads The celestial pass wrote alpha 0 over each quad, so HDR output lifted a square of bright daytime sky around the sun. It now draws premultiplied (one, one), which looks the same, and its alpha is how much a texel adds; the blend takes that off the frame's alpha, so only the discs shine. The dim End sky, drawn by the same pass, stays unmarked. fs_celestial keeps its own blend for lightning and additive entities. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity.wgsl | 17 +++++++++++++++-- crates/horizon-client/src/gfx.rs | 13 +++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..93c2a4105 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -208,9 +208,22 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } +fn celestial_color(in: Out) -> vec4 { + return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; +} @fragment fn fs_celestial(in: Out) -> @location(0) vec4 { - let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; - return color; + return celestial_color(in); +} + +// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light, +// premultiplied for an additive (one, one) blend, and as alpha how much of it +// the texel adds, which the blend takes off the frame's alpha. HDR output +// (hdr.wgsl) lifts only where that left it low: the sun's and moon's discs, not +// the dark rest of their quads or the dim End sky. +@fragment fn fs_sky_celestial(in: Out) -> @location(0) vec4 { + let color = celestial_color(in); + let added = color.rgb * color.a; + return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b)))); } // RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 904370c04..c18f2cb6c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1939,22 +1939,23 @@ impl Renderer { multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &entity_shader, - entry_point: Some("fs_celestial"), + entry_point: Some("fs_sky_celestial"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), - // RenderPipelines.CELESTIAL: additive (src alpha, one). The - // alpha goes to 0: HDR output (hdr.wgsl) lets the sun and - // moon shine; nothing else reads the frame's alpha. + // RenderPipelines.CELESTIAL: additive (src alpha, one), with + // the colour premultiplied in fs_sky_celestial. Its alpha is + // how much a texel adds: HDR output (hdr.wgsl) lets the sun's + // and moon's discs shine; nothing else reads the frame's alpha. blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, + src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Zero, - dst_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, }), From e8ae26c27016790f088eb6b4eeb1650ac5dffee5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:09:01 +0100 Subject: [PATCH 067/195] Carry the exploding mob's kind with its blast and anger bees at guests too --- .../examples/probe/mob_ai_probe.rs | 2 +- crates/horizon-client/src/game/beehives.rs | 34 ++++++++++++++++--- crates/horizon-client/src/game/creatures.rs | 9 +++-- crates/horizon-client/src/mobs.rs | 4 ++- crates/horizon-client/src/mobs/hostile.rs | 1 + crates/horizon-client/src/mobs/sulfur_cube.rs | 1 + crates/horizon-client/src/mobs/wither.rs | 1 + 7 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index ecdf02901..2f3cc70da 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -580,7 +580,7 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { match e { MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, // ServerExplosion.hurtEntities: within twice the radius every hit does damage. - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, _) => { let d = Vec3::new(at[0], at[1], at[2]) .distance_squared(p.position) .sqrt(); diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index 258610f5e..1335377c5 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -195,7 +195,8 @@ impl Game<'_> { self.anger_nearby_bees(at); } /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) - /// without a target go for a player in the same box. + /// without a target go for a random player in the same box, the window's + /// own or a guest (`None` is the window's player). pub(super) fn anger_nearby_bees(&mut self, at: [i32; 3]) { let min = Vec3::new( f64::from(at[0]) - 8.0, @@ -203,10 +204,24 @@ impl Game<'_> { f64::from(at[2]) - 8.0, ); let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0)); - if !self + let mut players: Vec> = Vec::new(); + if self .player_view() .is_some_and(|p| p.bounds.intersects(area)) { + players.push(None); + } + if let Some(host) = self.lan.as_ref() { + players.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .filter(|g| super::lan_mobs::guest_bounds(g).intersects(area)) + .map(|g| Some(g.conn)), + ); + } + if players.is_empty() { return; } let mut bees: Vec = (0..self.mobs.len()) @@ -219,9 +234,20 @@ impl Game<'_> { .collect(); bees.retain(|&i| self.mobs[i].ai.target.is_none()); for i in bees { - // Util.getRandom over the one player. - let _ = self.world.random.next_int_bound(1); + // Util.getRandom over the players. + let pick = self + .world + .random + .next_int_bound(players.len() as i32) + .unwrap_or(0) as usize; self.mobs[i].ai.target = Some(Who::Player); + // The player a mob sees is its guest binding, else the window's. + if let Some(host) = self.lan.as_mut() { + match players[pick] { + Some(conn) => host.mob_players.insert(self.mobs[i].id, conn), + None => host.mob_players.remove(&self.mobs[i].id), + }; + } } } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 6e6610dcc..fd0f5f5de 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -901,7 +901,7 @@ impl Game<'_> { owner, } => self.add_fangs(at, yaw, delay, owner), MobEvent::Shoot(..) => {} - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, species) => { // The exploding mob causes the damage (Creeper.explodeCreeper). let source_mob = self .mobs @@ -916,10 +916,9 @@ impl Game<'_> { } self.combat.explosion_source = source_mob; // Only a creeper or a wither empties the hives it blows up. - let empties_hives = source_mob - .and_then(|id| self.mobs.iter().find(|m| m.id == id)) - .is_some_and(|m| matches!(m.species(), Species::Creeper | Species::Wither)); - let result = if empties_hives { + // The creeper is already gone from the list, so the event + // carries its kind. + let result = if matches!(species, Species::Creeper | Species::Wither) { self.with_hive_emptying_blast(|g| g.explode(at, radius)) } else { self.explode(at, radius) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1b5dddbe7..a97d3514e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -965,7 +965,9 @@ pub enum MobEvent { owner: u32, }, Shoot([f64; 3], [f64; 3]), - Explode([f64; 3], f32), + /// The centre, the radius and the kind of the mob blowing up (it may be + /// gone from the list by the time the blast is handled). + Explode([f64; 3], f32, Species), /// Melee or ranged damage to another mob. AttackMob { target: u32, diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 0d3feaa6c..8ad69b030 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -180,6 +180,7 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y, m.position.z], radius, + m.species(), )); m.removed = true; } diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index 00b846b86..2af0d7362 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -370,6 +370,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y + 0.0625, m.position.z], power, + m.species(), )); m.removed = true; return; diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6702686c5..7f1fc0db2 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -221,6 +221,7 @@ pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec Date: Mon, 26 Oct 2026 17:11:51 +0000 Subject: [PATCH 068/195] Fix recipe book settings persistence on the server Send open/filter changes to the authoritative player's recipe book and cover packet settings plus save/reopen in both single-player modes. Co-Authored-By: OpenCode GPT-6.1 Sol --- .../examples/probe/recipe_book_fixture.rs | 23 ++++++- crates/horizon-client/src/game/agent.rs | 3 + crates/horizon-client/src/game/recipe_book.rs | 18 +++++ crates/horizon-client/src/lan/hub.rs | 10 +++ crates/horizon-client/tests/lan_bot.rs | 69 +++++++++++++++++++ crates/horizon-protocol/src/packets/play.rs | 1 + .../horizon-protocol/src/packets/recipes.rs | 27 ++++++++ .../parity/VanillaRecipeBookOracle.java | 21 +++++- tools/lan_e2e.py | 59 ++++++++++++++++ tools/test_recipe_book_parity.py | 11 ++- 10 files changed, 236 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/examples/probe/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs index ce2afe624..2dda3b109 100644 --- a/crates/horizon-client/examples/probe/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -5,6 +5,10 @@ //! //! usage: recipe_book_fixture RESOURCES CASES OUTPUT use horizon_client::recipe_book::{BookType, RecipeIndex, Settings}; +use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::recipes::RecipeBookChangeSettings, +}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::BTreeSet, fs, path::Path}; @@ -93,8 +97,23 @@ pub fn main() -> horizon_client::Result<()> { _ => BookType::Smoker, } .index(); - book.open[i] = op["open"].as_bool().unwrap_or(false); - book.filtering[i] = op["filtering"].as_bool().unwrap_or(false); + let packet = RecipeBookChangeSettings { + book_type: i as i32, + open: op["open"].as_bool().unwrap_or(false), + filtering: op["filtering"].as_bool().unwrap_or(false), + }; + let mut wire = Writer::new(); + RecipeBookChangeSettings::write(&packet, &mut wire); + extra = format!( + " packet={}", + wire.data + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ); + let decoded = RecipeBookChangeSettings::read(&mut Reader::new(&wire.data))?; + book.open[decoded.book_type as usize] = decoded.open; + book.filtering[decoded.book_type as usize] = decoded.filtering; } "save" => { let tag = book.write(); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0d2d218ab..1433e92e8 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -686,9 +686,12 @@ impl Game<'_> { // the recipe buttons of the page, page arrows, filter and tabs. let book = self.recipe_book_targets(); if !book.is_empty() { + let (open, filtering) = self.recipe_book_flags().unwrap_or_default(); v["recipe_book"] = json!({ "targets": book.iter().map(|t| t.rect).collect::>(), "known": self.recipe_book_known(), + "open": open, + "filtering": filtering, }); } v["slot_ids"] = json!( diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 96e12d79b..bf0d1c370 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -590,6 +590,7 @@ impl Game<'_> { if inside(cursor, bx, by, 20.0, 18.0) { let open = !self.book_open(book_type); self.level.recipe_book.open[book_type.index()] = open; + self.send_book_settings(book_type); if !open { self.recipe_ui.overlay = None; } @@ -675,6 +676,7 @@ impl Game<'_> { if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; + self.send_book_settings(book_type); self.recipe_ui.page = 0; self.audio .play("minecraft:ui.button.click", None, 0.25, 1.0); @@ -695,6 +697,22 @@ impl Game<'_> { } false } + /// `RecipeBookComponent.sendUpdateSettings`: the server owns the saved book. + fn send_book_settings(&self, book_type: BookType) { + self.send( + horizon_protocol::packets::play::Serverbound::RecipeBookChangeSettings( + horizon_protocol::packets::recipes::RecipeBookChangeSettings { + book_type: book_type.index() as i32, + open: self.book_open(book_type), + filtering: self.book_filtering(book_type), + }, + ), + ); + } + pub(super) fn recipe_book_flags(&self) -> Option<(bool, bool)> { + let book = self.active_book()?; + Some((self.book_open(book), self.book_filtering(book))) + } /// How many displays the client's book holds. pub(super) fn recipe_book_known(&self) -> usize { self.recipe_ui.client.displays().len() diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b462536b9..dc0dbe89d 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1930,6 +1930,7 @@ impl Hub { | S::PlayerLoaded(_) | S::ChunkBatchReceived(_) | S::ClientInformation(_) + | S::RecipeBookChangeSettings(_) | S::ClientTickEnd(_) | S::KeepAlive(_) => false, S::MovePlayerPos(p) => self.moved_far(i, [p.x, p.y, p.z]), @@ -1996,6 +1997,15 @@ impl Hub { g.max_unacknowledged = 10; } S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, + // ServerGamePacketListenerImpl.handleRecipeBookChangeSettingsPacket. + S::RecipeBookChangeSettings(p) => { + if let Some(book) = crate::recipe_book::BookType::ALL.get(p.book_type as usize) + { + let settings = &mut self.guests[i].recipe_book; + settings.open[book.index()] = p.open; + settings.filtering[book.index()] = p.filtering; + } + } S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 34e8265a1..81ec192f5 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -278,6 +278,75 @@ fn run( handle.join().unwrap().unwrap() } +#[test] +fn recipe_settings_packets_update_only_the_players_book_and_survive_save() { + let Some(resources) = resources() else { + return; + }; + let mut s = server(&resources); + let port = s.hub.lan.port; + let _bot = run(&mut s, move || connect(port, "RecipeSettings", true)); + let deadline = Instant::now() + Duration::from_secs(5); + while s.hub.guests.is_empty() { + s.tick(&[]); + assert!(Instant::now() < deadline, "guest did not join"); + thread::yield_now(); + } + for book in 0..4 { + for flags in 0..4 { + let open = flags & 1 != 0; + let filtering = flags & 2 != 0; + let before = s.hub.guests[0].recipe_book.clone(); + // Vanilla's wire payload: RecipeBookType VarInt, open, filtering. + let packet = S::decode( + horizon_protocol::ids::play::serverbound::RECIPE_BOOK_CHANGE_SETTINGS, + &[book, u8::from(open), u8::from(filtering)], + ) + .unwrap(); + s.hub.guests[0].inbox.push_back(packet); + s.tick(&[]); + let settings = &s.hub.guests[0].recipe_book; + for i in 0..4 { + assert_eq!( + settings.open[i], + if i == usize::from(book) { + open + } else { + before.open[i] + } + ); + assert_eq!( + settings.filtering[i], + if i == usize::from(book) { + filtering + } else { + before.filtering[i] + } + ); + } + let mut saved = horizon_client::save::Level::default(); + horizon_client::lan::playerdata::store(&s.hub.guests[0], &mut saved); + let mut reopened = horizon_client::save::Level::default(); + reopened.read_player(&saved.player_tag()); + assert_eq!(reopened.recipe_book.open, settings.open); + assert_eq!(reopened.recipe_book.filtering, settings.filtering); + } + } + for book_type in [-1, 4] { + let mut wire = horizon_protocol::buf::Writer::new(); + wire.varint(book_type); + wire.bool(true); + wire.bool(true); + assert!( + S::decode( + horizon_protocol::ids::play::serverbound::RECIPE_BOOK_CHANGE_SETTINGS, + &wire.data, + ) + .is_err() + ); + } +} + #[test] fn sprint_commands_survive_keyboard_input_changes() { let Some(resources) = resources() else { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 67373cf4b..1c20ed36c 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2219,6 +2219,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ChatCommandSigned(ChatCommandSigned) = CHAT_COMMAND_SIGNED, ChatSessionUpdate(ChatSessionUpdate) = CHAT_SESSION_UPDATE, PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE, + RecipeBookChangeSettings(super::recipes::RecipeBookChangeSettings) = RECIPE_BOOK_CHANGE_SETTINGS, ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, ClientCommand(ClientCommand) = CLIENT_COMMAND, ClientInformation(ClientInformation) = CLIENT_INFORMATION, diff --git a/crates/horizon-protocol/src/packets/recipes.rs b/crates/horizon-protocol/src/packets/recipes.rs index c289b8943..dcbe5ffa0 100644 --- a/crates/horizon-protocol/src/packets/recipes.rs +++ b/crates/horizon-protocol/src/packets/recipes.rs @@ -500,6 +500,33 @@ impl Codec for RecipeBookSettings { } } +/// ServerboundRecipeBookChangeSettingsPacket: the active book's open and +/// filtering flags, with its `RecipeBookType` ordinal as a VarInt. +#[derive(Clone, Debug, PartialEq)] +pub struct RecipeBookChangeSettings { + pub book_type: i32, + pub open: bool, + pub filtering: bool, +} +impl Codec for RecipeBookChangeSettings { + fn read(r: &mut Reader) -> Result { + let book_type = r.varint()?; + if !(0..4).contains(&book_type) { + return Err(crate::Error::new("invalid recipe book type")); + } + Ok(Self { + book_type, + open: r.bool()?, + filtering: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.book_type); + w.bool(v.open); + w.bool(v.filtering); + } +} + /// ClientboundPlaceGhostRecipePacket: the recipe to show faded in a menu /// whose items were missing. #[derive(Clone, Debug, PartialEq)] diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java index 60640010b..2cf9d7d48 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookOracle.java @@ -1,12 +1,15 @@ package dev.horizonlab.parity; import com.google.gson.*; +import io.netty.buffer.Unpooled; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import net.minecraft.core.registries.Registries; import net.minecraft.nbt.*; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.game.ServerboundRecipeBookChangeSettingsPacket; import net.minecraft.resources.Identifier; import net.minecraft.resources.ResourceKey; import net.minecraft.server.level.ServerPlayer; @@ -102,8 +105,22 @@ public final class VanillaRecipeBookOracle { count = kind.equals("give") ? book.addRecipes(holders, player) : book.removeRecipes(holders, player); } case "seen" -> book.removeHighlight(key(op.get("id").getAsString())); - case "set" -> book.setBookSetting(RecipeBookType.valueOf(op.get("type").getAsString()), - op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean()); + case "set" -> { + var packet = new ServerboundRecipeBookChangeSettingsPacket( + RecipeBookType.valueOf(op.get("type").getAsString()), + op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean()); + var buf = new FriendlyByteBuf(Unpooled.buffer()); + try { + ServerboundRecipeBookChangeSettingsPacket.STREAM_CODEC.encode(buf, packet); + byte[] wire = new byte[buf.readableBytes()]; + buf.getBytes(buf.readerIndex(), wire); + extra = " packet=" + HexFormat.of().formatHex(wire); + var decoded = ServerboundRecipeBookChangeSettingsPacket.STREAM_CODEC.decode(buf); + book.setBookSetting(decoded.getBookType(), decoded.isOpen(), decoded.isFiltering()); + } finally { + buf.release(); + } + } case "save" -> { saved = (CompoundTag) ServerRecipeBook.Packed.CODEC.encodeStart(NbtOps.INSTANCE, book.pack()).getOrThrow(); extra = compound(saved); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0ec7218d8..1866a6ee3 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -5877,6 +5877,65 @@ CHECKS += ['recipe_removal'] CHECK_FNS.update(recipe_removal=check_recipe_removal) +def check_recipe_settings(host, guest, out): + """RecipeBookComponent sends both settings to the server; each player's + own book keeps them when the authoritative world saves and reopens (#2290).""" + def inventory(game): + back_to_game(game) + game.raw('key', 'e', 'tap') + game.wait(5) + return game('screen')['recipe_book'] + + def flags(book): + return {'open': book['open'], 'filtering': book['filtering']} + + def set_flags(game, opened, filtering): + book = inventory(game) + if not book['open']: + game.raw('click-at', *centre(book['targets'][0])) + game.wait(5) + book = game('screen')['recipe_book'] + if book['filtering'] != filtering: + target = next(t for t in book['targets'] if t[2:] == [26.0, 16.0]) + game.raw('click-at', *centre(target)) + game.wait(5) + if not opened: + book = game('screen')['recipe_book'] + game.raw('click-at', *centre(book['targets'][0])) + game.wait(5) + actual = flags(game('screen')['recipe_book']) + assert actual == {'open': opened, 'filtering': filtering}, f'{game.name}: {actual}' + game.shot(out, 'recipe-settings-before') + back_to_game(game) + return actual + + # Deliberately different settings ensure neither player's book overwrites the other's. + before = {host.name: set_flags(host, True, True), + guest.name: set_flags(guest, False, True)} + host.wait(20) + guest.raw('disconnect') + host.raw('pause') + host.raw('click-button', 'Save and Quit to Title') + host.raw('wait-for', 'screen', 'title', '--timeout', 120) + host.raw('open', 'Lan') + host('wait_ready', seconds=400) + port = host.raw('lan', 'open', 0, 'commands')['port'] + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + after = {} + for game in (host, guest): + after[game.name] = flags(inventory(game)) + game.shot(out, 'recipe-settings-reopened') + back_to_game(game) + assert after == before, f'saved recipe settings reset: before={before}, after={after}' + return {'before': before, 'reopened': after} + + +CHECKS += ['recipe_settings'] +CHECK_FNS.update(recipe_settings=check_recipe_settings) + + def check_shulker_bullets(host, guest, out): """ShulkerAttackGoal's bullets reach ClientPacketListener.handleAddEntity, then the existing projectile renderer and interpolation, with distinct ids from the server's entity counter.""" diff --git a/tools/test_recipe_book_parity.py b/tools/test_recipe_book_parity.py index c25f180ac..291adeb86 100644 --- a/tools/test_recipe_book_parity.py +++ b/tools/test_recipe_book_parity.py @@ -5,8 +5,9 @@ Each case runs a sequence of operations on a fresh book: awarding recipes (advancement rewards, /recipe give, crafting; special recipes are never learnt, and the count is the displays added), taking them back, the client having seen a highlighted recipe, the open and filter settings of the four -book types, and saving and loading the player's recipeBook compound (with -unknown ids dropped, and a compound missing a list ignored). The Java oracle +book types (through the serverbound settings packet's codec), and saving and +loading the player's recipeBook compound (with unknown ids dropped, and a +compound missing a list ignored). The Java oracle (VanillaRecipeBookOracle) drives ServerRecipeBook and its codec; examples/probe/recipe_book_fixture drives horizon_client::recipe_book. After each operation the count, the known and highlighted recipes, the settings and @@ -35,6 +36,12 @@ def main(): ids = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')) rng = random.Random(args.seed) cases = [] + # Every book and flag combination crosses the wire, then survives a save/load. + for book_type in TYPES: + for opened in (False, True): + for filtering in (False, True): + cases.append({'ops': [{'op': 'set', 'type': book_type, 'open': opened, + 'filtering': filtering}, {'op': 'save'}, {'op': 'load'}]}) for _ in range(args.cases): ops, known = [], set() for _ in range(rng.randrange(1, 12)): From 7a3a19697a75e9f7bcf42da70d9f665b7937239c Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 18:13:22 +0100 Subject: [PATCH 069/195] Resolve dynamic head profiles, and re-upload evicted skins Player heads whose profile carries only a name or only a UUID (ResolvableProfile.Dynamic) resolved to nothing, so heads some servers send that way kept the default skin. Adds skins::Resolver (ProfileResolver.Cached: profiles/getByName then session/getProfileById through the services discovery document, on background threads) used by placed heads, head items and mannequins; the profile-derived DefaultPlayerSkin stands in until the download lands, with the name's offline UUID keying it for name-only profiles. A skin evicted from the atlas's 128 slots could never return: the decoded image was dropped and show_skin simply failed. The downloader now keeps the images (and the disk cache backs them), and again queues the upload again where the tab list, level players, mannequins and heads notice the missing sprite. profile_tag keeps id so id-only and name+id profiles survive into the item data JSON, and the player-head item fallback matches vanilla's slim/steve (was wide/steve). Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/auth.rs | 2 +- .../horizon-client/src/block_entity_render.rs | 9 +- crates/horizon-client/src/containers.rs | 16 +- crates/horizon-client/src/game.rs | 4 + .../src/game/block_entity_anims.rs | 31 +- crates/horizon-client/src/game/item_draw.rs | 18 +- crates/horizon-client/src/game/remote.rs | 41 +- .../horizon-client/src/item_render/special.rs | 2 +- crates/horizon-client/src/item_sync.rs | 11 + crates/horizon-client/src/skins.rs | 512 +++++++++++++++++- 10 files changed, 601 insertions(+), 45 deletions(-) diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index b899ea5d5..a86992735 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -179,7 +179,7 @@ fn agent() -> ureq::Agent { } /// The discovery document, fetched once per game (a failure is retried next time). -fn discovery() -> Result, JoinError> { +pub(crate) fn discovery() -> Result, JoinError> { static CACHE: Mutex>> = Mutex::new(None); if let Some(d) = CACHE.lock().unwrap().clone() { return Ok(d); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 28a876d80..a6f7b1991 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -734,7 +734,7 @@ pub struct Scene<'a> { /// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer` /// profile → skin): a downloaded `skins/` slot or the profile's /// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve). - pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>, + pub skull: &'a dyn Fn([i32; 3]) -> Option, /// Font glyph cell (none for blank glyphs such as the space) and advance. pub glyph: &'a dyn Fn(char) -> (Option, f32), } @@ -1286,11 +1286,12 @@ impl BlockEntityRenderer { }; // SkullBlockRenderer.getRenderType: the profile's skin when it // resolves, `SKIN_BY_TYPE` (steve) otherwise. - let texture = if *kind == SkullType::Player { - (scene.skull)(pos).unwrap_or(texture) + let skin = if *kind == SkullType::Player { + (scene.skull)(pos) } else { - texture + None }; + let texture = skin.as_deref().unwrap_or(texture); let (Some(model), Some(paint)) = (self.models.get(model), paint(texture, 0xFFFFFF, packed)) else { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6aba0970e..e93626584 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -187,6 +187,9 @@ impl Skull { #[derive(Clone, Debug)] pub struct SkullSkin { pub download: Option<(String, String)>, + /// `ResolvableProfile.nameOrId` when the profile is `Dynamic` (a name or + /// an id only): the key `skins::Resolver` resolves it by. + pub dynamic: Option, pub fallback: &'static str, } impl SkullSkin { @@ -195,10 +198,21 @@ impl SkullSkin { let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?); Some((url, location)) }); + // A `Dynamic` profile (a name or id only) resolves through the + // services when the skull is drawn. + let dynamic = crate::skins::dynamic_nbt(profile); // DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id. let fallback = crate::skins::profile_uuid_nbt(profile) + .or_else(|| { + crate::skins::nbt_text(profile.get("name")) + .map(|name| horizon_protocol::crypto::offline_uuid(&name)) + }) .map_or("entity/player/slim/steve", crate::tab_list::default_skin); - Self { download, fallback } + Self { + download, + dynamic, + fallback, + } } } /// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 755a00f6f..734a06df5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1471,6 +1471,9 @@ struct Game<'a> { /// Player skin downloads, and which skin each atlas skin slot holds /// (least recently shown first). skin_downloads: RefCell, + /// `ProfileResolver.Cached`: `Dynamic` profiles (name- or id-only heads + /// and mannequins) resolve through the services in the background. + skin_profiles: RefCell, skin_slots: Vec<(String, usize)>, /// Atlas trim slots in use: (sprite name, slot), least recently drawn first. trim_slots: Vec<(String, usize)>, @@ -12411,6 +12414,7 @@ impl<'a> Game<'a> { .unwrap_or_default() .join("assets/skins"), )), + skin_profiles: RefCell::new(horizon_client::skins::Resolver::new()), skin_slots: Vec::new(), trim_slots: Vec::new(), cart_models: prepared.cart_models, diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 3d452596e..d384238cc 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -474,21 +474,38 @@ impl Game<'_> { /// the player head at `pos`. The skin download is started here; while it /// is in flight (or when it cannot be got) the profile's default skin /// stands in. A head with no profile answers None: `SKIN_BY_TYPE`. - pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> { + pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option { let Some(BlockEntity::Skull(skull)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) else { return None; }; let skin = skull.skin.as_ref()?; - if let Some((url, location)) = &skin.download { - self.skin_downloads - .borrow_mut() - .state(skins::Kind::Skin, url); - if self.gui.atlas.sprites.contains_key(location) { + // The texture a packed or resolved `textures` property fetches: the + // download of a static profile, or the one the services answer for a + // `Dynamic` (name- or id-only) profile. + let download = skin.download.clone().or_else(|| { + let key = skin.dynamic.as_ref()?; + let skins::Resolve::Done(Some(profile)) = self.skin_profiles.borrow_mut().state(key) + else { + return None; + }; + let (value, signature) = profile.textures()?; + let url = skins::unpack(&value, signature, &skins::TEXTURE_URIS).skin?; + let location = skins::skin_location(&skins::texture_hash(&url)?); + Some((url, location)) + }); + if let Some((url, location)) = download { + let mut downloads = self.skin_downloads.borrow_mut(); + if self.gui.atlas.sprites.contains_key(&location) { + let _ = downloads.state(skins::Kind::Skin, &url); return Some(location); } + // Its slot was evicted: offer the image again. + if downloads.state(skins::Kind::Skin, &url) == skins::Download::Ready { + downloads.again(&location); + } } - Some(skin.fallback) + Some(skin.fallback.to_owned()) } } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 1d79f077d..7bf60e3c0 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -129,6 +129,7 @@ pub(super) struct Host<'a> { banners: &'a horizon_client::banner::Banners, sprites: &'a HashMap, skins: &'a RefCell, + profiles: &'a RefCell, } impl SpecialHost for Host<'_> { fn banner_texture(&self, pattern: &str) -> Option { @@ -144,14 +145,14 @@ impl SpecialHost for Host<'_> { fn player_skin(&self, profile: &Value) -> Option { // SkullBlockRenderer.getPlayerSkin: SkinManager.getInsecureSkinInformation // accepts a texture property without a signature, unlike the tab list. - let url = horizon_client::skins::profile_skin_url(profile)?; - let location = - horizon_client::skins::skin_location(&horizon_client::skins::texture_hash(&url)?); - let _ = self - .skins - .borrow_mut() - .state(horizon_client::skins::Kind::Skin, &url); - self.sprites.contains_key(&location).then_some(location) + // A `Dynamic` profile (a name or id only) resolves through the + // services (`PlayerSkinRenderCache.getOrDefault`). + Some(horizon_client::skins::head_skin( + profile, + &mut self.profiles.borrow_mut(), + &mut self.skins.borrow_mut(), + |location| self.sprites.contains_key(location), + )) } } @@ -194,6 +195,7 @@ impl Game<'_> { banners: &self.res.stations().banners, sprites: &self.gui.atlas.sprites, skins: &self.skin_downloads, + profiles: &self.skin_profiles, } } /// The client level as item models read it. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3ef87c201..3628b9773 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2778,7 +2778,7 @@ impl Game<'_> { resolved.push((uuid, skin)); } } - resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.show_skin(skin)); + resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.again_skin(skin)); let Some((level, skins, own)) = self.remote.as_mut().map(|r| { r.skins = resolved.into_iter().collect(); ( @@ -2817,11 +2817,9 @@ impl Game<'_> { .iter() .filter(|m| &*m.kind.id == "minecraft:mannequin" && m.profile.is_some()) .map(|m| { - let t = m - .profile - .as_ref() - .and_then(|p| p.properties.iter().find(|p| p.name == "textures")); - let textures = t.map_or_else(Default::default, |t| { + let profile = m.profile.as_ref(); + let t = profile.and_then(|p| p.properties.iter().find(|p| p.name == "textures")); + let textures = if let Some(t) = t { let signature = if t.signature.is_some() { horizon_client::skins::Signature::Signed } else { @@ -2832,7 +2830,30 @@ impl Game<'_> { signature, &horizon_client::skins::TEXTURE_URIS, ) - }); + } else { + // `ResolvableProfile.resolveProfile`: no `textures` and + // only a name or an id resolves through the services. + let key = profile.and_then(|p| match (&p.name, p.uuid) { + (Some(name), None) => { + Some(horizon_client::skins::NameOrId::Name(name.clone())) + } + (None, Some(id)) => Some(horizon_client::skins::NameOrId::Id(id)), + _ => None, + }); + key.and_then(|key| match self.skin_profiles.borrow_mut().state(&key) { + horizon_client::skins::Resolve::Done(Some(profile)) => { + profile.textures().map(|(value, signature)| { + horizon_client::skins::unpack( + &value, + signature, + &horizon_client::skins::TEXTURE_URIS, + ) + }) + } + _ => None, + }) + .unwrap_or_default() + }; (m.id, textures) }) .collect(); @@ -2847,7 +2868,7 @@ impl Game<'_> { resolved.push((id, skin)); } for (id, skin) in resolved { - let skin = skin.filter(|s| !s.starts_with("skins/") || self.show_skin(s)); + let skin = skin.filter(|s| !s.starts_with("skins/") || self.again_skin(s)); if let Some(mob) = self .mobs .iter_mut() @@ -2897,6 +2918,10 @@ impl Game<'_> { self.skin_slots.push(e); true } + /// `show_skin`, or — its slot evicted — the image queued for upload again. + fn again_skin(&mut self, location: &str) -> bool { + self.show_skin(location) || self.skin_downloads.borrow_mut().again(location) + } /// ChatType decoration: `chat.translation_key` with sender/content parameters. /// ChatType.Bound.decorate: the chat type's translation, with the /// sender, the target and the message as its parameters, in its style. diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index d42378db1..9e69e9d44 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -498,7 +498,7 @@ pub(super) fn submit( let skin = (!argument.is_null()) .then(|| host.player_skin(argument)) .flatten() - .unwrap_or_else(|| "entity/player/wide/steve".to_owned()); + .unwrap_or_else(|| "entity/player/slim/steve".to_owned()); part("player", &none, &skin, white, Foil::None); } SpecialKind::Trident => { diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index fc35e15e7..01d90246f 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -229,6 +229,17 @@ fn profile_tag(p: &Profile) -> Tag { if let Some(name) = &p.name { entries.push(("name", Tag::String(name.as_str().into()))); } + if let Some(id) = p.id { + entries.push(( + "id", + Tag::IntArray(vec![ + (id >> 96) as i32, + (id >> 64) as i32, + (id >> 32) as i32, + id as i32, + ]), + )); + } entries.push(("properties", Tag::List(properties))); Tag::compound(entries) } diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index ee6851e00..239e1c3ac 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -116,20 +116,9 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture /// heads and mannequins read their profile this way, and `SkinManager` lets /// those textures be unsigned (`getInsecureSkinInformation`). pub fn profile_skin_url(profile: &serde_json::Value) -> Option { - let value = profile - .get("properties")? - .as_array()? - .iter() - .find_map(|p| { - if p.get("name")?.as_str()? == "textures" { - p.get("value")?.as_str() - } else { - None - } - })?; - unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin + let (value, signature) = parse_profile(profile).textures?; + unpack(&value, signature, &TEXTURE_URIS).skin } - /// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`): /// the same `properties` list, held as a compound. A name-only profile (a /// string tag) has no properties and no skin URL. @@ -164,13 +153,329 @@ pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option { } } -fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { +pub(crate) fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { match tag { Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()), _ => None, } } +/// `Either`: the key a `Dynamic` `ResolvableProfile` resolves +/// by (`ResolvableProfile.nameOrId`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NameOrId { + Name(String), + Id(u128), +} + +/// `GameProfile` as `fetchProfile` returns it: the account's id, name and +/// property map (its `textures` property is the skin). +#[derive(Clone, Debug)] +pub struct ResolvedProfile { + pub id: u128, + pub name: String, + /// `(name, value, signature)` properties. + pub properties: Vec<(String, String, Option)>, +} +impl ResolvedProfile { + /// `SessionService.getPackedTextures`: the `textures` property. + pub fn textures(&self) -> Option<(String, Signature)> { + self.properties + .iter() + .find(|(n, _, _)| n == "textures") + .map(|(_, v, s)| { + ( + v.clone(), + if s.is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + ) + }) + } +} + +/// Where a `Dynamic` profile's resolution stands (`resolveProfile`'s future). +#[derive(Clone, Debug)] +pub enum Resolve { + Pending, + /// The services' answer: `None` for no profile or no answer, which the + /// cache holds like any result (`Optional.empty`). + Done(Option), +} + +/// `ProfileResolver.Cached`: resolves a `Dynamic` profile through the +/// services — `profileCacheByName` asks `profiles`/`getByName` for the id, +/// `profileCacheById` asks `session`/`getProfileById` for the profile — +/// at most 256 entries kept 10 minutes after their last use, fetched on +/// background threads. +pub struct Resolver { + entries: std::collections::HashMap, + done: std::sync::mpsc::Receiver<(NameOrId, Option)>, + send: std::sync::mpsc::Sender<(NameOrId, Option)>, + last_sweep: std::time::Instant, +} +struct Entry { + touched: std::time::Instant, + /// `None` while the fetch is in flight. + resolved: Option>, +} +/// `ProfileResolver.Cached`'s cache bounds. +const MAX_PROFILES: usize = 256; +const PROFILE_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60); + +/// `StringUtil.isValidPlayerName` (the check `fetchByName` makes first). +fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// `fetchByNameOrId`: `getByName` answers `{id, name}`; `getProfileById` +/// (`fetchProfile(id, requireSecure)`) answers `{id, name, properties}` — +/// asked `unsigned=false` so the `textures` property is signed. +fn resolve_profile(key: &NameOrId, doc: &serde_json::Value) -> Option { + let id = match key { + NameOrId::Id(id) => *id, + NameOrId::Name(name) => { + let url = crate::auth::endpoint(doc, "profiles", "getByName")? + .replace("{name}", &name.to_lowercase()); + let body = http_get(&url)?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + crate::auth::parse_uuid(v.get("id")?.as_str()?)? + } + }; + let url = crate::auth::endpoint(doc, "session", "getProfileById")? + .replace("{profileId}", &format!("{id:032x}")); + let separator = if url.contains('?') { '&' } else { '?' }; + let body = http_get(&format!("{url}{separator}unsigned=false"))?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + Some(ResolvedProfile { + id: crate::auth::parse_uuid(v.get("id")?.as_str()?)?, + name: v.get("name")?.as_str()?.to_owned(), + properties: v + .get("properties")? + .as_array()? + .iter() + .map(|p| { + Some(( + p.get("name")?.as_str()?.to_owned(), + p.get("value")?.as_str()?.to_owned(), + p.get("signature") + .and_then(|s| s.as_str()) + .map(str::to_owned), + )) + }) + .collect::>>()?, + }) +} + +impl Default for Resolver { + fn default() -> Self { + Self::new() + } +} +impl Resolver { + pub fn new() -> Self { + let (send, done) = std::sync::mpsc::channel(); + Self { + entries: Default::default(), + done, + send, + last_sweep: std::time::Instant::now(), + } + } + /// `CacheBuilder.expireAfterAccess` with `maximumSize`. + fn sweep(&mut self) { + if self.last_sweep.elapsed() < std::time::Duration::from_secs(30) { + return; + } + self.last_sweep = std::time::Instant::now(); + self.entries + .retain(|_, e| e.touched.elapsed() < PROFILE_TTL); + while self.entries.len() > MAX_PROFILES + && let Some(oldest) = self + .entries + .iter() + .min_by_key(|(_, e)| e.touched) + .map(|(k, _)| k.clone()) + { + self.entries.remove(&oldest); + } + } + /// How the resolution of `key` stands, starting it the first time. + pub fn state(&mut self, key: &NameOrId) -> Resolve { + while let Ok((key, resolved)) = self.done.try_recv() { + self.entries.insert( + key, + Entry { + touched: std::time::Instant::now(), + resolved: Some(resolved), + }, + ); + } + self.sweep(); + if let Some(entry) = self.entries.get_mut(key) { + entry.touched = std::time::Instant::now(); + return match &entry.resolved { + Some(resolved) => Resolve::Done(resolved.clone()), + None => Resolve::Pending, + }; + } + // `fetchByName` refuses an invalid name without a fetch; like every + // other empty answer that is the cached result. + let resolved = matches!(key, NameOrId::Name(name) if !valid_player_name(name)); + self.entries.insert( + key.clone(), + Entry { + touched: std::time::Instant::now(), + resolved: resolved.then_some(None), + }, + ); + if resolved { + return Resolve::Done(None); + } + let (key, send) = (key.clone(), self.send.clone()); + std::thread::spawn(move || { + let resolved = crate::auth::discovery() + .ok() + .and_then(|doc| resolve_profile(&key, &doc)); + let _ = send.send((key, resolved)); + }); + Resolve::Pending + } +} + +/// `ResolvableProfile` (an item's `minecraft:profile` component, a skull's +/// `profile` tag): the `textures` property it carries, the key a `Dynamic` +/// profile resolves by, and `partialProfile.id` — the fallback skin's key. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ProfileInfo { + /// `GameProfile.id` (`DefaultPlayerSkin.get`). + pub id: u128, + /// The `textures` property's value and signature state, when present. + pub textures: Option<(String, Signature)>, + /// `Dynamic` profiles resolve by name or id. + pub dynamic: Option, +} + +/// A profile's `id`: `UUIDUtil.CODEC` (an int array of four, or a UUID +/// string). +fn profile_id(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Array(a) => { + let ints: Option> = a.iter().map(|x| x.as_i64()).collect(); + let i = ints?; + (i.len() == 4).then(|| { + ((i[0] as u32 as u128) << 96) + | ((i[1] as u32 as u128) << 64) + | ((i[2] as u32 as u128) << 32) + | i[3] as u32 as u128 + }) + } + serde_json::Value::String(s) => crate::auth::parse_uuid(s), + _ => None, + } +} + +/// `ResolvableProfile`'s read of a `profile` value: a bare name is +/// `createUnresolved` (the `PLAYER_NAME` codec's alternative), a compound +/// `name` + `id` + `properties` (`Partial.MAP_CODEC` or a `GameProfile`). +pub fn parse_profile(v: &serde_json::Value) -> ProfileInfo { + if let serde_json::Value::String(name) = v { + return ProfileInfo { + id: horizon_protocol::crypto::offline_uuid(name), + textures: None, + dynamic: valid_player_name(name).then(|| NameOrId::Name(name.clone())), + }; + } + let name = v.get("name").and_then(|n| n.as_str()).map(str::to_owned); + let id = v.get("id").and_then(profile_id); + let properties = v.get("properties").and_then(|p| p.as_array()); + let textures = properties + .into_iter() + .flatten() + .find(|p| p.get("name").and_then(|n| n.as_str()) == Some("textures")) + .and_then(|p| { + Some(( + p.get("value")?.as_str()?.to_owned(), + if p.get("signature").is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + )) + }); + // `ResolvableProfile.create`: a Partial is Dynamic with no properties + // and exactly one of a name or an id. + let dynamic = + (properties.is_none_or(|p| p.is_empty()) && name.is_some() != id.is_some()).then(|| { + name.as_deref().map_or_else( + || NameOrId::Id(id.unwrap()), + |n| NameOrId::Name(n.to_owned()), + ) + }); + ProfileInfo { + // `createPartialProfile`: the id, else the name's offline UUID, else nil. + id: id + .or_else(|| name.as_deref().map(horizon_protocol::crypto::offline_uuid)) + .unwrap_or(0), + textures, + dynamic, + } +} + +/// `ResolvableProfile.create`'s `Dynamic` key from a skull's `profile` tag: +/// a bare name string is `createUnresolved`, and a compound without +/// properties and with exactly one of a name or an id is `Dynamic`. +pub fn dynamic_nbt(profile: &horizon_world::nbt::Tag) -> Option { + if let horizon_world::nbt::Tag::String(s) = profile { + let name = s.to_string_lossy(); + return valid_player_name(&name).then_some(NameOrId::Name(name)); + } + if matches!(profile.get("properties"), Some(horizon_world::nbt::Tag::List(l)) if !l.is_empty()) + { + return None; + } + match (nbt_text(profile.get("name")), profile_uuid_nbt(profile)) { + (Some(name), None) => Some(NameOrId::Name(name)), + (None, Some(id)) => Some(NameOrId::Id(id)), + _ => None, + } +} + +/// `PlayerSkinRenderCache.getOrDefault` for a head: the resolved skin once +/// its texture is in the atlas (`atlas`), else `partialProfile`'s default. +pub fn head_skin( + profile: &serde_json::Value, + resolver: &mut Resolver, + downloads: &mut Downloader, + atlas: impl Fn(&str) -> bool, +) -> String { + let p = parse_profile(profile); + let property = p.textures.or_else(|| { + let key = p.dynamic.as_ref()?; + match resolver.state(key) { + Resolve::Done(Some(profile)) => profile.textures(), + _ => None, + } + }); + if let Some((value, signature)) = property + && let Some(url) = unpack(&value, signature, &TEXTURE_URIS).skin + && let Some(hash) = texture_hash(&url) + { + let location = skin_location(&hash); + match downloads.state(Kind::Skin, &url) { + Download::Ready if atlas(&location) => return location, + // Its slot was evicted: offer the image again. + Download::Ready => { + downloads.again(&location); + } + _ => {} + } + } + crate::tab_list::default_skin(p.id).to_owned() +} + /// `MinecraftProfileTexture.getHash`: the base name of the URL's path. pub fn texture_hash(url: &str) -> Option { let rest = url.split_once("://")?.1; @@ -313,7 +618,16 @@ pub struct Downloader { done: std::sync::mpsc::Receiver<((Kind, String), Option>)>, send: std::sync::mpsc::Sender<((Kind, String), Option>)>, ready: Vec<(String, Vec)>, + /// Locations already in `ready`, so `again` does not double-queue. + queued: std::collections::HashSet, + /// Decoded skin images by location, kept so a skin evicted from the + /// atlas uploads again (`again`); the disk cache backs anything dropped. + images: std::collections::HashMap>, + image_order: std::collections::VecDeque, } +/// `images` is bounded only so a long session on a busy server does not grow +/// without end; the disk cache holds everything it drops. +const MAX_SKIN_IMAGES: usize = 1024; impl Downloader { pub fn new(root: std::path::PathBuf) -> Self { let (send, done) = std::sync::mpsc::channel(); @@ -323,6 +637,9 @@ impl Downloader { done, send, ready: Vec::new(), + queued: Default::default(), + images: Default::default(), + image_order: Default::default(), } } /// How the download of `url` stands, starting it the first time. @@ -331,7 +648,9 @@ impl Downloader { let state = match image { Some(rgba) => { if key.0 == Kind::Skin { - self.ready.push((skin_location(&key.1), rgba)); + let location = skin_location(&key.1); + self.remember(location.clone(), rgba.clone()); + self.ready.push((location, rgba)); } Download::Ready } @@ -370,8 +689,48 @@ impl Downloader { }); Download::Pending } + /// Keeps a decoded skin for `again`, dropping the oldest past the bound. + fn remember(&mut self, location: String, rgba: Vec) { + if !self.images.contains_key(&location) { + self.image_order.push_back(location.clone()); + while self.image_order.len() > MAX_SKIN_IMAGES + && let Some(old) = self.image_order.pop_front() + { + self.images.remove(&old); + } + } + self.images.insert(location, rgba); + } + /// A ready skin whose atlas slot was evicted (`show_skin` answered no): + /// its image for upload again, from memory or the disk cache. + pub fn again(&mut self, location: &str) -> bool { + if self.queued.contains(location) { + return true; + } + let Some(digest) = location.strip_prefix("skins/") else { + return false; + }; + let image = self.images.get(location).cloned().or_else(|| { + let file = self + .root + .join(if digest.len() > 2 { &digest[..2] } else { "xx" }) + .join(digest); + let (w, h, rgba) = crate::hud::decode_bytes(&std::fs::read(&file).ok()?).ok()?; + process_legacy_skin(w, h, &rgba) + }); + let Some(image) = image else { + return false; + }; + self.remember(location.to_owned(), image.clone()); + self.queued.insert(location.to_owned()); + self.ready.push((location.to_owned(), image)); + true + } /// Skins that finished since the last call: texture id and 64x64 RGBA. pub fn take_ready(&mut self) -> Vec<(String, Vec)> { + for (location, _) in &self.ready { + self.queued.remove(location); + } std::mem::take(&mut self.ready) } } @@ -452,6 +811,129 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + #[test] + fn profiles_parse_like_resolvable_profiles() { + use super::{NameOrId, Signature, parse_profile}; + // A bare name is `createUnresolved`: dynamic by name, and its partial + // id is the name's offline UUID. + let p = parse_profile(&serde_json::json!("Notch")); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + assert_eq!(p.id, horizon_protocol::crypto::offline_uuid("Notch")); + assert!(p.textures.is_none()); + // A name-only compound resolves the same way. + let p = parse_profile(&serde_json::json!({"name": "Notch"})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + // An id-only compound resolves by id (int array or UUID string). + let id = 0x0123_4567_89ab_cdef_0123_4567_89ab_cdef_u128; + let ints: Vec = [ + (id >> 96) as i32 as i64, + (id >> 64) as i32 as i64, + (id >> 32) as i32 as i64, + id as i32 as i64, + ] + .into(); + let p = parse_profile(&serde_json::json!({"id": ints})); + assert_eq!(p.dynamic, Some(NameOrId::Id(id))); + let p = parse_profile(&serde_json::json!({"id": "01234567-89ab-cdef-0123-4567abcdef00"})); + assert_eq!( + p.dynamic, + Some(NameOrId::Id(0x0123_4567_89ab_cdef_0123_4567_abcd_ef00)) + ); + // Name and id but no properties is Static: it never resolves, and its + // default skin keys off the id. + let p = parse_profile(&serde_json::json!({"name": "Notch", "id": ints})); + assert!(p.dynamic.is_none()); + assert_eq!(p.id, id); + // A `textures` property makes it Static (unsigned and signed). + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v"}] + })); + assert!(p.dynamic.is_none()); + assert_eq!(p.textures, Some(("v".into(), Signature::Unsigned))); + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v", "signature": "s"}] + })); + assert_eq!(p.textures, Some(("v".into(), Signature::Signed))); + // Empty properties leave it dynamic. + let p = parse_profile(&serde_json::json!({"name": "Notch", "properties": []})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + } + + /// `getByName` and `getProfileById` answer from the services the + /// discovery document names; a profile resolves through both. + #[test] + fn profiles_resolve_through_the_services() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let reply = |status: &str, body: &str| { + format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + }; + for stream in listener.incoming().take(3) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + reader.read_line(&mut line).unwrap(); + while reader.read_line(&mut String::new()).unwrap() > 2 {} + let body = if line.contains("/users/profiles/minecraft/") { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"# + } else if line.contains("/session/minecraft/profile/") + && line.contains("unsigned=false") + { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"dmFsdWU=","signature":"c2ln"}]}"# + } else { + "{}" + }; + stream.write_all(reply("200 OK", body).as_bytes()).unwrap(); + } + }); + let doc = serde_json::json!({"discovery": { + "profiles": {"endpoints": {"getByName": {"uri": format!("{base}/users/profiles/minecraft/{{name}}")}}}, + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + let resolved = + super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).unwrap(); + assert_eq!(resolved.id, 0x069a_79f4_44e9_4726_a5be_fca9_0e38_aaf5); + assert_eq!(resolved.name, "Notch"); + assert_eq!( + resolved.properties, + vec![( + "textures".to_owned(), + "dmFsdWU=".to_owned(), + Some("c2ln".to_owned()) + )] + ); + let by_id = super::resolve_profile(&super::NameOrId::Id(resolved.id), &doc).unwrap(); + assert_eq!(by_id.name, "Notch"); + // A discovery without `profiles`/`getByName` resolves no name. + let doc = serde_json::json!({"discovery": { + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + assert!(super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).is_none()); + } + + /// A skin evicted from the atlas re-uploads (`again`), once per ask. + #[test] + fn evicted_skins_upload_again() { + let mut d = super::Downloader::new(std::env::temp_dir().join("horizon-test-skins")); + d.remember("skins/abc".into(), vec![1, 2, 3]); + assert!(d.again("skins/abc")); + assert!(!d.again("skins/missing")); + // Once queued, more asks do not pile up uploads. + assert!(d.again("skins/abc")); + assert_eq!( + d.take_ready(), + vec![("skins/abc".to_owned(), vec![1, 2, 3])] + ); + assert!(d.take_ready().is_empty()); + assert!(d.again("skins/abc")); + assert_eq!(d.take_ready().len(), 1); + } + #[test] fn profile_components_supply_unsigned_head_skins() { let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0="; From 0300ad8922780e964b1bab11488aed8b6bdb77f1 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:13:33 +0100 Subject: [PATCH 070/195] Keep the current attack target regardless of invisibility --- crates/horizon-client/src/mobs/goals.rs | 27 +++++++++++++++---- .../horizon-client/src/mobs/monster_brain.rs | 3 +++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c44614571..2341c11d4 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -588,21 +588,38 @@ impl Mob { if p.creative || p.allies.contains(&self.id) { return false; } - self.player_in_range(w, range, check_sight) + self.player_in_range(w, range, check_sight, true) + } + /// forCombat().ignoreInvisibilityTesting() for the player: the check for + /// a target the mob already has, which ignores the visibility scaling. + pub fn can_keep_target_player(&mut self, w: &MobWorld, range: f64) -> bool { + let Some(p) = &w.player else { return false }; + if p.creative || p.allies.contains(&self.id) { + return false; + } + self.player_in_range(w, range, true, false) } /// TargetingConditions.forNonCombat().range(range).test for the player /// (seen by anyone, within range scaled by visibility, in sight). pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool { - self.player_in_range(w, range, true) + self.player_in_range(w, range, true, true) } - fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { + /// `scale` is `TargetingConditions.testInvisible`: scale the range by + /// the player's visibility. + fn player_in_range( + &mut self, + w: &MobWorld, + range: f64, + check_sight: bool, + scale: bool, + ) -> bool { let Some(p) = &w.player else { return false }; if !p.alive || p.spectator { return false; } // LivingEntity.getVisibilityPercent - let mut visibility = p.visibility_percent(); - if let Some(head) = &p.head { + let mut visibility = if scale { p.visibility_percent() } else { 1.0 }; + if let Some(head) = p.head.as_ref().filter(|_| scale) { let skull = match self.species() { Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { "minecraft:zombie_head" diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 9456c00a1..4990913eb 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -359,11 +359,14 @@ fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { /// `Sensor.isEntityAttackable`: `TargetingConditions.forCombat()` within the /// follow range, in sight. fn attackable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + // The current ATTACK_TARGET is tested with ignoreInvisibilityTesting. + let current = mem_ref(m).attack_target.value() == Some(who); let range = m.attrs.follow_range; if !can_attack(m, w, who) { return false; } match who { + Who::Player if current => m.can_keep_target_player(w, range), Who::Player => m.can_target_player(w, range, true), Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; From 004ad993d9e77d8262094afea01b2351b1bf3403 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:16:15 +0000 Subject: [PATCH 071/195] Reject boarding a horse with an existing mob passenger Fixes #1759 Co-Authored-By: OpenAI Codex GPT-6.1 Sol --- crates/horizon-client/src/game/mounts.rs | 11 ++++++ tools/lan_e2e.py | 47 +++++++++++++++++++++++- 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa4bbc209..7da98135f 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -175,6 +175,17 @@ impl Game<'_> { return true; } // doPlayerRide + // Entity.canAddPassenger: ordinary horses have one seat. Camels + // override that capacity; equipment and feeding above are separate. + if !matches!(species, Species::Camel | Species::CamelHusk) + && self.mobs.iter().any(|passenger| { + passenger.extra.mount == Some(self.mobs[index].id) + && !passenger.removed + && passenger.alive() + }) + { + return false; + } let m = &mut self.mobs[index]; m.extra.flag = false; m.extra.counter = 0; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index c508a67d6..f179a201c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -299,7 +299,7 @@ CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'si 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', - 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', + 'lightning', 'riding', 'occupied_horse', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater', 'fireworks'] @@ -4199,6 +4199,49 @@ def check_riding(host, guest, out): return result +def check_occupied_horse(host, guest, out): + """#1759: a mob passenger fills a zombie horse's seat, for both real players.""" + spots = apart(host, guest) + result = {} + tag = 'occupied_horse' + host('command', command='time set midnight') + for label, player in (('host', host), ('guest', guest)): + x, y, z = spots[label] + at = (x + 0.5, y, z + 2.5) + player('command', command='gamemode creative') + player('command', command='clear @s') + result[label] = {} + for occupied in (True, False): + passengers = ',Passengers:[{id:"minecraft:zombie",NoAI:1b,PersistenceRequired:1b}]' if occupied else '' + try: + player('command', command=f'summon minecraft:zombie_horse {at[0]} {y} {at[2]} ' + f'{{Tame:1b,NoAI:1b,NoGravity:1b,Tags:["{tag}"]{passengers}}}') + player.wait(5) + horse = next(m for m in player.raw('mobs', 16)['near'] + if m['kind'] == 'minecraft:zombie_horse' and m['health'] > 0 + and math.dist(m['pos'], at) < 0.1) + if occupied: + # Assert the setup too: a missing passenger would make this a false positive. + passengers_nbt = player('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') + assert 'minecraft:zombie' in json.dumps(passengers_nbt), passengers_nbt + player.raw('look-at', at[0], y + 0.8, at[2]) + player.raw('mouse', 'right', 'click') + player.wait(10) + riding = player('status').get('riding') + expected = None if occupied else horse['id'] + assert riding == expected, f'{label}: occupied={occupied}, riding={riding}, expected={expected}' + result[label]['occupied' if occupied else 'free'] = riding + player.shot(out, f'occupied-horse-{label}-{occupied}') + if not occupied: + hold(player, 'shift', 5) + finally: + player('command', command=f'kill @e[tag={tag}]') + player('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..6]') + player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5} 0 0') + player.wait(25) + return result + + # Mount inventories: (kind, summon NBT, what goes in by shift-click and the menu slot it lands # in: 700 the saddle, 701 the body armour or carpet, 710 the chest's first slot). MOUNT_MENUS = [ @@ -4688,7 +4731,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, - 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, + 'lightning': check_lightning, 'riding': check_riding, 'occupied_horse': check_occupied_horse, 'mounts': check_mounts, 'worldspawn': check_world_spawn, 'beds': check_beds, 'shield': check_shield, 'deathmining': check_death_mining, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, From 442d52a038aa50a715e5517d59f3a1d78ec075e6 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:19:04 +0000 Subject: [PATCH 072/195] Release notes: preserve wrapped known issues Co-Authored-By: OpenCode agentrouter/gpt-6.1-sol --- tests/test_release_train.py | 28 ++++++++++++++++++++++++++-- tools/release_train.py | 12 +++++++++++- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 56064fa42..58fc591b1 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -219,10 +219,34 @@ class ReleaseTrainTests(unittest.TestCase): def test_known_issues_are_the_bullets_of_the_file(self): with tempfile.TemporaryDirectory() as temp: path = Path(temp, "known-issues.md") - path.write_text("# Known issues\n\nSome text.\n\n- One.\n- Two, with **bold**.\n continued\n") - self.assertEqual(train.known_issues(path), ["- One.", "- Two, with **bold**."]) + path.write_text("# Known issues\n\nSome text.\n\n- One.\n- Two, with **bold**. \n" + " continued with `code`\n\tand a [link](https://example.com). \n- Three.\n") + self.assertEqual(train.known_issues(path), + ["- One.", "- Two, with **bold**. continued with `code` and a [link](https://example.com).", + "- Three."]) self.assertEqual(train.known_issues(Path(temp, "missing.md")), []) + def test_known_issues_do_not_include_unrelated_text(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp, "known-issues.md") + for separator in ["\n", " \n", "# Heading\n", "Some text.\n"]: + with self.subTest(separator=separator): + path.write_text(" Intro.\n- One.\n continued.\n" + separator + " Not an issue.\n- Two.\n") + self.assertEqual(train.known_issues(path), ["- One. continued.", "- Two."]) + path.write_text("# Known issues\n\nNo issues.\n") + self.assertEqual(train.known_issues(path), []) + path.write_text("") + self.assertEqual(train.known_issues(path), []) + + def test_notes_keep_the_wrapped_shaderpacks_issue(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp, "known-issues.md") + path.write_text("- Shader packs have been removed for now. Packs in your\n" + " `shaderpacks` folder are left where they are.\n") + _, body = train.notes("game", "v0.2.70", [pr(1)], train.known_issues(path)) + self.assertIn("### Known issues\n- Shader packs have been removed for now. Packs in your " + "`shaderpacks` folder are left where they are.\n", body) + if __name__ == "__main__": unittest.main() diff --git a/tools/release_train.py b/tools/release_train.py index 48d4d46cf..1e4fa5a19 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -347,7 +347,17 @@ def bullet(pr): def known_issues(path=ROOT / "docs" / "known-issues.md"): if not path.exists(): return [] - return [line.rstrip() for line in path.read_text().splitlines() if line.startswith("- ")] + issues = [] + in_bullet = False + for line in path.read_text().splitlines(): + if line.startswith("- "): + issues.append(line.rstrip()) + in_bullet = True + elif in_bullet and line.startswith((" ", "\t")) and line.strip(): + issues[-1] += " " + line.strip() + else: + in_bullet = False + return issues def line_intro(kind, version, previous): From f661443fa993eb4d26649cb6b7c9c67d76cd683e Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:22:50 +0000 Subject: [PATCH 073/195] Read LAN passenger fixture output through the host Co-Authored-By: OpenAI Codex GPT-6.1 Sol --- tools/lan_e2e.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index f179a201c..f16e6312b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -4222,7 +4222,7 @@ def check_occupied_horse(host, guest, out): and math.dist(m['pos'], at) < 0.1) if occupied: # Assert the setup too: a missing passenger would make this a false positive. - passengers_nbt = player('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') + passengers_nbt = host('command', command=f'data get entity @e[tag={tag},limit=1] Passengers') assert 'minecraft:zombie' in json.dumps(passengers_nbt), passengers_nbt player.raw('look-at', at[0], y + 0.8, at[2]) player.raw('mouse', 'right', 'click') From 5589edb118c0a9152c2dabb2ff22bfaf5aae5b3c Mon Sep 17 00:00:00 2001 From: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:26:50 +0100 Subject: [PATCH 074/195] Server packs: swallow gameplay input while the reload progress shows The progress overlay only changed drawing: a pack pushed while playing left movement, attack and use live behind it. Input events are now dropped while the staged reload runs (as vanilla's LoadingOverlay does), and start_pack_reload releases held keys and mouse buttons up front so nothing keeps acting across the frame it covers. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game.rs | 13 +++++++++++++ crates/horizon-client/src/game/server_packs.rs | 7 +++++++ 2 files changed, 20 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index abaa639eb..e5ab50256 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11314,6 +11314,19 @@ impl ApplicationHandler for Game<'_> { { return; } + // The pack reload's progress overlay takes no input + // (`LoadingOverlay`): `start_pack_reload` released what was held. + if self.server_packs.reload.is_some() + && !matches!( + &event, + WindowEvent::CloseRequested + | WindowEvent::Focused(_) + | WindowEvent::Resized(_) + | WindowEvent::RedrawRequested + ) + { + return; + } if self.pending_save.is_some() { match event { WindowEvent::CloseRequested => { diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 12b73f4f9..d0769b894 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -407,6 +407,13 @@ impl Game<'_> { return; }; self.server_packs.active = server.clone(); + // The overlay swallows input until the apply (`LoadingOverlay`): + // release what is held so nothing keeps acting while it covers the + // frame (`KeyMapping.releaseAll` when a screen opens). + self.keys.clear(); + self.physical_keys.clear(); + self.left = false; + self.right = false; let vanilla = self.vanilla_root(); if self.ui.vanilla_root.as_os_str().is_empty() { self.ui.vanilla_root = vanilla.clone(); From 077da2e06b16bcfded6224765b838c3177b45d38 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 18:30:09 +0100 Subject: [PATCH 075/195] Queue the first skin upload as well as re-uploads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The completed-download push into ready never marked the location queued, so an again() before the next take_ready() put the same skin in twice: store_skin allocated two slots, and evicting one removed the sprite while show_skin still found the other entry — the skin never uploaded again. Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/skins.rs | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index 239e1c3ac..740208973 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -649,8 +649,7 @@ impl Downloader { Some(rgba) => { if key.0 == Kind::Skin { let location = skin_location(&key.1); - self.remember(location.clone(), rgba.clone()); - self.ready.push((location, rgba)); + self.queue(location, rgba); } Download::Ready } @@ -701,6 +700,13 @@ impl Downloader { } self.images.insert(location, rgba); } + /// An image off to the atlas: remembered for `again` and marked queued + /// so nothing uploads the same location twice. + fn queue(&mut self, location: String, rgba: Vec) { + self.remember(location.clone(), rgba.clone()); + self.queued.insert(location.clone()); + self.ready.push((location, rgba)); + } /// A ready skin whose atlas slot was evicted (`show_skin` answered no): /// its image for upload again, from memory or the disk cache. pub fn again(&mut self, location: &str) -> bool { @@ -721,9 +727,7 @@ impl Downloader { let Some(image) = image else { return false; }; - self.remember(location.to_owned(), image.clone()); - self.queued.insert(location.to_owned()); - self.ready.push((location.to_owned(), image)); + self.queue(location.to_owned(), image); true } /// Skins that finished since the last call: texture id and 64x64 RGBA. @@ -932,6 +936,11 @@ mod tests { assert!(d.take_ready().is_empty()); assert!(d.again("skins/abc")); assert_eq!(d.take_ready().len(), 1); + // The first upload marks the location queued too: an `again` before + // `take_ready` does not put the same skin in the atlas twice. + d.queue("skins/def".into(), vec![4]); + assert!(d.again("skins/def")); + assert_eq!(d.take_ready(), vec![("skins/def".to_owned(), vec![4])]); } #[test] From 2c8b933be483bcf6d44437fb0763facfee707095 Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 18:30:53 +0100 Subject: [PATCH 076/195] Apply vanilla's view scale to entity render distance Entity.shouldRenderAtSqrDistance scales the bounding box's mean edge by 64 * viewScale, and LevelExtractor sets viewScale to the entity distance option times clamp(renderDistance / 8, 1, 2.5). Horizon used the option alone, so above render distance 8 entities vanished sooner than vanilla: a chicken at 32 blocks instead of 48 at the default 12. RemotePlayer's box also counts ten times. Fixes #2273 Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --- crates/horizon-client/src/game/boats.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 13 ++++++++++--- crates/horizon-client/src/game/cushions.rs | 3 +-- crates/horizon-client/src/game/entity_culling.rs | 16 +++++++++++++--- crates/horizon-client/src/game/frames.rs | 5 +++-- crates/horizon-client/src/game/minecarts.rs | 5 ++--- crates/horizon-client/src/game/paintings.rs | 3 +-- crates/horizon-client/src/game/text_displays.rs | 3 ++- crates/horizon-client/src/game/tnt.rs | 2 +- crates/horizon-client/src/game/trident.rs | 2 +- 10 files changed, 35 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 06dfab22d..7e80f6f58 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -862,7 +862,7 @@ impl Game<'_> { let a = alpha as f32; let range = super::entity_culling::default_range( glam::DVec3::new(WIDTH, HEIGHT, WIDTH), - self.settings.entity_distance, + self.view_scale(), ); for b in &self.boats { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index a2ed7fd66..f8c28732a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3032,7 +3032,7 @@ impl Game<'_> { pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); - let scale = f64::from(self.settings.entity_distance); + let scale = self.view_scale(); for mob in &self.mobs { let entity_start = out.len(); // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. @@ -3041,9 +3041,16 @@ impl Game<'_> { } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's - // mean edge, scaled by the entity distance option. + // mean edge, scaled by the view scale. RemotePlayer's box counts + // ten times. let (w, h, _) = mob.dims(); - let range = (w + h + w) / 3.0 * 64.0 * scale; + let edge = (w + h + w) / 3.0 + * if &*mob.kind.id == "minecraft:player" { + 10.0 + } else { + 1.0 + }; + let range = edge * 64.0 * scale; if d.length_squared() >= range * range { continue; } diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs index 0847321d6..216e2cc1b 100644 --- a/crates/horizon-client/src/game/cushions.rs +++ b/crates/horizon-client/src/game/cushions.rs @@ -455,8 +455,7 @@ impl Game<'_> { glam::DVec3::new(lo.x, lo.y, lo.z), glam::DVec3::new(hi.x, hi.y, hi.z), ); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 66fbaa3e4..4377b2f8d 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -60,12 +60,22 @@ impl Game<'_> { } } +impl Game<'_> { + /// Entity.setViewScale (LevelExtractor.extractVisibleEntities): the entity + /// distance option times the render distance's boost — 1 at 8 chunks, 2.5 + /// at 20 or more (`streaming.radius` is the effective render distance). + pub(super) fn view_scale(&self) -> f64 { + (f64::from(self.streaming.radius) / 8.0).clamp(1.0, 2.5) + * f64::from(self.settings.entity_distance) + } +} + /// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding -/// box's mean edge, scaled by the entity distance option. -pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 { +/// box's mean edge, scaled by the view scale. +pub(super) fn default_range(size: glam::DVec3, view_scale: f64) -> f64 { let edge = (size.x + size.y + size.z) / 3.0; let edge = if edge.is_nan() { 1.0 } else { edge }; - edge * 64.0 * f64::from(view_scale) + edge * 64.0 * view_scale } impl Game<'_> { diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index d08c5f283..b4e6bb158 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -311,8 +311,9 @@ impl Game<'_> { let sprites = &self.gui.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); - // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%. - let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance); + // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at a view scale + // of 1. + let range = 16.0 * 64.0 * self.view_scale(); for f in &self.item_frames { let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..781dd6b7c 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1340,9 +1340,8 @@ impl Game<'_> { return; }; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean - // edge, scaled by the entity distance option. - let range = - (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance); + // edge, scaled by the view scale. + let range = (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * self.view_scale(); for c in &self.carts { let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 321e59f7d..1b839f5b0 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -267,8 +267,7 @@ impl Game<'_> { // measured from the box's centre (HangingEntity's position). let (lo, hi) = p.bounds(); let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/text_displays.rs b/crates/horizon-client/src/game/text_displays.rs index 45bd64fa7..587db3382 100644 --- a/crates/horizon-client/src/game/text_displays.rs +++ b/crates/horizon-client/src/game/text_displays.rs @@ -164,11 +164,12 @@ impl Game<'_> { } else { [self.yaw, self.pitch] }; + let scale = self.view_scale(); for display in self.text_displays.values_mut() { display.last_progress = display.progress(partial as f32); let d = display.shown.blend(&display.from, display.last_progress); let position = display.previous.lerp(display.position, partial); - let range = f64::from(d.view_range) * 64.0 * f64::from(self.settings.entity_distance); + let range = f64::from(d.view_range) * 64.0 * scale; if position.distance_squared(camera) >= range * range || d.text.is_empty() { continue; } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 6bd2ae956..177e3bf80 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -252,7 +252,7 @@ impl Game<'_> { } let range = super::entity_culling::default_range( glam::DVec3::splat(PrimedTnt::SIZE), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tnts { // EntityRenderer.shouldRender. diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index c31094596..cfb8d807c 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -419,7 +419,7 @@ impl Game<'_> { let range = 10.0 * super::entity_culling::default_range( glam::DVec3::splat(2.0 * HALF), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tridents { // EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5. From 1862395e4b72d7ed7d5e6ee1769727ac38964031 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 13:32:44 -0400 Subject: [PATCH 077/195] Keep a leaving guest's play state until their statistics are saved lan_crafting_left removed the guest's GuestPlay from host.play before the leave_game award and save_guest_records ran, so a normal guest disconnect awarded nothing and wrote no statistics. It now takes the crafting table and workstation state out of the entry and leaves the entry for HostEvent::Left to remove after saving. New lan_e2e check `leave`: a guest leaves twice and the host's saved statistics show leave_game 1, then 2. It fails on the previous commit (0, then [0, 0]) and passes here. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/src/game/lan_crafting.rs | 10 +++--- tools/lan_e2e.py | 35 +++++++++++++++++-- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index db6235c4d..839390529 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -576,16 +576,18 @@ impl Game<'_> { /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let play = host.play.remove(&g.conn); + // The guest's play state stays: their statistics are awarded and saved + // after this (`HostEvent::Left`), which removes it. + let play = host.play.get_mut(&g.conn); 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.take() { grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); } // A workstation's inputs too. - if let Some(station) = &play.station { - grid.extend(super::lan_stations::station_inputs(station)); + if let Some(station) = play.station.take() { + grid.extend(super::lan_stations::station_inputs(&station)); } } if grid.is_empty() { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 866602c9b..2c8885b81 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -22,7 +22,7 @@ address. The script then checks, from both sides, what a guest's game used to ge - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; - kills: a pig the guest kills counts in the guest's killed statistic, not the host's (#484); - +- leave: a guest who leaves has leave_game in their saved statistics, and again after the next leave; - arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484); - looks: mobs look on both sides as the server has them (their synched data): a calf is a @@ -290,7 +290,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # Match normal single player; --in-frame is the comparison path. SERVER_THREAD = True -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'leave', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -1134,6 +1134,35 @@ def check_pvp(host, guest, out): return hits +def leave_game_total(host): + """The leave_game statistic summed over the stats files the host's world holds.""" + total = 0 + for path in (host.work / 'saves' / 'Lan' / 'players' / 'stats').glob('*.json'): + custom = json.loads(path.read_text()).get('stats', {}).get('minecraft:custom', {}) + total += custom.get('minecraft:leave_game', 0) + return total + + +def check_leave(host, guest, out): + # PlayerList.remove awards Stats.LEAVE_GAME before it saves the player: a guest who leaves has it in + # their saved statistics, and it counts again the next time they leave. + port = host.raw('lan', 'status')['port'] + before = leave_game_total(host) + counts = [] + for _ in range(2): + guest.raw('disconnect') + for _ in range(20): + time.sleep(0.5) + if leave_game_total(host) > (counts[-1] if counts else before): + break + counts.append(leave_game_total(host)) + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + assert counts == [before + 1, before + 2], f'leave_game was {before}, then {counts} after two leaves' + return {'leave_game': counts} + + def check_kills(host, guest, out): # A mob the guest kills is the guest's kill (#484): LivingEntity.die credits lastHurtByPlayer, so the # killed statistic (and its scoreboard criterion) counts for the guest, not the host. @@ -4616,7 +4645,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, 'time': check_time, 'growth': check_growth, 'doors': check_doors, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, - 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, + 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'leave': check_leave, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'mounts': check_mounts, From 76d748caf8b5d5a5e8e5446c0533d862197f3cf3 Mon Sep 17 00:00:00 2001 From: Pavel Mikhailovin Date: Mon, 26 Oct 2026 20:43:35 +0300 Subject: [PATCH 078/195] Server books: positional page indicator and component-list pages The page indicator only replaced bare %s, but 26.3's en_us template is "Page %1$s of %2$s"; it now goes through format_java like other translations (BookViewScreen.getPageNumberMessage). Pages sent as a component list (Hypixel through ViaVersion) were dropped by item_data::read_text, which only took a string or a compound, so the book opened blank. ComponentSerialization.CODEC also takes a list. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/books.rs | 9 ++++--- crates/horizon-client/src/item_data.rs | 35 ++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 2f38dffd9..b09803e49 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -1009,9 +1009,12 @@ impl Game<'_> { } }; let indicator = |batch: &mut HudBatch, page: usize, count: usize| { - let text = tr("book.pageIndicator", "Page %s of %s") - .replacen("%s", &(page + 1).to_string(), 1) - .replacen("%s", &count.max(1).to_string(), 1); + // BookViewScreen.getPageNumberMessage: 26.3's en_us template is + // positional ("Page %1$s of %2$s"). + let text = horizon_protocol::text::format_java( + &tr("book.pageIndicator", "Page %1$s of %2$s"), + &[(page + 1).to_string(), count.max(1).to_string()], + ); let tw = HudBatch::text_width(atlas, &text); batch.text(atlas, &text, left + 148.0 - tw, top + 16.0, BLACK, false); }; diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index ac624e85b..3d4fb11e5 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -305,7 +305,9 @@ fn read_text(t: &Tag) -> Option { // A component's root `text` may be empty with the visible words in // `extra` (every legacy display name ViaVersion produces looks like // this), so flatten the whole component instead of reading one key. - Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()), + // ComponentSerialization.CODEC also takes a list (its first element + // styling the rest), as servers behind ViaVersion send book pages. + Tag::Compound(_) | Tag::List(_) => Some(crate::entity_nbt::name_text(t).plain()), _ => None, } } @@ -899,6 +901,37 @@ mod tests { ); } + #[test] + fn written_book_pages_may_be_component_lists() { + // A page as Hypixel sends it through ViaVersion: a list, not a compound. + let page = Tag::List(vec![ + Tag::compound([("text", Tag::String("".into()))]), + Tag::compound([("text", Tag::String("Please read ".into()))]), + Tag::compound([("text", Tag::String("the rules".into()))]), + ]); + let book = Tag::compound([ + ( + "title", + Tag::compound([("raw", Tag::String("Rules".into()))]), + ), + ("author", Tag::String("Server".into())), + ( + "pages", + Tag::List(vec![ + page, + Tag::compound([("raw", Tag::String("Two".into()))]), + ]), + ), + ]); + let components = Tag::compound([("minecraft:written_book_content", book)]); + let (_, extra) = decode_components(Some(&components)); + let pages = extra.and_then(|d| d.written.clone()).map(|w| w.pages); + assert_eq!( + pages, + Some(vec!["Please read the rules".to_owned(), "Two".to_owned()]) + ); + } + #[test] fn banner_layers_and_shield_base_round_trip() { let mut stack = ItemStack::new("minecraft:shield", 1); From 91d6bdba85be4bc2f81b5f44ab896257799ecbf5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:11:21 +0100 Subject: [PATCH 079/195] Fly firework rockets on by themselves between server updates --- crates/horizon-client/src/game/fireworks.rs | 89 +++++++++++-------- crates/horizon-client/src/game/remote.rs | 9 ++ .../src/game/remote_projectiles.rs | 16 +++- 3 files changed, 72 insertions(+), 42 deletions(-) diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index af226335e..716fa7d60 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -62,11 +62,56 @@ impl Rocket { item, } } - /// One tick of a server's client: the previous position, then `step`. - pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + /// One tick of a server's client: the rocket flies on by itself between + /// the server's updates (a rocket that follows an entity is placed by the + /// caller). + pub(super) fn remote_step(&mut self, scene: &mut SceneCollisions) { self.previous = self.position; + if self.attached_to.is_none() { + self.free_flight(scene); + } self.life += 1; - self.position = step(self.position); + } + /// `FireworkRocketEntity.tick` for a rocket attached to no entity: speed + /// up (an angled one keeps its motion) and rise, then move. True when a + /// block stopped it. + fn free_flight(&mut self, scene: &mut SceneCollisions) -> bool { + let h = 0.125; + let bounds = Aabb::new( + Vec3::new(self.position.x - h, self.position.y, self.position.z - h), + Vec3::new( + self.position.x + h, + self.position.y + 2.0 * h, + self.position.z + h, + ), + ); + let wanted = if self.angled { + self.velocity + } else { + Vec3::new( + self.velocity.x * 1.15, + self.velocity.y + 0.04, + self.velocity.z * 1.15, + ) + }; + let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) else { + return false; + }; + let blocked = (moved.x - wanted.x).abs() > 1e-7 + || (moved.y - wanted.y).abs() > 1e-7 + || (moved.z - wanted.z).abs() > 1e-7; + let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + self.velocity = if horizontal { + Vec3::new(self.velocity.x, wanted.y, self.velocity.z) + } else { + wanted + }; + blocked } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { @@ -191,46 +236,14 @@ impl Game<'_> { r.velocity = p.velocity; } } else { - // Not shot at an angle: accelerate (unless blocked sideways) and rise. let mut scene = SceneCollisions { world: &self.world, binding: self.collision, subject: None, }; - let h = 0.125; - let bounds = Aabb::new( - Vec3::new(r.position.x - h, r.position.y, r.position.z - h), - Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h), - ); - let wanted = if r.angled { - r.velocity - } else { - Vec3::new( - r.velocity.x * 1.15, - r.velocity.y + 0.04, - r.velocity.z * 1.15, - ) - }; - if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) { - let blocked = (moved.x - wanted.x).abs() > 1e-7 - || (moved.y - wanted.y).abs() > 1e-7 - || (moved.z - wanted.z).abs() > 1e-7; - if r.angled && blocked { - // hitTargetOrDeflectSelf: explode on the block. - r.life = r.lifetime; - } - let horizontal = - (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; - r.position = Vec3::new( - r.position.x + moved.x, - r.position.y + moved.y, - r.position.z + moved.z, - ); - r.velocity = if horizontal { - Vec3::new(r.velocity.x, wanted.y, r.velocity.z) - } else { - wanted - }; + if r.free_flight(&mut scene) && r.angled { + // hitTargetOrDeflectSelf: explode on the block. + r.life = r.lifetime; } } let at = [r.position.x, r.position.y, r.position.z]; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..1c86da46b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1406,6 +1406,13 @@ impl Game<'_> { { return; } + // So does a firework rocket: its own tick flies it on. + if path.is_some() + && let Some(f) = self.rockets.iter_mut().find(|f| f.id == id as u32) + { + f.position = Vec3::new(position[0], position[1], position[2]); + return; + } // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: // the server's position replaces its own at once. if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { @@ -3016,6 +3023,8 @@ impl Game<'_> { p.velocity = v; } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { b.velocity = v; + } else if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id as u32) { + r.velocity = v; } else if let Some(p) = self .remote .as_mut() diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index b12cb4cd6..1dc9da095 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,8 +3,11 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; -use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}; +use horizon_client::{ + collisions::SceneCollisions, + particles::{ParticleOptions, ParticleType}, +}; use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; @@ -361,9 +364,13 @@ impl Game<'_> { .remote .as_ref() .and_then(|r| u32::try_from(r.entity_id).ok()); - for r in &mut self.rockets { - let id = r.id; - r.remote_step(|at| step(id, at)); + let mut rockets = std::mem::take(&mut self.rockets); + for r in &mut rockets { + r.remote_step(&mut SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }); if let Some(target) = r.attached_to { if me == Some(target) { if let Some(p) = self.player.as_mut() { @@ -401,6 +408,7 @@ impl Game<'_> { v, ); } + self.rockets = rockets; for c in &mut self.crystals { c.time += 1; c.position = step(c.id, c.position); From 484cc945aa0b4c9cf558da2262169e8ae09642fb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:23:52 +0100 Subject: [PATCH 080/195] Add the rockets list to the remote motion test fixture --- tests/test_remote_motion.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py index b00e5f0a9..59526b476 100644 --- a/tests/test_remote_motion.py +++ b/tests/test_remote_motion.py @@ -35,7 +35,8 @@ impl End { fn remote_eye_motion(&mut self, _id: u32, _v: [f64; 3]) {} } #[derive(Default)] struct Game { mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, - creatures: Creatures, dragon_fireballs: Vec, remote: Option, + creatures: Creatures, dragon_fireballs: Vec, rockets: Vec, + remote: Option, potions: Potions, end: End, } impl Game { From 766bfbcdfa6d602518e0fe70657092c54f63b692 Mon Sep 17 00:00:00 2001 From: mahirsn Date: Mon, 26 Oct 2026 21:13:00 +0300 Subject: [PATCH 081/195] fix(client): answer the server's held slot like vanilla ClientboundSetHeldSlotPacket only changes the selected hotbar slot (and ignores slots outside the hotbar), so the next tick sends ServerboundSetCarriedItemPacket as vanilla does. Each login starts again from slot 0, as handleLogin's new MultiPlayerGameMode and LocalPlayer do. --- crates/horizon-client/src/game/remote.rs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..d53420db9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1619,7 +1619,11 @@ impl Game<'_> { } C::Login(p) => { self.level.hardcore = p.hardcore; + // handleLogin makes a new MultiPlayerGameMode (carried index 0) and a + // new LocalPlayer (slot 0). + self.selected = 0; if let Some(r) = self.remote.as_mut() { + r.carried = Some(0); r.online_mode = p.online_mode; r.entity_id = p.player_id; r.view_distance = p.chunk_radius; @@ -2295,10 +2299,11 @@ impl Game<'_> { } self.apply_remote_abilities(); } + // ClientPacketListener.handleSetHeldSlot: a hotbar slot only, and the + // carried index stays, so the next tick answers with SetCarriedItem. C::SetHeldSlot(p) => { - self.selected = p.slot.clamp(0, 8) as usize; - if let Some(r) = self.remote.as_mut() { - r.carried = Some(self.selected); + if (0..9).contains(&p.slot) { + self.selected = p.slot as usize; } } C::ContainerSetContent(p) => { From 2b2aecd9757305af6e124daeaf55b5327440c02e Mon Sep 17 00:00:00 2001 From: mahirsn Date: Mon, 26 Oct 2026 21:40:03 +0300 Subject: [PATCH 082/195] fix(client): send sign editor text like vanilla A new editor or a removed sign closes the open editor (Minecraft.setScreen, AbstractSignEditScreen.tick), and closing sends ServerboundSignUpdatePacket with the lines it opened with when the sign is gone. Sign lines resolve key binds and translations (Component.getString) instead of keeping only plain text. --- crates/horizon-client/src/game/remote.rs | 9 +++++++ crates/horizon-client/src/game/sign_edit.rs | 29 +++++++++++++++------ crates/horizon-client/src/signs.rs | 8 +++--- 3 files changed, 34 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..4e279de6c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3129,6 +3129,15 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; + // AbstractSignEditScreen.tick: the editor closes once its sign is removed. + if let Some(edit) = &self.sign_edit + && !matches!( + self.world.block_entities.get(&edit.pos), + Some(BlockEntity::Sign(_)) + ) + { + self.close_sign_editor(); + } self.track_experience_display(); // Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s // for a server's client (multiplayer and the default single player), diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 2d010f1f5..529e511f2 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -20,6 +20,9 @@ pub(super) struct SignEditor { pub line: usize, /// The line being edited (`AbstractSignEditScreen`'s text field). edit: EditBox, + /// `AbstractSignEditScreen.messages`: the lines when it opened, sent if + /// the sign is gone by the time the editor closes. + lines: [String; 4], } fn sign_box() -> EditBox { @@ -33,11 +36,19 @@ fn sign_box() -> EditBox { impl Game<'_> { /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { + // Minecraft.setScreen: the editor already open is removed first. + self.close_sign_editor(); + let lines = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Sign(sign)) if front => sign.front.lines.clone(), + Some(BlockEntity::Sign(sign)) => sign.back.lines.clone(), + _ => Default::default(), + }; self.sign_edit = Some(SignEditor { pos, front, line: 0, edit: sign_box(), + lines, }); self.sign_load(); self.keys.clear(); @@ -50,14 +61,16 @@ impl Game<'_> { pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { if self.remote.is_some() { - if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { - let side = if edit.front { &sign.front } else { &sign.back }; - self.send(S::SignUpdate(play::SignUpdate { - pos: [edit.pos.0, edit.pos.1, edit.pos.2], - lines: side.lines.clone(), - front: edit.front, - })); - } + let lines = match self.world.block_entities.get(&edit.pos) { + Some(BlockEntity::Sign(sign)) if edit.front => sign.front.lines.clone(), + Some(BlockEntity::Sign(sign)) => sign.back.lines.clone(), + _ => edit.lines, + }; + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines, + front: edit.front, + })); } else { self.mark_block_entity_updated(edit.pos); } diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs index 07217ed79..799210797 100644 --- a/crates/horizon-client/src/signs.rs +++ b/crates/horizon-client/src/signs.rs @@ -147,10 +147,10 @@ fn component_text(tag: &Tag) -> String { _ => s, } } - Tag::Compound(_) => match tag.get("text") { - Some(Tag::String(t)) => t.to_string_lossy(), - _ => String::new(), - }, + // Component.getString: translations and key binds resolved. + Tag::Compound(_) => { + crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(tag)).plain() + } _ => String::new(), } } From ae3737b1c279efb2acb3092f04d6711820c2de61 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:34:08 +0100 Subject: [PATCH 083/195] Mod API: render.set-far-terrain, and the official Far View mod A mod can now turn on the game's distant terrain (LOD) with render.set-far-terrain: a distance of 64 to 1024 chunks and Far Detail's Reduced. The game builds and draws the tiles as it does for the LOD Distance setting, which wins while it is on. One far terrain shows at a time, the first loaded mod's. API level 4. mods/official/far-view is the official mod on it: Distance (256 chunks by default) and Far detail on its settings page, kept in its storage. --- Cargo.lock | 7 ++ Cargo.toml | 2 +- crates/horizon-client/src/game.rs | 34 +++++-- crates/horizon-client/src/game/mod_input.rs | 18 ++++ crates/horizon-client/src/graphics.rs | 16 ++-- crates/horizon-mod-sdk/wit/horizon.wit | 17 ++++ crates/horizon-mods/src/api_level.rs | 5 +- crates/horizon-mods/src/runtime.rs | 25 +++++- crates/horizon-mods/tests/sandbox.rs | 17 +++- crates/horizon-mods/tests/ui_guest/src/lib.rs | 10 +++ docs/api/mods-reference.md | 8 ++ docs/api/stability.md | 7 +- docs/graphics.md | 2 +- docs/mods.md | 5 +- mods/official/far-view/Cargo.toml | 16 ++++ mods/official/far-view/horizon-mod.toml | 9 ++ mods/official/far-view/src/lib.rs | 89 +++++++++++++++++++ 17 files changed, 261 insertions(+), 26 deletions(-) create mode 100644 mods/official/far-view/Cargo.toml create mode 100644 mods/official/far-view/horizon-mod.toml create mode 100644 mods/official/far-view/src/lib.rs diff --git a/Cargo.lock b/Cargo.lock index 809df3a5a..a17262571 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -923,6 +923,13 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "far-view" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "fdeflate" version = "0.3.7" diff --git a/Cargo.toml b/Cargo.toml index 59bfe5e33..a669fb489 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/far-view", "mods/official/minimap", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d00c7710c..1e4e93d3b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11208,11 +11208,28 @@ impl Game<'_> { } Ok(()) } - /// LOD Distance as far terrain uses it (`Graphics::lod_distance_on`). + /// LOD Distance and Far Detail Reduced as chosen: the player's LOD + /// Distance when it is on, else a mod's far terrain + /// (`render.set-far-terrain`). + fn far_terrain_choice(&self) -> (u32, bool) { + let g = &self.settings.horizon; + let reduced = g.far_detail == horizon_client::graphics::FarDetail::Reduced; + if g.lod_distance > 0 { + return (g.lod_distance, reduced); + } + match self.mod_far_terrain() { + Some(f) => (f.distance, reduced || f.reduced), + None => (0, reduced), + } + } + /// LOD Distance as far terrain uses it (`graphics::lod_distance_capped`). fn lod_distance(&self) -> u32 { + let (distance, _) = self.far_terrain_choice(); match &self.renderer { - Some(renderer) => self.settings.horizon.lod_distance_on(&renderer.info), - None => self.settings.horizon.lod_distance.min(1024), + Some(renderer) => { + horizon_client::graphics::lod_distance_capped(distance, &renderer.info) + } + None => distance.min(1024), } } /// Only enabled LOD worlds extend the renderer's range, never simulation. @@ -11233,7 +11250,7 @@ impl Game<'_> { } } fn prepare_lod(&mut self) { - let enabled = self.settings.horizon.lod_distance > 0 + let enabled = self.far_terrain_choice().0 > 0 && self.renderer.is_some() && self.player.is_some() && self.title.is_none() @@ -11330,6 +11347,7 @@ impl Game<'_> { { log::warn!("Horizon: failed to save unloaded chunks: {e}"); } + let (far_distance, far_reduced) = self.far_terrain_choice(); if let Some(renderer) = self.renderer.as_mut() { let g = &self.settings.horizon; let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0; @@ -11383,12 +11401,10 @@ impl Game<'_> { } renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z))); if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { - let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info); + let lod_distance = + horizon_client::graphics::lod_distance_capped(far_distance, &renderer.info); lod.set_near_loading(self.streaming.busy()); - lod.set_reduced_detail( - self.settings.horizon.far_detail - == horizon_client::graphics::FarDetail::Reduced, - ); + lod.set_reduced_detail(far_reduced); // The covered columns change only with the complete ones and // the render area: rebuilt then, not every frame. let at = ( diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 10faf6a81..467ea1cc0 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -31,6 +31,9 @@ impl Game<'_> { pub(super) fn mod_minimap(&self) -> Option { None } + pub(super) fn mod_far_terrain(&self) -> Option { + None + } } /// A mod's zoom (`render.set-zoom`), clamped by the runtime. @@ -51,6 +54,13 @@ pub(super) struct ModMinimap { pub(super) round: bool, } +/// A mod's far terrain (`render.set-far-terrain`), clamped by the runtime. +#[derive(Clone, Copy)] +pub(super) struct ModFarTerrain { + pub(super) distance: u32, + pub(super) reduced: bool, +} + #[cfg(feature = "mods")] impl Game<'_> { /// The main hand's stack as `input` shows it; none when it is empty. @@ -178,4 +188,12 @@ impl Game<'_> { round: m.round, }) } + /// The far terrain the first mod drawing one asks for. + pub(super) fn mod_far_terrain(&self) -> Option { + let f = self.mods.mods.far_terrain()?; + Some(ModFarTerrain { + distance: f.distance, + reduced: f.reduced, + }) + } } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 4f6f04bc0..edef7c3bc 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -216,15 +216,19 @@ pub const INTEGRATED_LOD_DISTANCE: u32 = 128; pub fn lod_capped(info: &wgpu::AdapterInfo) -> bool { info.device_type == wgpu::DeviceType::IntegratedGpu && !info.name.starts_with("Apple") } +/// A LOD distance as far terrain uses it on this adapter. +pub fn lod_distance_capped(distance: u32, info: &wgpu::AdapterInfo) -> u32 { + let distance = distance.min(1024); + if lod_capped(info) { + distance.min(INTEGRATED_LOD_DISTANCE) + } else { + distance + } +} impl Graphics { /// `lod_distance` as far terrain uses it on this adapter. pub fn lod_distance_on(&self, info: &wgpu::AdapterInfo) -> u32 { - let distance = self.lod_distance.min(1024); - if lod_capped(info) { - distance.min(INTEGRATED_LOD_DISTANCE) - } else { - distance - } + lod_distance_capped(self.lod_distance, info) } } #[derive(Clone, Debug, PartialEq)] diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index d9bb9f5c2..9c9fc1574 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -412,6 +412,23 @@ interface render { /// own frame budget; hidden, they are dropped. One map shows at a time: /// the first loaded mod's. set-minimap: func(minimap: option); + record far-terrain { + /// How far the distant terrain reaches, in chunks: 64 to 1024. On + /// integrated graphics other than Apple's the game caps it lower. + distance: u32, + /// Coarser far tiles, as the Far Detail setting's Reduced: 2 to 4 ms + /// less GPU time per frame on integrated graphics. + reduced: bool, + } + /// Draws the world beyond the render distance as distant terrain, out to + /// `distance` chunks, until the next call (none ends it). The game builds + /// it on its own workers, from the chunks already loaded or saved and, + /// where nobody has been, from the world's generator; the simulation + /// distance doesn't change. Only worlds whose generator the game has + /// (single player and a LAN world you host) show it. The player's own LOD + /// Distance setting, when on, wins. One far terrain shows at a time: the + /// first loaded mod's. + set-far-terrain: func(far-terrain: option); } /// What the game calls. Only the hooks `init` asks for are ever called. diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index bf87d0cfa..a20a413c5 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 3; +pub const LEVEL: u32 = 4; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 34] = [ +pub const FUNCTIONS: [(&str, u32); 35] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -48,6 +48,7 @@ pub const FUNCTIONS: [(&str, u32); 34] = [ ("players.broadcast", 1), ("game.raycast", 2), ("command.run-quiet", 3), + ("render.set-far-terrain", 4), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index ce48f2317..ead43a8f2 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -73,9 +73,9 @@ use render_bindings::horizon::mods::input; pub use render_bindings::horizon::mods::input::{Event as InputEvent, HeldItem, ItemUse}; /// What capability `render` asks the game to draw (WIT `interface render`). pub use render_bindings::horizon::mods::render::{ - Corner as RenderCorner, FillShape, FrameRate, ItemShape, Minimap as ModMinimap, - Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, TextShape, - Zoom as ModZoom, + Corner as RenderCorner, FarTerrain as ModFarTerrain, FillShape, FrameRate, ItemShape, + Minimap as ModMinimap, Point as RenderPoint, QuadShape, Rect as RenderRect, Shape, SpriteShape, + TextShape, Zoom as ModZoom, }; use render_bindings::{RenderHost, horizon::mods::render}; @@ -297,6 +297,8 @@ struct State { zoom: Option, /// Capability `render`'s minimap, when the mod shows one. minimap: Option, + /// Capability `render`'s far terrain, when the mod draws one. + far_terrain: Option, input: InputState, /// Capability `storage`'s folder; made on first `set`. data_dir: PathBuf, @@ -460,6 +462,7 @@ impl Mods { corner: None, zoom: None, minimap: None, + far_terrain: None, input: InputState::default(), data_dir, storage_budget: STORAGE_WRITE_BUDGET, @@ -924,6 +927,12 @@ impl Mods { .iter() .find_map(|e| e.run.as_ref()?.store.data().minimap) } + /// The far terrain the first running mod draws (capability `render`). + pub fn far_terrain(&self) -> Option { + self.entries + .iter() + .find_map(|e| e.run.as_ref()?.store.data().far_terrain) + } fn inputs(&self) -> impl Iterator { self.entries .iter() @@ -1292,6 +1301,8 @@ const TURN_MIN: f32 = 0.05; /// `set-minimap`'s side in GUI pixels and its blocks per map pixel. const MINIMAP_SIZE: (f32, f32) = (16.0, 256.0); const MINIMAP_SCALE: (f32, f32) = (0.5, 4.0); +/// `set-far-terrain`'s distance in chunks, as the LOD Distance setting's. +const FAR_TERRAIN_DISTANCE: (u32, u32) = (64, 1024); /// A mod's corner panel: shapes in a `width` × `height` box the game /// places in `corner`, stacked with the other overlays. @@ -1381,6 +1392,14 @@ impl render::Host for State { ..m }); } + fn set_far_terrain(&mut self, far_terrain: Option) { + self.far_terrain = far_terrain.map(|f| ModFarTerrain { + distance: f + .distance + .clamp(FAR_TERRAIN_DISTANCE.0, FAR_TERRAIN_DISTANCE.1), + ..f + }); + } fn frame_stats(&mut self) -> FrameRate { let (fps, min, low) = self.snapshot.frame; FrameRate { fps, min, low } diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index c6b835f10..701968781 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -252,7 +252,7 @@ experimental = ["ui", "render", "input"] needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 }; assert_eq!(level("coords_hud.hmod"), 0); - // The UI guest shows a minimap (`render.set-minimap`). + // The UI guest draws far terrain (`render.set-far-terrain`). assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); } @@ -722,6 +722,21 @@ fn render_minimap_is_clamped_and_hidden() { assert_eq!(map(&mut mods, "off"), None); } +#[test] +fn render_far_terrain_is_clamped_and_ended() { + let mut mods = load("horizon_mods_test_ui_guest.hmod"); + let far = |mods: &mut Mods, args: &str| { + assert!(mods.command(&format!("far_terrain {args}"))); + mods.far_terrain().map(|f| (f.distance, f.reduced)) + }; + assert!(mods.far_terrain().is_none()); + assert_eq!(far(&mut mods, "256 1"), Some((256, true))); + // The distance is clamped to LOD Distance's 64 to 1024 chunks. + assert_eq!(far(&mut mods, "8 0"), Some((64, false))); + assert_eq!(far(&mut mods, "99999 0"), Some((1024, false))); + assert_eq!(far(&mut mods, "off"), None); +} + /// `game.raycast`: the view's hit the game worked out, up to the distance /// asked for; the game works it out only while a mod imports the call. #[test] diff --git a/crates/horizon-mods/tests/ui_guest/src/lib.rs b/crates/horizon-mods/tests/ui_guest/src/lib.rs index 74fb64350..f3ab0f6af 100644 --- a/crates/horizon-mods/tests/ui_guest/src/lib.rs +++ b/crates/horizon-mods/tests/ui_guest/src/lib.rs @@ -99,6 +99,7 @@ impl Mod for Guest { "input_wheel", "zoom", "minimap", + "far_terrain", "raycast", "quiet", "quiet_many", @@ -222,6 +223,15 @@ impl Mod for Guest { }); render::set_minimap(map); } + // `far_terrain off`, or `far_terrain DISTANCE REDUCED`. + "far_terrain" => { + let words: Vec<&str> = args.split(' ').collect(); + let far = (args != "off").then(|| render::FarTerrain { + distance: words.first().and_then(|w| w.parse().ok()).unwrap_or(0), + reduced: words.get(1) == Some(&"1"), + }); + render::set_far_terrain(far); + } "quiet" => command::run_quiet(&args.split(';').map(str::to_owned).collect::>()), "quiet_many" => { let n: usize = args.parse().unwrap_or(0); diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index c44f27576..c9409b7e4 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -426,6 +426,13 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `rotate` | `bool` | The map turns with the player, who faces up, and an N on its rim marks north. Otherwise north is up and the player's arrow turns. | | `round` | `bool` | Round, the corners left clear; otherwise square. | +### record `far-terrain` + +| Field | Type | | +| --- | --- | --- | +| `distance` | `u32` | How far the distant terrain reaches, in chunks: 64 to 1024. On integrated graphics other than Apple's the game caps it lower. | +| `reduced` | `bool` | Coarser far tiles, as the Far Detail setting's Reduced: 2 to 4 ms less GPU time per frame on integrated graphics. | + | Function | Signature | What it does | | --- | --- | --- | | `set-hud` | `func(shapes: list)` | Replaces the mod's HUD shapes: up to 1024, drawn every frame in order over the HUD (after the hotbar, under chat and screens), hidden with the HUD (F1). An empty list removes them. | @@ -437,6 +444,7 @@ Any four-cornered shape (a wheel's segment, an arrow): the corners in order roun | `frame-stats` | `func() -> frame-rate` | The game's frame counter, recomputed twice a second. | | `set-zoom` | `func(zoom: zoom)` | Zooms the camera until the next call (`factor` 1 ends it), only while playing: a screen opening or the spyglass's own view (which wins) leave the camera vanilla's. With several mods, the strongest zoom counts. | | `set-minimap` | `func(minimap: option)` | Shows a map of the world around the player in `corner`, stacked with the game's overlays and the mods' panels, until the next call (none hides it). It looks like a map item: vanilla's map colours with their height shading and water depth, and the player's arrow. Underground, under a roof and in the Nether it maps the floor around the player's height. The game keeps the map's tiles and refreshes them within its own frame budget; hidden, they are dropped. One map shows at a time: the first loaded mod's. | +| `set-far-terrain` | `func(far-terrain: option)` | Draws the world beyond the render distance as distant terrain, out to `distance` chunks, until the next call (none ends it). The game builds it on its own workers, from the chunks already loaded or saved and, where nobody has been, from the world's generator; the simulation distance doesn't change. Only worlds whose generator the game has (single player and a LAN world you host) show it. The player's own LOD Distance setting, when on, wins. One far terrain shows at a time: the first loaded mod's. | ## `events` diff --git a/docs/api/stability.md b/docs/api/stability.md index df2c1aeb3..f65bafa55 100644 --- a/docs/api/stability.md +++ b/docs/api/stability.md @@ -38,7 +38,7 @@ don't import it); faster, or fixing behaviour to what the reference already says A new WIT function doesn't break older mods, but a mod that calls it can't run on a Horizon from before it. So every function the game offers mods has an **API level**, the one it arrived at (`crates/horizon-mods/src/api_level.rs`): -level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`. A mod needs the level of +level 0 is the contract of Horizon 0.2.67 to 0.2.69, level 1 adds `render.set-minimap` and server mods' `players`, level 2 `game.raycast`, level 3 `command.run-quiet`, level 4 `render.set-far-terrain`. A mod needs the level of the newest function it imports (a component imports only the functions it calls). The level is read from the file, never declared: @@ -134,3 +134,8 @@ Deprecations and breaking changes are in bold. The release notes of the game rel for a map image costs too much through hook calls, so the game keeps the tiles (vanilla's map colours) and the mod picks the corner, side, scale and shape. One map shows at a time, the first loaded mod's. It is a new function and a new type, so mods built before it keep loading. +- **`render.set-far-terrain`** turns on the game's own distant terrain, not one a mod builds: sampling the generator + and meshing thousands of far tiles runs on the game's workers within its frame and upload budgets, which no hook + call could match. The mod picks the distance (64 to 1024 chunks, capped lower on integrated graphics as LOD Distance + is) and Far Detail's Reduced. The player's own LOD Distance, when on, wins; one far terrain shows at a time, the + first loaded mod's. diff --git a/docs/graphics.md b/docs/graphics.md index dcba29773..bebd8a7f6 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -47,7 +47,7 @@ Coverage and detail improve progressively; a large selected radius does not mean Ordinary Overworld atmospheric fog extends with the selected LOD distance. Fog Off disables distance haze at large ranges too; fluid, darkness and boss fog retain their limits. -The setting is stored as `lodDistance` in `horizon-graphics.txt`; `0` disables it. Existing `renderDistance` in `options.txt` keeps its normal meaning for full chunks. +The setting is stored as `lodDistance` in `horizon-graphics.txt`; `0` disables it. The official Far View mod (`mods/official/far-view`, [mods.md](mods.md)) turns the same distant terrain on from the mod browser, with its own distance and detail; the setting, when on, wins. Existing `renderDistance` in `options.txt` keeps its normal meaning for full chunks. Not implemented: anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless). diff --git a/docs/mods.md b/docs/mods.md index a68b6d123..3e4fcc53c 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -15,7 +15,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage, command, ui; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mods | `crates/horizon-mod-sdk/examples/coords-hud`, `examples/predator-missile` | coordinates, facing and time HUD, `/where`, `/coords`; `/missile`, a guided missile from vanilla commands | -| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap | +| Horizon's official mods | `mods/official/` | the extras moving to the registry: FPS Counter (`fps-overlay`), Keystrokes, Zoom, Minimap; Far View (`far-view`), distant terrain | | Runtime | `crates/horizon-mods` | wasmtime 48 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new [--template code\|content] / build / run / test / check`, and the registry's CI (`registry build / review / list`) | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | @@ -89,7 +89,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | `command` | `command` | `run(line)`: a vanilla command run as the player, with the player's permissions, after the hook returns (8 per call); mods' own commands are not run. `run-quiet(lines)`: up to 256 a call, the same rights, nothing in the chat (single player and Horizon's servers run them 64 a tick and log one line a batch; elsewhere they go as chat commands and their feedback shows) | | `ui` | `ui` | `open-screen`, `close-screen`, `set-settings`: a screen the mod owns and a page in Options > Mods, of text, button, item and list widgets the game lays out and draws with its own menus' code. **Experimental:** the manifest needs `experimental = ["ui"]` | -| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | +| `render` | `render` | `set-hud(shapes)`: up to 1024 fills, four-cornered shapes, GUI sprites, items and text, kept on the HUD (over the hotbar, under chat and screens, hidden with F1) until replaced; `set-corner(corner, w, h, shapes)`: a box the game places in a corner, stacked with its overlays and other panels, as `hud`'s panels are; `text-width(text)`; `frame-stats()`: the game's FPS, min and 1% low; `gui-size()`; `shake(strength, seconds)`: the view turns, the player doesn't, scaled by Distortion Effects; `set-zoom(zoom)`: the field of view divided by up to 10, eased or at once, with slower turning, while playing and not through a spyglass (the strongest of several mods' zooms counts); `set-minimap(minimap)`: a map of the world around the player in a corner, as a map item colours it (the floor underground and under roofs), square or round, turning with the player or north up, with the player's arrow; the game keeps its tiles within its own frame budget (one map at a time, the first loaded mod's); `set-far-terrain(far-terrain)`: the world past the render distance as distant terrain, out to 64 to 1024 chunks, built by the game's own workers (the player's LOD Distance, when on, wins; the first loaded mod's). The game's own HUD renderer draws them: a mod never supplies shader code. **Experimental:** `experimental = ["render"]` | | `input` | `input` | `claim-items(ids)`: the use button on those items is the mod's (`use-start`, `use-stop` with the ticks held; the game doesn't place, eat or swing); `register-key(name, label, key)`: up to 16 keys (`key.keyboard.r`), heard while playing as `key-down` / `key-up` (the game's own mapping on that key still runs; a screen opening lets held keys up), mouse buttons as `key.mouse.4`. The player rebinds them on the mod's page in Options > Mods, where the game lists them first as Key Binds rows (click, then press a key or mouse button; Esc binds none), even for a mod without `ui`; the choice is kept in `horizon-mods.txt` (`key..:key.keyboard.z`) and wins over `register-key`'s default; `claim-wheel(on)`: the wheel's steps become `wheel` events and the hotbar doesn't move (the one input a mod takes from the game; a mod's keys never do); `held()`; `mapping(name)`: a movement or click mapping's key label and whether it is held; `clicks-per-second()`; `poll()` returns the events, at most 256 kept. **Experimental:** `experimental = ["input"]` | | Hook (export) | When | @@ -569,6 +569,7 @@ so the same rustc and `Cargo.lock` give the same file. | Keystrokes | `keystrokes` | Extras > Keystrokes | `corner`: as above, default `top_left`; `cps`: `true` (default), `false` | | Zoom | `zoom` | Extras > Zoom | `level`: `2`, `3`, `4` (default), `6`, `8`, `10`; `smooth`: `true` (default), `false`; `sensitivity` (slower turning): `true` (default), `false`. The key is the game's: `key.zoom.zoom` in `horizon-mods.txt`, default `key.keyboard.z` | | Minimap | `minimap` | Extras > Minimap | `corner`: as above, default `top_right`; `size`: `64`, `96` (default), `128`; `shape`: `square` (default), `round`; `zoom` (blocks per pixel): `0.5`, `1` (default), `2`, `4`; `rotate`: `false` (default), `true`. The game draws the map (`render.set-minimap`) | +| Far View | `far_view` | Graphics > LOD Distance and Far Detail | `distance` (chunks): `64`, `128`, `256` (default), `512`, `1024`; `detail`: `full` (default), `reduced`. The game builds and draws the distant terrain (`render.set-far-terrain`); the player's LOD Distance, when on, wins | ## Versions and compatibility diff --git a/mods/official/far-view/Cargo.toml b/mods/official/far-view/Cargo.toml new file mode 100644 index 000000000..965ee0bb4 --- /dev/null +++ b/mods/official/far-view/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "far-view" +version = "1.0.0" +edition.workspace = true +license.workspace = true +publish = false +description = "Horizon's official far view: distant terrain past the render distance." + +[lib] +crate-type = ["cdylib"] + +[dependencies] +horizon-mod-sdk = { path = "../../../crates/horizon-mod-sdk" } + +[lints] +workspace = true diff --git a/mods/official/far-view/horizon-mod.toml b/mods/official/far-view/horizon-mod.toml new file mode 100644 index 000000000..5070f897c --- /dev/null +++ b/mods/official/far-view/horizon-mod.toml @@ -0,0 +1,9 @@ +id = "far_view" +name = "Far View" +version = "1.0.0" +description = "See much farther: the world past your render distance drawn as simplified distant terrain, out to 1024 chunks, without loading or simulating more chunks." +authors = ["Horizon"] +api = "0.1" +side = "client" +capabilities = ["render", "ui", "storage"] +experimental = ["render", "ui"] diff --git a/mods/official/far-view/src/lib.rs b/mods/official/far-view/src/lib.rs new file mode 100644 index 000000000..e5b92e590 --- /dev/null +++ b/mods/official/far-view/src/lib.rs @@ -0,0 +1,89 @@ +//! Horizon's official far view: the world past the render distance drawn as +//! distant terrain (`render.set-far-terrain`; the game builds the tiles on +//! its own workers). Its settings page picks how far it reaches and the far +//! tiles' detail, kept in the mod's storage (`distance`, `detail`). The +//! player's own LOD Distance setting, when on, wins over the mod. +use horizon_mod_sdk::{ + Mod, Registration, + render::{self, FarTerrain}, + storage, + ui::{self, ButtonWidget, Widget}, +}; + +/// Distances in chunks, as LOD Distance offers them. +const DISTANCES: [u32; 5] = [64, 128, 256, 512, 1024]; +/// Settings page buttons. +const DISTANCE_BUTTON: u32 = 1; +const DETAIL_BUTTON: u32 = 2; + +/// An index into [`DISTANCES`] and Far Detail's Reduced. +struct FarView { + distance: usize, + reduced: bool, +} + +impl FarView { + fn show(&self) { + render::set_far_terrain(Some(FarTerrain { + distance: DISTANCES[self.distance], + reduced: self.reduced, + })); + } + fn page(&self) { + let button = |id, label: String| Widget::Button(ButtonWidget { id, label }); + ui::set_settings(&[ + button( + DISTANCE_BUTTON, + format!("Distance: {} chunks", DISTANCES[self.distance]), + ), + button( + DETAIL_BUTTON, + format!( + "Far detail: {}", + if self.reduced { "Reduced" } else { "Full" } + ), + ), + ]); + } + fn save(&self) { + let _ = storage::set("distance", DISTANCES[self.distance].to_string().as_bytes()); + let _ = storage::set("detail", if self.reduced { b"reduced" } else { b"full" }); + } +} + +fn stored(key: &str) -> Option { + storage::get(key) + .and_then(|v| String::from_utf8(v).ok()) + .map(|v| v.trim().to_owned()) +} + +impl Mod for FarView { + fn init() -> Result<(Self, Registration), String> { + // 256 chunks and full detail, as the docs suggest; an unknown value + // keeps the default. + let far = FarView { + distance: stored("distance") + .and_then(|v| DISTANCES.iter().position(|d| d.to_string() == v)) + .unwrap_or(2), + reduced: stored("detail").as_deref() == Some("reduced"), + }; + far.show(); + far.page(); + Ok((far, Registration::new())) + } + fn ui_select(&mut self, id: u32, _row: u32) { + match id { + DISTANCE_BUTTON => self.distance = (self.distance + 1) % DISTANCES.len(), + DETAIL_BUTTON => self.reduced = !self.reduced, + _ => return, + } + self.save(); + self.show(); + self.page(); + } + fn ui_settings_opened(&mut self) { + self.page(); + } +} + +horizon_mod_sdk::export_mod!(FarView); From 6af81b600f6001f9e7ce25b549028f08fb106926 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 01:01:31 +0500 Subject: [PATCH 084/195] Push entities with moving pistons Move players, mobs and common objects when piston block entities advance, applying collision and the per-tick piston limit. Exercise host, guest, inventory-open and mob pushes in both single-player paths, and compare the push geometry with vanilla. Co-Authored-By: Codex (GPT-6) --- crates/horizon-client/src/collisions.rs | 47 +- crates/horizon-client/src/game.rs | 28 +- crates/horizon-client/src/game/minecarts.rs | 2 +- .../horizon-client/src/game/moving_pistons.rs | 4 +- crates/horizon-client/src/game/piston_push.rs | 479 ++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 2 + crates/horizon-client/src/mobs.rs | 4 + crates/horizon-client/src/motion.rs | 14 +- crates/horizon-client/src/world.rs | 5 +- crates/horizon-world/examples/probe/main.rs | 2 + .../examples/probe/piston_push_fixture.rs | 163 ++++++ crates/horizon-world/src/level/pistons.rs | 18 +- crates/horizon-world/src/level/ticks.rs | 6 + crates/horizon-world/src/lib.rs | 1 + crates/horizon-world/src/piston_push.rs | 461 +++++++++++++++++ .../parity/VanillaPistonPushOracle.java | 78 +++ tools/lan_e2e.py | 57 ++- tools/test_piston_push_parity.py | 193 +++++++ 18 files changed, 1542 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client/src/game/piston_push.rs create mode 100644 crates/horizon-world/examples/probe/piston_push_fixture.rs create mode 100644 crates/horizon-world/src/piston_push.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java create mode 100644 tools/test_piston_push_parity.py diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 7c32bd829..9ec271b27 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -54,6 +54,27 @@ fn strider_liquid_shape() -> VoxelShape { VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column") } +// Vanilla scopes this direction to Entity.move while a piston pushes it. +thread_local! { + static PISTON_NOCLIP: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Suppress the moving part of pistons moving in this direction during a push. +pub fn with_piston_noclip( + direction: horizon_core::geometry::Direction, + f: impl FnOnce() -> T, +) -> T { + struct Reset(Option); + impl Drop for Reset { + fn drop(&mut self) { + PISTON_NOCLIP.with(|value| value.set(self.0)); + } + } + let previous = PISTON_NOCLIP.with(|value| value.replace(Some(direction))); + let _reset = Reset(previous); + f() +} + pub struct SceneCollisions<'w, 'r> { pub world: &'w World, pub binding: &'w BlockCollisionRegistry<'r>, @@ -324,7 +345,7 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { return Ok(None); }; pistons - .collision_shape(self, p, piston, None) + .collision_shape(self, p, piston, PISTON_NOCLIP.with(|value| value.get())) .map(Some) .map_err(io::Error::other) } @@ -475,3 +496,27 @@ impl PowderSnowWorld for LookupCollisions<'_, '_> { Ok(false) } } + +#[cfg(test)] +mod piston_noclip_tests { + use super::*; + use horizon_core::geometry::Direction; + + #[test] + fn piston_noclip_is_scoped_and_restored_after_unwind() { + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + with_piston_noclip(Direction::East, || { + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + let _ = + std::panic::catch_unwind(|| with_piston_noclip(Direction::West, || panic!("test"))); + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + }); + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..cffafb7d3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -127,6 +127,7 @@ mod persist; mod perspective; mod pickups; mod piglins; +mod piston_push; mod player_equip; mod postprocess; mod potions; @@ -2821,20 +2822,29 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + // `PistonMovingBlockEntity.tick` pushes what its block just ran into, + // with the progress it is about to take. + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); + self.process_level_events()?; self.sync_moving_pistons(); - self.process_level_events() + Ok(()) } /// Copies the moving-piston block entities into the world, where the /// collision queries and the renderer read them. fn sync_moving_pistons(&mut self) { - let pistons = &mut self.world.moving_pistons; - pistons.clear(); - pistons.extend( - self.block_ticks - .moving_pistons - .iter() - .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), - ); + let previous = std::mem::take(&mut self.world.moving_pistons); + let current: Vec<_> = self + .block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())) + .collect(); + self.world.moving_piston_fallback = previous + .into_iter() + .filter(|(pos, _)| !current.iter().any(|(next, _)| next == pos)) + .collect(); + self.world.moving_pistons = current; } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..58e1a2690 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -73,7 +73,7 @@ pub(super) struct Minecart { pub yaw: f32, pub previous_yaw: f32, pub flipped: bool, - on_ground: bool, + pub(super) on_ground: bool, horizontal_collision: bool, fall_distance: f64, pub hurt_time: i32, diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs index 17247850e..e1bdf89d0 100644 --- a/crates/horizon-client/src/game/moving_pistons.rs +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -14,7 +14,9 @@ impl Game<'_> { out: &mut Vec, ) { let partial = alpha as f32; - for &(p, piston) in &self.world.moving_pistons { + let mut states = self.world.moving_pistons.clone(); + states.extend(self.world.moving_piston_fallback.iter().copied()); + for (p, piston) in states { let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { continue; }; diff --git a/crates/horizon-client/src/game/piston_push.rs b/crates/horizon-client/src/game/piston_push.rs new file mode 100644 index 000000000..9c3eebb50 --- /dev/null +++ b/crates/horizon-client/src/game/piston_push.rs @@ -0,0 +1,479 @@ +//! `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` for +//! the entities the game moves itself: the players and the mobs. +//! +//! The geometry is in [`horizon_world::piston_push`]; this file supplies the +//! bodies and applies the movement the way `Entity.move(MoverType.PISTON, …)` +//! does: limited to 0.51 blocks per tick per axis (`Entity.limitPistonMovement`), +//! then run through the block collision scan, so a pushed entity stops at a +//! wall instead of passing through it. +//! +use super::Game; +use horizon_client::collisions::{SceneCollisions, with_piston_noclip}; +use horizon_core::geometry::{Aabb, Direction, Vec3}; +use horizon_core::position::BlockPos; +use horizon_world::{level::pistons::MovingPiston, piston_movement::PistonMovement, piston_push}; + +/// What one piston asks for this tick: where it is, its state, and the progress +/// `moveCollidedEntities` runs at (before the tick stores it). +pub(super) type Push = (BlockPos, MovingPiston, f32); + +/// Which entity was pushed, so its storage can be reached after the world +/// borrow ends. +#[derive(Clone, Copy, Hash, PartialEq, Eq)] +enum Target { + Player, + Guest(u32), + Mob(usize), + Item(usize), + Boat(usize), + Cart(usize), + ArmorStand(usize), +} + +/// `Entity.getStepHeight` of each body, read before the push. +struct StepHeights { + player: f32, + guests: std::collections::HashMap, +} + +/// What the push needs from one entity. +#[derive(Clone, Copy)] +struct Body { + bounds: Aabb, + position: Vec3, + on_ground: bool, + step_height: f32, + /// Standing on the piston's own block (`Entity.isSupportedBy`). + supported: bool, +} + +impl Game<'_> { + /// Push whatever this tick's moving pistons ran into, in the order the + /// pistons ticked: vanilla pushes from each block entity's own tick. + pub(super) fn push_piston_entities(&mut self, pushes: Vec) { + let mut accumulators = std::collections::HashMap::new(); + for push in pushes { + self.push_for_piston(push, &mut accumulators); + } + } + + fn push_for_piston( + &mut self, + (pos, piston, new_progress): Push, + accumulators: &mut std::collections::HashMap, + ) { + let delta_progress = f64::from(new_progress - piston.progress); + if delta_progress <= 0.0 { + return; + } + let Some(bindings) = self.collision.pistons() else { + return; + }; + let Ok(state) = bindings.collision_related_state(piston.shape_state()) else { + return; + }; + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + let Ok(shape) = self + .collision + .collision_shape(&mut scene, state, [pos.x, pos.y, pos.z]) + else { + return; + }; + if shape.is_empty() { + return; + } + let movement = piston.movement_direction(); + let boxes: Vec = shape.boxes().to_vec(); + let facts = self.res.facts(); + let slime = &*facts.get(piston.moved_state).name == "minecraft:slime_block"; + let honey = &*facts.get(piston.moved_state).name == "minecraft:honey_block"; + // `moveStuckEntities` asks the moved state's own top for its box. + let sticky_top = if honey { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape(&mut scene, piston.moved_state, [pos.x, pos.y, pos.z]) + .ok() + .and_then(|s| s.bounds()) + .map_or(0.0, |b| b.max_position().y) + } else { + 0.0 + }; + + let steps = self.push_step_heights(); + let search = shape.bounds().map(|bounds| { + piston_push::movement_search_area( + piston_push::move_by_position_and_progress(pos, bounds, piston.shape_state()), + movement, + delta_progress, + ) + }); + let targets = self.push_targets(); + for &target in &targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + let amount = piston_push::collided_amount( + &boxes, + pos, + piston.shape_state(), + new_progress, + movement, + body.bounds, + ); + if slime && search.is_some_and(|area| area.intersects(body.bounds)) { + self.bounce(target, movement); + } + if amount > 0.0 { + let step = piston_push::step_vector(movement); + let before = body.bounds; + self.move_pushed( + target, + before, + body.step_height, + body.on_ground, + step.scale(amount), + movement, + accumulators, + ); + // `fixEntityWithinPistonBase`: a retracting source piston drags + // an entity that is still inside its own block. + if !piston.extending + && piston.source + && let Some(after) = self.push_body(target, pos, &steps) + && let Some(fix) = piston_push::fix_within_piston_base( + pos, + after.bounds, + movement, + delta_progress, + ) + { + let back = piston_push::step_vector(movement.opposite()); + self.move_pushed( + target, + after.bounds, + after.step_height, + after.on_ground, + back.scale(fix), + movement, + accumulators, + ); + } + } + } + // Vanilla selects honey passengers after all collided entities have moved. + if honey && movement.normal()[1] == 0 { + let area = piston_push::sticky_area(pos, piston.shape_state(), sticky_top); + for target in targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + if piston_push::sticky_entity_selected( + area, + body.bounds, + horizon_world::level::data::PushReaction::PushPull, + body.on_ground, + body.supported, + body.position, + ) { + self.move_pushed( + target, + body.bounds, + body.step_height, + body.on_ground, + piston_push::step_vector(movement).scale(delta_progress), + movement, + accumulators, + ); + } + } + } + } + + /// `Entity.getStepHeight` for each body, read once: the attribute lookup + /// needs the mutable body, and the push only needs the number. + fn push_step_heights(&mut self) -> StepHeights { + let player = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + let mut guests = std::collections::HashMap::new(); + if let Some(host) = self.lan.as_mut() { + for g in &mut host.hub.guests { + let step = g + .motion + .as_mut() + .and_then(|m| m.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + guests.insert(g.conn, step); + } + } + StepHeights { player, guests } + } + + /// The entities a moving block can run into: the window's player, the LAN + /// guests in the level, then the mobs. + fn push_targets(&self) -> Vec { + let mut targets = Vec::new(); + if self.player.is_some() { + targets.push(Target::Player); + } + if let Some(host) = self.lan.as_ref() { + targets.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| Target::Guest(g.conn)), + ); + } + targets.extend((0..self.mobs.len()).map(Target::Mob)); + targets.extend((0..self.dropped.len()).map(Target::Item)); + targets.extend((0..self.boats.len()).map(Target::Boat)); + targets.extend((0..self.carts.len()).map(Target::Cart)); + targets.extend((0..self.armor_stands.len()).map(Target::ArmorStand)); + targets + } + + /// What the push needs from one entity, or `None` when it is not pushed: + /// removed, dead, a spectator, or an armor-stand marker. + fn push_body(&self, target: Target, pos: BlockPos, steps: &StepHeights) -> Option { + let at = [pos.x, pos.y, pos.z]; + match target { + Target::Player => { + let p = self.player.as_ref()?; + if p.spectator { + return None; + } + Some(Body { + bounds: p.bounds(), + position: p.position, + on_ground: p.ground.on_ground, + step_height: steps.player, + supported: p.ground.supporting_block == Some(pos), + }) + } + Target::Guest(conn) => { + let host = self.lan.as_ref()?; + let g = host.hub.guests.iter().find(|g| g.conn == conn)?; + if g.dead || g.game_mode == 3 { + return None; + } + let p = g.position; + Some(Body { + bounds: Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + 1.8, p[2] + 0.3), + ), + position: Vec3::new(p[0], p[1], p[2]), + on_ground: g.on_ground, + step_height: steps.guests.get(&conn).copied().unwrap_or(0.6), + supported: g + .motion + .as_ref() + .is_some_and(|m| m.ground.supporting_block == Some(pos)), + }) + } + Target::Mob(i) => { + let m = &self.mobs[i]; + if m.removed || !m.alive() { + return None; + } + Some(Body { + bounds: m.bounds(), + position: m.position, + on_ground: m.on_ground, + step_height: m.kind.step_height as f32, + supported: m.supporting == Some(at), + }) + } + Target::Item(i) => { + let entity = &self.dropped[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Boat(i) => { + let entity = &self.boats[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Cart(i) => { + let entity = &self.carts[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::ArmorStand(i) => { + let entity = &self.armor_stands[i]; + if entity.marker { + return None; + } + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + } + } + + /// `Entity.move(MoverType.PISTON, movement)` for one pushed entity: the + /// per-tick piston limit, then the block collision scan. + fn move_pushed( + &mut self, + target: Target, + before: Aabb, + step_height: f32, + on_ground: bool, + movement: Vec3, + piston_direction: Direction, + accumulators: &mut std::collections::HashMap, + ) { + let Some(limited) = self.limit_piston(target, movement, accumulators) else { + return; + }; + // `limitPistonMovement` returns zero once the tick's budget is spent. + if limited == Vec3::ZERO { + return; + } + let resolved = with_piston_noclip(piston_direction, || { + SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + } + .resolve(before, limited, step_height, on_ground) + .unwrap_or(Vec3::ZERO) + }); + if resolved.length_squared() <= 1.0e-7 + && limited.length_squared() - resolved.length_squared() >= 1.0e-7 + { + return; + } + self.apply_push(target, resolved); + } + + /// `Entity.limitPistonMovement`: each axis may travel at most 0.51 blocks + /// per game tick, and a move touches only its first non-zero axis. + fn limit_piston( + &mut self, + target: Target, + movement: Vec3, + accumulators: &mut std::collections::HashMap, + ) -> Option { + let time = self.world.game_time; + let limit = |state: &mut PistonMovement| state.limit(movement, || Ok::(time)).ok(); + match target { + Target::Player => { + let p = self.player.as_mut()?; + limit(&mut p.piston) + } + Target::Guest(conn) => { + let host = self.lan.as_mut()?; + let g = host.hub.guests.iter_mut().find(|g| g.conn == conn)?; + limit(&mut g.motion.as_deref_mut()?.piston) + } + Target::Mob(i) => limit(&mut self.mobs[i].piston), + _ => limit(accumulators.entry(target).or_default()), + } + } + + fn apply_push(&mut self, target: Target, movement: Vec3) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.position = p.position.add_vector(movement); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + { + // The body and the hub's copy of its position move together: + // `leave_guest` writes the body back over the hub's. + for (slot, delta) in g.position.iter_mut().zip(movement.components()) { + *slot += delta; + } + if let Some(m) = g.motion.as_deref_mut() { + m.position = m.position.add_vector(movement); + } + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.position = m.position.add_vector(movement); + } + Target::Item(i) => { + self.dropped[i].position = self.dropped[i].position.add_vector(movement) + } + Target::Boat(i) => self.boats[i].position = self.boats[i].position.add_vector(movement), + Target::Cart(i) => self.carts[i].position = self.carts[i].position.add_vector(movement), + Target::ArmorStand(i) => { + self.armor_stands[i].position = self.armor_stands[i].position.add_vector(movement) + } + } + } + + /// `causeBounce`: a slime block sets the velocity along the movement axis. + fn bounce(&mut self, target: Target, movement: Direction) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.velocity = piston_push::bounce_velocity(movement, p.velocity); + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.velocity = piston_push::bounce_velocity(movement, m.velocity); + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(guest) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && let Some(motion) = guest.motion.as_deref_mut() + { + motion.velocity = piston_push::bounce_velocity(movement, motion.velocity); + } + } + Target::Item(i) => { + self.dropped[i].velocity = + piston_push::bounce_velocity(movement, self.dropped[i].velocity) + } + Target::Boat(i) => { + self.boats[i].velocity = + piston_push::bounce_velocity(movement, self.boats[i].velocity) + } + Target::Cart(i) => { + self.carts[i].velocity = + piston_push::bounce_velocity(movement, self.carts[i].velocity) + } + Target::ArmorStand(i) => { + self.armor_stands[i].velocity = + piston_push::bounce_velocity(movement, self.armor_stands[i].velocity) + } + } + } +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..eb7f1409c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3185,6 +3185,8 @@ impl Game<'_> { self.with_level(|b, level, ticks| { b.client_tick_block_entities(level, ticks); }); + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f4086216d..d27a13658 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -819,6 +819,9 @@ pub struct Mob { pub previous_swell: i32, pub ambient_timer: i32, pub fall_distance: f64, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this mob this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub persistent: bool, /// `CustomName` (plain text) and `CustomNameVisible`. pub custom_name: Option, @@ -1648,6 +1651,7 @@ impl Mob { // Mob.ambientSoundTime starts at 0. ambient_timer: 0, fall_distance: 0.0, + piston: Default::default(), persistent: false, random, ai: Box::default(), diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 234390e23..9e69dc235 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -223,6 +223,9 @@ pub struct PlayerMotion { pub history: MovementHistory, pub fall_distance: f64, pub stuck_multiplier: Vec3, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this entity this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub yaw: f32, pub head_yaw: f32, pub jumping: bool, @@ -428,6 +431,7 @@ impl PlayerMotion { history: MovementHistory::default(), fall_distance: 0.0, stuck_multiplier: Vec3::ZERO, + piston: Default::default(), yaw: 0.0, head_yaw: 0.0, jumping: false, @@ -1795,8 +1799,14 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { fn set_collision_flags(&mut self, value: CollisionFlags) { self.player.collision = value; } - fn limit_piston_movement(&mut self, _: Vec3) -> Result { - Err("piston movement requires a ticking entity runtime".into()) + /// `Entity.limitPistonMovement`: the per-tick 0.51-block budget shared by + /// every move on an axis. A failed game-time read leaves the accumulator + /// as it was, as native does. + fn limit_piston_movement(&mut self, movement: Vec3) -> Result { + let time = self.scene.game_time; + self.player + .piston + .limit(movement, || Ok::>(time)) } fn stuck_multiplier(&self) -> Vec3 { self.player.stuck_multiplier diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 83083eba2..00ff04ac5 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -93,11 +93,13 @@ pub struct World { pub light_log: Option>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections, + /// Moving-piston states removed during the last tick; retained until the + /// final block mesh is visible. + pub moving_piston_fallback: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, /// The moving-piston block entities of the level, by position, copied /// from the block ticks after each tick: collision and rendering read them. pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, } -/// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] pub struct Weather { pub clear_time: i32, @@ -187,6 +189,7 @@ impl World { weather: Weather::default(), block_log: None, light_log: None, + moving_piston_fallback: Vec::new(), moving_pistons: Vec::new(), pois: Default::default(), } diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index b87e5620a..56dbc8843 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -137,6 +137,7 @@ mod movement_support_fixture; mod object_open_map_fixture; mod object_open_set_fixture; mod piston_movement_fixture; +mod piston_push_fixture; mod piston_shape_fixture; mod placement_fixture; mod player_equipment_fixture; @@ -309,6 +310,7 @@ probes! { object_open_map_fixture, object_open_set_fixture, piston_movement_fixture, + piston_push_fixture, piston_shape_fixture, placement_fixture, player_equipment_fixture, diff --git a/crates/horizon-world/examples/probe/piston_push_fixture.rs b/crates/horizon-world/examples/probe/piston_push_fixture.rs new file mode 100644 index 000000000..1d40cd610 --- /dev/null +++ b/crates/horizon-world/examples/probe/piston_push_fixture.rs @@ -0,0 +1,163 @@ +//! The moving-piston push maths against the real game: `PistonMath.getMovementArea`, +//! `moveByPositionAndProgress`, `getMovement`, the `moveCollidedEntities` loop +//! over the block's own boxes, and `moveStuckEntities`' box with +//! `matchesStickyCritera`. +use crate::support::common::f64_hex; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::{level::data::PushReaction, piston_push, piston_shape::MovingPistonState}; +use serde_json::Value; +use std::{ + fs, + io::{self, BufWriter, Write}, + path::Path, +}; + +fn number(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} + +fn float(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} + +fn aabb(v: &Value) -> Aabb { + let a = v.as_array().unwrap(); + Aabb::new( + Vec3::new(number(&a[0]), number(&a[1]), number(&a[2])), + Vec3::new(number(&a[3]), number(&a[4]), number(&a[5])), + ) +} + +fn direction(index: i64) -> Direction { + Direction::ALL[index.rem_euclid(6) as usize] +} + +fn reaction(index: i64) -> PushReaction { + match index.rem_euclid(5) { + 0 => PushReaction::PushPull, + 1 => PushReaction::Push, + 2 => PushReaction::Popped, + 3 => PushReaction::Immoveable, + _ => PushReaction::IgnoreEntity, + } +} + +fn line(out: &mut impl Write, name: &str, b: Aabb) -> io::Result<()> { + let (min, max) = (b.min_position(), b.max_position()); + writeln!( + out, + "{name} {} {} {} {} {} {}", + f64_hex(min.x), + f64_hex(min.y), + f64_hex(min.z), + f64_hex(max.x), + f64_hex(max.y), + f64_hex(max.z) + ) +} + +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for text in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(text)?; + let p = &f["pos"]; + let pos = BlockPos::new( + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ); + let progress = float(&f["progress"]); + let piston = MovingPistonState { + moved_state: horizon_world::registry::BlockStateId(0), + direction: direction(f["direction"].as_i64().unwrap()), + extending: f["extending"].as_bool().unwrap(), + source: f["source"].as_bool().unwrap(), + progress, + previous_progress: progress, + }; + let new_progress = float(&f["new_progress"]); + let delta_progress = f64::from(new_progress - progress); + let movement = piston.movement_direction(); + let block_box = aabb(&f["block_box"]); + let entity = aabb(&f["entity"]); + let movement_box = aabb(&f["movement_box"]); + + writeln!( + out, + "extended {:08x}", + piston_push::extended_progress(piston, progress).to_bits() + )?; + let origin = piston_push::move_by_position_and_progress(pos, block_box, piston); + line(&mut out, "origin", origin)?; + line( + &mut out, + "area", + piston_push::movement_area(block_box, movement, delta_progress), + )?; + for (name, face) in [ + ("east", Direction::East), + ("west", Direction::West), + ("up", Direction::Up), + ("down", Direction::Down), + ("south", Direction::South), + ("north", Direction::North), + ] { + writeln!( + out, + "movement {name} {}", + f64_hex(piston_push::get_movement(movement_box, face, entity)) + )?; + } + + // `moveCollidedEntities`' loop: the furthest box reaches into the + // entity, capped at the progress delta, plus the push offset. + let boxes: Vec = f["boxes"].as_array().unwrap().iter().map(aabb).collect(); + let mut delta: f64 = 0.0; + let mut capped = false; + for block in &boxes { + let moving = piston_push::movement_area( + piston_push::move_by_position_and_progress(pos, *block, piston), + movement, + delta_progress, + ); + if moving.intersects(entity) { + delta = delta.max(piston_push::get_movement(moving, movement, entity)); + if delta >= delta_progress { + capped = true; + break; + } + } + } + let collided = if delta <= 0.0 { + 0.0 + } else { + delta.min(delta_progress) + piston_push::PUSH_OFFSET + }; + writeln!(out, "collided {} {capped}", f64_hex(collided))?; + line( + &mut out, + "search", + piston_push::movement_search_area(origin, movement, delta_progress), + )?; + let sticky = piston_push::sticky_area(pos, piston, number(&f["sticky_top"])); + line(&mut out, "sticky", sticky)?; + writeln!( + out, + "matches {}", + piston_push::matches_sticky_criteria( + sticky, + reaction(f["reaction"].as_i64().unwrap()), + f["on_ground"].as_bool().unwrap(), + f["supported"].as_bool().unwrap(), + Vec3::new(number(&f["entity_x"]), 0.0, number(&f["entity_z"])), + ) + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 45e469efd..70e8aa32a 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -182,7 +182,9 @@ impl Sim<'_, L> { self.neighbor_changed_at(pos, block); } } - /// `PistonMovingBlockEntity.tick` (entity pushing excluded). + /// `PistonMovingBlockEntity.tick`. A piston that is still moving reports + /// the push `moveCollidedEntities` would do at its new progress; the caller + /// moves the entities, because `Ticks` has none (`piston_pushes`). fn moving_piston_tick(&mut self, pos: BlockPos) { let Some(mut piston) = self.moving_piston(pos) else { return; @@ -227,14 +229,20 @@ impl Sim<'_, L> { } } } else { - piston.progress = (piston.progress + 0.5).min(1.0); - if let Some(entry) = self + // moveCollidedEntities and moveStuckEntities run with the new + // progress but read the old one off the entity (their delta), + // so the push carries the piston as it was before the advance. + let old = piston; + let new_progress = (old.progress + 0.5).min(1.0); + let current = self .ticks .moving_pistons .iter_mut() - .find(|(p, _)| *p == pos) - { + .find(|(p, _)| *p == pos); + if let Some(entry) = current { + piston.progress = new_progress; entry.1 = piston; + self.ticks.piston_pushes.push((pos, old, new_progress)); } } } diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs index c8d715623..195078e31 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -29,6 +29,11 @@ pub struct Ticks { /// Moving-piston block entities in ticker order (render and collide /// moving blocks from these; see `piston_shape`). pub moving_pistons: Vec<(BlockPos, super::pistons::MovingPiston)>, + /// The pushes this tick's moving-piston block entities asked for: each + /// piston with the progress it is about to reach, in the order they ticked + /// (`PistonMovingBlockEntity.tick`'s `moveCollidedEntities` call). The + /// caller moves entities by these; `Ticks` has no entities of its own. + pub piston_pushes: Vec<(BlockPos, super::pistons::MovingPiston, f32)>, pub(crate) next_block_entity_id: u64, /// `ServerLevel.blockEvents`, run by `Behaviours::run_block_events`. pub block_events: Vec, @@ -65,6 +70,7 @@ impl Ticks { comparator_outputs: Default::default(), torch_toggles: Vec::new(), moving_pistons: Vec::new(), + piston_pushes: Vec::new(), next_block_entity_id: 0, block_events: Vec::new(), handling_tick: false, diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index b6d05ecf6..6df870d42 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -94,6 +94,7 @@ pub mod nbt; pub mod object_open_map; pub mod object_open_set; pub mod piston_movement; +pub mod piston_push; pub mod piston_shape; pub mod player_food; pub mod player_health; diff --git a/crates/horizon-world/src/piston_push.rs b/crates/horizon-world/src/piston_push.rs new file mode 100644 index 000000000..5f64f22ba --- /dev/null +++ b/crates/horizon-world/src/piston_push.rs @@ -0,0 +1,461 @@ +//! `PistonMovingBlockEntity.moveCollidedEntities`, `moveStuckEntities` and +//! `fixEntityWithinPistonBase` over immutable geometry. +//! +//! Entity storage, the moving entities themselves and the blocks they collide +//! with belong to the caller: these functions decide *how far* an entity is +//! pushed, which is the part that must match vanilla to the bit. The movement +//! they describe is an `Entity.move(MoverType.PISTON, …)`, so the caller still +//! applies it through its own collision resolution and per-tick piston limit. +use crate::{level::data::PushReaction, piston_shape::MovingPistonState}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; + +/// `PistonMovingBlockEntity.PUSH_OFFSET`. +pub const PUSH_OFFSET: f64 = 0.01; + +/// `PistonMovingBlockEntity.getExtendedProgress`: where along its travel the +/// moved block is, in blocks (negative before it starts, 0 when it arrives). +pub fn extended_progress(piston: MovingPistonState, progress: f32) -> f32 { + if piston.extending { + progress - 1.0 + } else { + 1.0 - progress + } +} + +/// `Direction.getAxisDirection().getStep()`. +fn step_along(direction: Direction) -> i32 { + match direction { + Direction::East | Direction::Up | Direction::South => 1, + Direction::West | Direction::Down | Direction::North => -1, + } +} + +/// `Direction.getStepX/Y/Z` as a vector. +pub fn step_vector(direction: Direction) -> Vec3 { + let [x, y, z] = direction.normal(); + Vec3::new(f64::from(x), f64::from(y), f64::from(z)) +} + +/// `PistonMath.getMovementArea`: the slab an entity's box must reach into to be +/// run over by `amount` of further travel along `direction`. +pub fn movement_area(aabb: Aabb, direction: Direction, amount: f64) -> Aabb { + let delta = amount * f64::from(step_along(direction)); + let low = delta.min(0.0); + let high = delta.max(0.0); + let (min, max) = (aabb.min_position(), aabb.max_position()); + match direction { + Direction::West => Aabb::new( + Vec3::new(min.x + low, min.y, min.z), + Vec3::new(min.x + high, max.y, max.z), + ), + Direction::East => Aabb::new( + Vec3::new(max.x + low, min.y, min.z), + Vec3::new(max.x + high, max.y, max.z), + ), + Direction::Down => Aabb::new( + Vec3::new(min.x, min.y + low, min.z), + Vec3::new(max.x, min.y + high, max.z), + ), + Direction::Up => Aabb::new( + Vec3::new(min.x, max.y + low, min.z), + Vec3::new(max.x, max.y + high, max.z), + ), + Direction::North => Aabb::new( + Vec3::new(min.x, min.y, min.z + low), + Vec3::new(max.x, max.y, min.z + high), + ), + Direction::South => Aabb::new( + Vec3::new(min.x, min.y, max.z + low), + Vec3::new(max.x, max.y, max.z + high), + ), + } +} + +/// `PistonMovingBlockEntity.moveByPositionAndProgress`: a box moved to the +/// block position and on to where the moved block currently is. +pub fn move_by_position_and_progress(pos: BlockPos, aabb: Aabb, piston: MovingPistonState) -> Aabb { + let current = f64::from(extended_progress(piston, piston.progress)); + let step = step_vector(piston.direction); + aabb.move_by(Vec3::new( + f64::from(pos.x) + current * step.x, + f64::from(pos.y) + current * step.y, + f64::from(pos.z) + current * step.z, + )) +} + +/// `PistonMovingBlockEntity.getMovement`: how far `entity` stands inside the +/// block it must be pushed out of, measured along `movement`'s axis. +pub fn get_movement(block: Aabb, movement: Direction, entity: Aabb) -> f64 { + let (bmin, bmax) = (block.min_position(), block.max_position()); + let (emin, emax) = (entity.min_position(), entity.max_position()); + match movement { + Direction::East => bmax.x - emin.x, + Direction::West => emax.x - bmin.x, + Direction::Up => bmax.y - emin.y, + Direction::Down => emax.y - bmin.y, + Direction::South => bmax.z - emin.z, + Direction::North => emax.z - bmin.z, + } +} + +/// `moveCollidedEntities`' inner loop: the furthest any of the moved block's +/// boxes reaches into `entity`, capped at the progress delta, plus +/// [`PUSH_OFFSET`]. `0.0` when the block does not touch the entity. +pub fn collided_amount( + boxes: &[Aabb], + pos: BlockPos, + piston: MovingPistonState, + new_progress: f32, + movement: Direction, + entity: Aabb, +) -> f64 { + let delta_progress = f64::from(new_progress - piston.progress); + let mut delta: f64 = 0.0; + for block in boxes { + let moving = movement_area( + move_by_position_and_progress(pos, *block, piston), + movement, + delta_progress, + ); + if moving.intersects(entity) { + delta = delta.max(get_movement(moving, movement, entity)); + if delta >= delta_progress { + break; + } + } + } + if delta <= 0.0 { + return 0.0; + } + delta.min(delta_progress) + PUSH_OFFSET +} + +/// The box `level.getEntities` searches for a push: the moved block's own box +/// widened by the slab it is about to sweep. +pub fn movement_search_area(block_box: Aabb, movement: Direction, delta_progress: f64) -> Aabb { + movement_area(block_box, movement, delta_progress).union_bounds(block_box) +} + +/// `moveStuckEntities`: the box of standing entities a moving honey block drags +/// with it. `sticky_top` is the moved state's top collision height. +pub fn sticky_area(pos: BlockPos, piston: MovingPistonState, sticky_top: f64) -> Aabb { + let area = Aabb::new( + Vec3::new(0.0, sticky_top, 0.0), + Vec3::new(1.0, 1.500_001_000_000_000_1, 1.0), + ); + move_by_position_and_progress(pos, area, piston) +} + +/// `PistonMovingBlockEntity.matchesStickyCritera`. +pub fn matches_sticky_criteria( + area: Aabb, + reaction: PushReaction, + on_ground: bool, + supported_by_piston: bool, + entity_position: Vec3, +) -> bool { + if reaction != PushReaction::PushPull || !on_ground { + return false; + } + if supported_by_piston { + return true; + } + let (min, max) = (area.min_position(), area.max_position()); + entity_position.x >= min.x + && entity_position.x <= max.x + && entity_position.z >= min.z + && entity_position.z <= max.z +} + +/// The level query intersects the sticky box before applying the predicate. +pub fn sticky_entity_selected( + area: Aabb, + bounds: Aabb, + reaction: PushReaction, + on_ground: bool, + supported_by_piston: bool, + position: Vec3, +) -> bool { + area.intersects(bounds) + && matches_sticky_criteria(area, reaction, on_ground, supported_by_piston, position) +} + +/// `fixEntityWithinPistonBase`: a retracting source piston drags an entity that +/// is still inside the piston's own block out along the opposite of `movement`. +/// The returned distance is measured along that opposite direction. +pub fn fix_within_piston_base( + pos: BlockPos, + entity: Aabb, + movement: Direction, + delta_progress: f64, +) -> Option { + let block = Aabb::unit_cube(Vec3::from_block(pos)); + if !entity.intersects(block) { + return None; + } + let opposite = movement.opposite(); + let delta = get_movement(block, opposite, entity) + PUSH_OFFSET; + let intersected = entity.intersect(block); + let delta_intersected = get_movement(block, opposite, intersected) + PUSH_OFFSET; + // As deep inside as the block allows: it is stuck in the base itself, so it + // leaves along with the retraction. + if (delta - delta_intersected).abs() < PUSH_OFFSET { + Some(delta.min(delta_progress) + PUSH_OFFSET) + } else { + None + } +} + +/// `PistonMovingBlockEntity.getCollisionRelatedBlockState` uses the moved state +/// unless a source piston is retracting, where it shows a piston head instead. +/// The state itself comes from [`PistonBlockBindings::collision_related_state`]. +/// +/// [`PistonBlockBindings::collision_related_state`]: +/// crate::piston_shape::PistonBlockBindings::collision_related_state +pub fn uses_moved_state(piston: MovingPistonState) -> bool { + piston.extending || !piston.source +} + +/// `moveCollidedEntities`' slime bounce: a slime block sets the velocity along +/// the movement axis to that direction's step, leaving the other axes. +pub fn bounce_velocity(movement: Direction, velocity: Vec3) -> Vec3 { + let mut velocity = velocity; + match movement { + Direction::East => velocity.x = 1.0, + Direction::West => velocity.x = -1.0, + Direction::Up => velocity.y = 1.0, + Direction::Down => velocity.y = -1.0, + Direction::South => velocity.z = 1.0, + Direction::North => velocity.z = -1.0, + } + velocity +} + +/// `Entity.getPistonPushReaction() == PushReaction.IGNORE_ENTITY`. +/// +/// `Marker`, `Interaction`, `Display`, `AreaEffectCloud` and +/// `OminousItemSpawner` return `IGNORE_ENTITY`, and an armor stand does when it +/// is a marker. Horizon gives those kinds no pushed body, so a caller that has +/// no box to push never reaches the maths above; this names the predicate for +/// the kinds that do have one. +pub fn ignores_push(marker: bool) -> bool { + marker +} + +#[cfg(test)] +mod tests { + use super::*; + + fn unit() -> Aabb { + Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)) + } + + fn moving(direction: Direction, extending: bool, progress: f32) -> MovingPistonState { + MovingPistonState { + moved_state: crate::registry::BlockStateId(0), + direction, + extending, + source: false, + progress, + previous_progress: progress, + } + } + + /// `getMovementArea` puts the slab on the leading face and widens it by the + /// travel in that direction only. + #[test] + fn movement_area_sits_on_the_leading_face() { + let east = movement_area(unit(), Direction::East, 0.5); + assert_eq!(east.min_position(), Vec3::new(1.0, 0.0, 0.0)); + assert_eq!(east.max_position(), Vec3::new(1.5, 1.0, 1.0)); + + let west = movement_area(unit(), Direction::West, 0.5); + assert_eq!(west.min_position(), Vec3::new(-0.5, 0.0, 0.0)); + assert_eq!(west.max_position(), Vec3::new(0.0, 1.0, 1.0)); + + let up = movement_area(unit(), Direction::Up, 0.5); + assert_eq!(up.min_position(), Vec3::new(0.0, 1.0, 0.0)); + assert_eq!(up.max_position(), Vec3::new(1.0, 1.5, 1.0)); + + let north = movement_area(unit(), Direction::North, 0.5); + assert_eq!(north.min_position(), Vec3::new(0.0, 0.0, -0.5)); + assert_eq!(north.max_position(), Vec3::new(1.0, 1.0, 0.0)); + } + + /// A negative amount sweeps behind the leading face. + #[test] + fn movement_area_follows_a_negative_amount() { + let area = movement_area(unit(), Direction::East, -0.5); + assert_eq!(area.min_position(), Vec3::new(0.5, 0.0, 0.0)); + assert_eq!(area.max_position(), Vec3::new(1.0, 1.0, 1.0)); + } + + /// The arm of a piston at the origin: the block entity sits in the block it + /// pushes into, and at progress 0 its shape is still a block back. + const ARM: BlockPos = BlockPos::new(1, 0, 0); + + /// An entity in the way is pushed the progress delta, plus the push offset; + /// here it hangs 0.6 into the slab and the delta caps it at 0.5. + #[test] + fn a_collided_entity_moves_the_progress_delta() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(0.9, 0.0, 0.2), Vec3::new(1.5, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert!((amount - (0.5 + PUSH_OFFSET)).abs() < 1.0e-12, "{amount}"); + } + + /// The delta is not a floor: an entity barely nicking the slab moves by only + /// what it is owed, plus the offset. + #[test] + fn a_grazed_entity_moves_only_what_it_overlaps() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(1.4, 0.0, 0.2), Vec3::new(2.0, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert!((amount - (0.1 + PUSH_OFFSET)).abs() < 1.0e-12, "{amount}"); + } + + /// Clear of the block, nothing moves. + #[test] + fn an_entity_out_of_the_way_is_left_alone() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(3.0, 0.0, 0.2), Vec3::new(3.6, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert_eq!(amount, 0.0); + } + + /// A retracting base drags an entity stuck inside its own block, limited by + /// the progress delta. + #[test] + fn a_retracting_base_drags_a_stuck_entity() { + let entity = Aabb::new(Vec3::new(0.75, 0.0, 0.2), Vec3::new(1.35, 1.8, 0.8)); + let amount = fix_within_piston_base(BlockPos::new(0, 0, 0), entity, Direction::West, 0.5) + .expect("stuck in the base"); + assert!(amount > 0.0 && amount <= 0.5 + PUSH_OFFSET, "{amount}"); + } + + /// An entity outside the base's block is not dragged by it. + #[test] + fn a_free_entity_is_not_dragged_by_the_base() { + let entity = Aabb::new(Vec3::new(2.0, 0.0, 0.2), Vec3::new(2.6, 1.8, 0.8)); + assert_eq!( + fix_within_piston_base(BlockPos::new(0, 0, 0), entity, Direction::West, 0.5), + None + ); + } + + /// Honey drags only entities that stand on it and that blocks may push. + #[test] + fn honey_drags_standing_entities() { + let area = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.5, 1.0)); + let on_top = Vec3::new(0.5, 0.0, 0.5); + assert!(matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + false, + on_top + )); + assert!(!matches_sticky_criteria( + area, + PushReaction::PushPull, + false, + false, + on_top + )); + assert!(!matches_sticky_criteria( + area, + PushReaction::Immoveable, + true, + false, + on_top + )); + // Beside it: only standing on the piston's own block holds it. + let beside = Vec3::new(2.0, 0.0, 0.5); + assert!(!matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + false, + beside + )); + assert!(matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + true, + beside + )); + } + + #[test] + fn honey_selection_uses_entity_position_and_intersection() { + let area = Aabb::new(Vec3::new(0.0, 1.0, 0.0), Vec3::new(1.0, 1.5, 1.0)); + let position = Vec3::new(0.1, 1.0, 0.5); + let bounds = Aabb::new(Vec3::new(-0.2, 1.0, 0.2), Vec3::new(0.4, 2.8, 0.8)); + assert!(sticky_entity_selected( + area, + bounds, + PushReaction::PushPull, + true, + false, + position + )); + let above = bounds.move_by(Vec3::new(0.0, 3.0, 0.0)); + assert!(!sticky_entity_selected( + area, + above, + PushReaction::PushPull, + true, + true, + position + )); + } + + /// The slime bounce rewrites only the movement axis. + #[test] + fn a_slime_block_bounces_along_its_axis() { + let v = Vec3::new(0.2, -0.5, 0.3); + assert_eq!( + bounce_velocity(Direction::East, v), + Vec3::new(1.0, -0.5, 0.3) + ); + assert_eq!(bounce_velocity(Direction::Up, v), Vec3::new(0.2, 1.0, 0.3)); + assert_eq!( + bounce_velocity(Direction::North, v), + Vec3::new(0.2, -0.5, -1.0) + ); + } + + /// The moved block sits along the piston's own direction, half a block short + /// at mid-travel and in place once landed. + #[test] + fn the_moved_block_sits_along_the_piston_direction() { + let half = moving(Direction::East, true, 0.5); + let moved = move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), half); + assert_eq!(moved.min_position(), Vec3::new(1.5, 3.0, 4.0)); + + let landed = moving(Direction::East, true, 1.0); + assert_eq!( + move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), landed).min_position(), + Vec3::new(2.0, 3.0, 4.0) + ); + + // Retracting runs the other way: two thirds out at progress 1/3. + let pulling = moving(Direction::East, false, 0.5); + assert_eq!( + move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), pulling).min_position(), + Vec3::new(2.5, 3.0, 4.0) + ); + } + + /// The search area covers the block and the slab in front of it. + #[test] + fn the_search_area_covers_block_and_sweep() { + let area = movement_search_area(unit(), Direction::East, 0.5); + assert_eq!(area.min_position(), Vec3::new(0.0, 0.0, 0.0)); + assert_eq!(area.max_position(), Vec3::new(1.5, 1.0, 1.0)); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java new file mode 100644 index 000000000..f1cee2fc2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java @@ -0,0 +1,78 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.monster.zombie.Zombie; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.piston.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; +/** + * The real moving-piston push maths: PistonMath.getMovementArea, + * moveByPositionAndProgress, getMovement, the moveCollidedEntities loop over + * the block's own boxes, and moveStuckEntities' box and matchesStickyCritera. + * fixEntityWithinPistonBase is left out: it moves the entity + * (`Entity.move(MoverType.PISTON, ...)`), which needs a live level, so the + * Rust side is covered by its own unit tests. + */ +public final class VanillaPistonPushOracle { + private static float number(JsonElement v){return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(),16));} + private static double dbl(JsonElement v){return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(),16));} + private static AABB box(JsonElement v){var a=v.getAsJsonArray();return new AABB(dbl(a.get(0)),dbl(a.get(1)),dbl(a.get(2)),dbl(a.get(3)),dbl(a.get(4)),dbl(a.get(5)));} + private static void line(PrintWriter out,String name,AABB b){out.printf(name+" %016x %016x %016x %016x %016x %016x%n",Double.doubleToLongBits(b.minX),Double.doubleToLongBits(b.minY),Double.doubleToLongBits(b.minZ),Double.doubleToLongBits(b.maxX),Double.doubleToLongBits(b.maxY),Double.doubleToLongBits(b.maxZ));} + private static Field field(Class c,String name)throws Exception{var f=c.getDeclaredField(name);f.setAccessible(true);return f;} + private static Method method(Class c,String name,Class...types)throws Exception{var m=c.getDeclaredMethod(name,types);m.setAccessible(true);return m;} + @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var allocator=Class.forName("sun.misc.Unsafe");var uf=allocator.getDeclaredField("theUnsafe");uf.setAccessible(true);var unsafe=uf.get(null);var allocate=allocator.getMethod("allocateInstance",Class.class); + var progress=field(PistonMovingBlockEntity.class,"progress"); + var movedBy=method(PistonMovingBlockEntity.class,"moveByPositionAndProgress",BlockPos.class,AABB.class,PistonMovingBlockEntity.class); + var extended=method(PistonMovingBlockEntity.class,"getExtendedProgress",float.class); + var getMovement=method(PistonMovingBlockEntity.class,"getMovement",AABB.class,Direction.class,AABB.class); + var matches=method(PistonMovingBlockEntity.class,"matchesStickyCritera",AABB.class,Entity.class,BlockPos.class); + var movementDir=method(PistonMovingBlockEntity.class,"getMovementDirection"); + var position=field(Entity.class,"position");var onGroundField=field(Entity.class,"onGround");var supporting=field(Entity.class,"mainSupportingBlockPos");var bbField=field(Entity.class,"bb"); + var faces=new Direction[]{Direction.EAST,Direction.WEST,Direction.UP,Direction.DOWN,Direction.SOUTH,Direction.NORTH}; + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var v=f.getAsJsonArray("pos");var p=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()); + var direction=Direction.values()[f.get("direction").getAsInt()]; + var piston=new PistonMovingBlockEntity(p,Blocks.MOVING_PISTON.defaultBlockState(),Blocks.STONE.defaultBlockState(),direction,f.get("extending").getAsBoolean(),f.get("source").getAsBoolean()); + float current=number(f.get("progress")); + progress.setFloat(piston,current); + float newProgress=number(f.get("new_progress")); + double deltaProgress=newProgress-current; + Direction movement=(Direction)movementDir.invoke(piston); + AABB blockBox=box(f.get("block_box")); + AABB entityBox=box(f.get("entity")); + AABB movementBox=box(f.get("movement_box")); + out.printf("extended %08x%n",Float.floatToIntBits((float)extended.invoke(piston,current))); + AABB origin=(AABB)movedBy.invoke(null,p,blockBox,piston); + line(out,"origin",origin); + line(out,"area",PistonMath.getMovementArea(blockBox,movement,deltaProgress)); + for(var face:faces)out.printf("movement %s %016x%n",face.getSerializedName(),Double.doubleToLongBits((double)getMovement.invoke(null,movementBox,face,entityBox))); + double delta=0.0;boolean capped=false; + for(var value:f.getAsJsonArray("boxes")){ + AABB movingAABB=PistonMath.getMovementArea((AABB)movedBy.invoke(null,p,box(value),piston),movement,deltaProgress); + if(movingAABB.intersects(entityBox)){delta=Math.max(delta,(double)getMovement.invoke(null,movingAABB,movement,entityBox));if(delta>=deltaProgress){capped=true;break;}} + } + double collided=delta<=0.0?0.0:Math.min(delta,deltaProgress)+0.01; + out.printf("collided %016x %b%n",Double.doubleToLongBits(collided),capped); + line(out,"search",PistonMath.getMovementArea(origin,movement,deltaProgress).minmax(origin)); + AABB sticky=(AABB)movedBy.invoke(null,p,new AABB(0.0,dbl(f.get("sticky_top")),0.0,1.0,1.5000010000000001,1.0),piston); + line(out,"sticky",sticky); + boolean pushable=f.get("reaction").getAsInt()==0; + var entity=(Entity)allocate.invoke(unsafe,pushable?Zombie.class:Marker.class); + position.set(entity,new Vec3(dbl(f.get("entity_x")),0.0,dbl(f.get("entity_z")))); + bbField.set(entity,entityBox); + onGroundField.setBoolean(entity,f.get("on_ground").getAsBoolean()); + supporting.set(entity,f.get("supported").getAsBoolean()?Optional.of(p):Optional.empty()); + out.printf("matches %b%n",(boolean)matches.invoke(null,sticky,entity,p)); + } + } + } +} \ No newline at end of file diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index ab3fcde1b..4d35dd6ac 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -296,7 +296,7 @@ CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'si 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', - 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', + 'piston-push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', @@ -2368,6 +2368,59 @@ def wait_state(game, pos, key, want, ticks): return state_of(game, pos, key) +def check_piston_push(host, guest, out): + """A moving piston pushes both players and a stationary mob on each host path.""" + hx, _, hz = pos_of(host) + x, y, z = (int(hx // 16) * 16 + 8, 100, int(hz // 16) * 16 + 8) + host('command', command=f'fill {x-4} {y-1} {z-4} {x+7} {y-1} {z+4} minecraft:stone') + host('command', command=f'fill {x-4} {y} {z-4} {x+7} {y+5} {z+4} minecraft:air') + host('command', command=f'setblock {x} {y} {z} minecraft:piston[facing=east]') + results = {} + for player, name in ((host, host.player), (guest, GUEST_NAME)): + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp {"@s" if player is host else GUEST_NAME} {x+1.65} {y} {z+0.5}') + player.wait(15) + before = pos_of(player) + assert abs(before[0] - (x + 1.65)) < 0.1, f'{name} did not reach piston: {before}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + player.wait(30) + after = pos_of(player) + results[name] = after[0] - before[0] + assert results[name] > 0.3, f'piston did not push {name}: {before} -> {after}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp @s {x+1.65} {y} {z+0.5}') + host.wait(10) + host.raw('key', 'e', 'tap') + host.raw('wait-for', 'screen', 'inventory') + before = pos_of(host) + guest('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + host.wait(30) + after = pos_of(host) + results['inventory'] = after[0] - before[0] + assert results['inventory'] > 0.3, f'piston did not push player with inventory open: {before} -> {after}' + host.raw('key', 'esc', 'tap') + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'summon minecraft:pig {x+1.65} {y} {z+0.5} {{NoAI:1b}}') + host.wait(10) + pigs = host('entities', radius=16, type='pig')['entities'] + pig = min(pigs, key=lambda p: abs(p['pos'][0] - (x + 1.65)) + abs(p['pos'][2] - (z + 0.5))) + before = pig['pos'][0] + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + host.wait(30) + pigs = host('entities', radius=16, type='pig')['entities'] + after = next(p['pos'][0] for p in pigs if p['id'] == pig['id']) + results['pig'] = after - before + assert results['pig'] > 0.3, f'piston did not push pig: {before} -> {after}' + return results + + def check_plates(host, guest, out): guest('command', command='gamemode survival') x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -4679,7 +4732,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'cartography': check_cartography, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, - 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, + 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'piston-push': check_piston_push, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, diff --git a/tools/test_piston_push_parity.py b/tools/test_piston_push_parity.py new file mode 100644 index 000000000..17f1a257d --- /dev/null +++ b/tools/test_piston_push_parity.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Compare moving-piston push geometry and predicates with pinned vanilla. + +`PistonMovingBlockEntity.moveCollidedEntities` decides how far an entity is +pushed; the movement it describes is `Entity.move(MoverType.PISTON, ...)`, whose +collision and per-tick limit the game owns. This harness covers the deciding +half: the movement area, the offset block box, `getMovement` on every face, the +per-box loop, `moveStuckEntities`' box and `matchesStickyCritera`, and +`fixEntityWithinPistonBase`. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import struct +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + def f32(v): return struct.pack('>f', float(v)).hex() + def f64(v): return struct.pack('>d', float(v)).hex() + def box(values): return [f64(v) for v in values] + step = [1.0 / 3.0, 0.25, 0.5, 0.75, 1.0] + unit = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] + offsets = [[0, 0, 0], [-17, -64, 30000000], [2147483647, -2147483648, -2147483648]] + faces = [0, 1, 2, 3, 4, 5] + # Progress pairs around the 0.25/0.5/1.0 thresholds the head and the + # extended-progress offset change at. + progress = [0.0, 0.25, 0.49999997, 0.5, 0.75, 0.99999994, 1.0] + entities = [ + [0.9, 0.0, 0.2, 1.5, 1.8, 0.8], + [1.4, 0.0, 0.2, 2.0, 1.8, 0.8], + [0.75, 0.0, 0.2, 1.35, 1.8, 0.8], + [3.0, 0.0, 0.2, 3.6, 1.8, 0.8], + [0.49, 0.0, 0.49, 0.51, 1.8, 0.51], + [0.0, 1.0, 0.0, 1.0, 2.8, 1.0], + ] + for index, position in enumerate(offsets): + for direction in faces: + for extending in (False, True): + for source in (False, True): + for current in progress: + advanced = min(current + 0.5, 1.0) + for entity in entities: + yield { + 'pos': position, + 'direction': direction, + 'extending': extending, + 'source': source, + 'progress': f32(current), + 'new_progress': f32(advanced), + 'block_box': box(unit), + 'movement_box': box(unit), + 'entity': box(entity), + 'boxes': [box(unit)], + 'sticky_top': f64(0.0), + 'reaction': 0, + 'on_ground': True, + 'supported': False, + 'entity_x': f64(entity[0]), + 'entity_z': f64(entity[2]), + } + # Split boxes, a retracting honey drag with every push reaction, and the + # predicate's supported/on-ground corners. + for index in range(4000): + rng = random.Random(0x50555348 + index) + current = rng.choice(progress) + advanced = min(current + 0.5, 1.0) + count = rng.randint(1, 4) + boxes = [] + for _ in range(count): + low = [rng.choice([0.0, 0.25, 0.5]), rng.choice([0.0, 0.5]), rng.choice([0.0, 0.5])] + high = [min(v + rng.choice([0.25, 0.5, 1.0]), 1.0) for v in low] + boxes.append(box(low + high)) + yield { + 'pos': rng.choice(offsets), + 'direction': rng.randrange(6), + 'extending': rng.random() < 0.5, + 'source': rng.random() < 0.5, + 'progress': f32(current), + 'new_progress': f32(advanced), + 'block_box': boxes[0], + 'movement_box': boxes[rng.randrange(len(boxes))], + 'entity': box([ + rng.choice([0.0, 0.49, 0.75, 0.9, 1.4]), + rng.choice([0.0, 0.5]), + rng.choice([0.0, 0.2, 0.49]), + rng.choice([0.51, 1.35, 1.5, 2.0]), + rng.choice([1.8, 2.8]), + rng.choice([0.51, 0.8, 1.0]), + ]), + 'boxes': boxes, + 'sticky_top': f64(rng.choice([0.0, 0.5, 0.9375])), + 'reaction': rng.randrange(5), + 'on_ground': rng.random() < 0.5, + 'supported': rng.random() < 0.5, + 'entity_x': f64(rng.choice([0.0, 0.5, 1.0, 2.0])), + 'entity_z': f64(rng.choice([0.0, 0.5, 1.0, 2.0])), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-piston-push-parity' + build.mkdir(parents=True, exist_ok=True) + report_path = build / 'report.json' + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java' + helpers = [oracle.with_name(name + '.java') + for name in ['VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaFaceSupportOracle']] + sources = [oracle, *helpers, Path(__file__), lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', + *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), + *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), + lab.ROOT / 'crates/horizon-world/examples/probe/piston_push_fixture.rs'] + tested_sources = base.source_hashes(sources) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + + dependency_path = os.pathsep.join(map(str, libraries)) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + dependency_path, + '-d', classes, oracle, *helpers], 'compile-java') + + def java(side, mode, path): + run(['java', '-Xmx512M', '-cp', os.pathsep.join([str(classes), str(jars[side]), dependency_path]), + 'dev.horizonlab.parity.VanillaPistonPushOracle', mode, path], side + '-' + mode) + + fixtures = list(corpus()) + inputs = build / 'inputs.txt' + inputs.write_text(''.join(json.dumps(value, separators=(',', ':')) + '\n' for value in fixtures), encoding='utf-8') + fixture_paths = [inputs] + tested_fixtures = base.source_hashes(fixture_paths) + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') + metadata = json.loads(subprocess.check_output( + ['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples' / ('world_probe.exe' if os.name == 'nt' else 'world_probe') + run([binary, 'piston_push_fixture', build], 'rust') + references = [] + for side, jar in jars.items(): + java(side, side, build) + reference = build / f'{side}.txt' + matched = base.compare(reference, build / 'rust.txt') + references.append({'side': side, 'jar_sha256': lab.digest(jar, 'sha256'), + 'output_sha256': lab.digest(reference, 'sha256'), 'matched_output_lines': matched}) + print(f'{side}: {matched:,} piston-push output lines match Rust', flush=True) + base.ensure_sources_unchanged(sources, tested_sources) + base.ensure_sources_unchanged(fixture_paths, tested_fixtures) + report = { + 'schema': 1, + 'minecraft': lock['minecraft']['version'], + 'manifest_sha1': lock['minecraft']['manifest_sha1'], + 'platform': platform.platform(), + 'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + 'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(), + 'fixtures': len(fixtures), + 'sources_sha256': tested_sources, + 'fixtures_sha256': tested_fixtures, + 'rust_output_sha256': lab.digest(build / 'rust.txt', 'sha256'), + 'references': references, + 'scope': 'Actual PistonMovingBlockEntity push geometry and predicates: getExtendedProgress, ' + 'moveByPositionAndProgress, PistonMath.getMovementArea, getMovement on every face, the ' + 'moveCollidedEntities loop over split shapes with its delta cap and PUSH_OFFSET, the ' + 'getEntities search box, and moveStuckEntities\' box with matchesStickyCritera for every push ' + 'reaction. fixEntityWithinPistonBase is covered by unit tests only: it calls ' + 'Entity.move(MoverType.PISTON, ...) and so needs a live level. Entity selection order, that ' + 'collision pass, the per-tick 0.51 limit, block behaviour of the moved state and full gameplay ' + 'remain elsewhere.', + } + lab.write_json(report_path, report) + print(f'Scoped piston-push parity passed: {report_path}') + + +if __name__ == '__main__': + main() \ No newline at end of file From da736d56d64aade0b9b95978358515a8c9b40b36 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:30:42 +0100 Subject: [PATCH 085/195] Lingering clouds skip mobs none of their effects can affect --- crates/horizon-client/src/game/potions.rs | 64 ++++++++++++++++++----- 1 file changed, 52 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index bfffff5ee..6a3f08ac5 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -79,6 +79,39 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { .get(id) .copied() } +/// `LivingEntity.canBeAffected` with the mob overrides (`WitherBoss` and +/// `WitherSkeleton` shrug off wither, `Spider` and `AbstractNautilus` poison, +/// `Parched` weakness): the immune-to-infested and immune-to-oozing tags +/// decide first, then the tag of mobs that ignore poison and regeneration. +fn mob_can_be_affected( + tags: &std::collections::HashMap>, + kind: &str, + effect: &str, +) -> bool { + let effect = effect.trim_start_matches("minecraft:"); + let kind = kind.trim_start_matches("minecraft:"); + let overridden = match kind { + "wither" | "wither_skeleton" => effect == "wither", + "spider" | "cave_spider" | "nautilus" | "zombie_nautilus" => effect == "poison", + "parched" => effect == "weakness", + _ => false, + }; + if overridden { + return false; + } + let in_tag = |tag: &str| { + tags.get(tag) + .is_some_and(|t| t.contains(&format!("minecraft:{kind}"))) + }; + if in_tag("minecraft:immune_to_infested") { + effect != "infested" + } else if in_tag("minecraft:immune_to_oozing") { + effect != "oozing" + } else { + !in_tag("minecraft:ignores_poison_and_regen") + || (effect != "regeneration" && effect != "poison") + } +} impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). @@ -632,14 +665,20 @@ impl Game<'_> { for p in players.iter().filter(|p| p.bounds.intersects(area)) { inside.push((Victim::Player(p.who), p.position.x, p.position.z)); } - for m in self - .mobs - .iter() - .filter(|m| m.alive() && m.bounds().intersects(area)) - { + let effects = potion.effects; + let tags = &self.res.stations().enchantments.entity_tags; + // Only mobs that at least one of the cloud's effects can affect are + // taken (`allEffects.stream().anyMatch(entity::canBeAffected)`), so + // the others neither become victims nor use up its radius. + for m in self.mobs.iter().filter(|m| { + m.alive() + && m.bounds().intersects(area) + && effects + .iter() + .any(|(id, ..)| mob_can_be_affected(tags, &m.kind.id, id)) + }) { inside.push((Victim::Mob(m.id), m.position.x, m.position.z)); } - let effects = potion.effects; for (victim, x, z) in inside { let (dx, dz) = (x - c.at[0], z - c.at[2]); if potion.victims.iter().any(|(v, _)| *v == victim) @@ -687,11 +726,8 @@ impl Game<'_> { return; }; // Undead invert healing and harming. - let inverted = self - .res - .stations() - .enchantments - .entity_tags + let tags = &self.res.stations().enchantments.entity_tags; + let inverted = tags .get("minecraft:inverted_healing_and_harm") .is_some_and(|t| t.contains(&self.mobs[i].kind.id)); for (id, duration, amp) in effects { @@ -707,7 +743,11 @@ impl Game<'_> { } } _ => { - if let Some(name) = mob_effect_id(id) { + // `LivingEntity.addEffect` refuses what the mob + // cannot be affected by. + if mob_can_be_affected(tags, &m.kind.id, id) + && let Some(name) = mob_effect_id(id) + { m.add_effect(name, scaled(*duration), *amp); } } From d75ef5e4f72426551c5aa9b68099037300e26e93 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:31:51 +0100 Subject: [PATCH 086/195] Draw translucent item quads without depth writes so water shows through glass items --- crates/horizon-client/src/gfx.rs | 45 ++++++++++++++++--- crates/horizon-client/src/gfx/entity_batch.rs | 9 +++- crates/horizon-client/src/item_render.rs | 41 ++++++++++++++++- crates/horizon-client/src/item_render/gui.rs | 1 + .../horizon-client/src/item_render/special.rs | 1 + 5 files changed, 88 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 70d882a98..b1afa4105 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -37,7 +37,9 @@ mod crumbling_tests; mod entity_batch; mod weather; use entity_batch::EntityBatch; -pub use entity_batch::{SHADOW_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY}; +pub use entity_batch::{ + SHADOW_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, +}; /// Window.getAppropriateLineWidth, in framebuffer pixels. pub fn outline_width(width: u32) -> f32 { @@ -391,6 +393,7 @@ pub struct Renderer { weather: weather::Weather, crumbling_pipeline: wgpu::RenderPipeline, shadow_blob_pipeline: wgpu::RenderPipeline, + translucent_item_pipeline: wgpu::RenderPipeline, /// `RenderPipelines.WATER_MASK`: depth writes only, no colour. water_mask_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, @@ -1837,6 +1840,19 @@ impl Renderer { alpha_blend, false, ); + // RenderPipelines.ITEM_TRANSLUCENT: blended, depth tested. Drawn before + // translucent terrain, it cannot write depth: the water behind a + // glass item would fail the test and vanish (vanilla sorts these in + // its order independent transparency pass instead). + let translucent_item_pipeline = entity_pipeline( + "Translucent items", + None, + false, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + alpha_blend, + false, + ); let cloud_pipeline = entity_pipeline( "Clouds", Some(wgpu::Face::Back), @@ -2371,6 +2387,7 @@ impl Renderer { weather, crumbling_pipeline, shadow_blob_pipeline, + translucent_item_pipeline, water_mask_pipeline, cloud_pipeline, cloud_mesh: Default::default(), @@ -3981,6 +3998,7 @@ impl Renderer { water_mask_quads, shadow_quads, translucent_particle_quads, + translucent_item_quads, ] = self .entity_batch .update(entities, frame.additive, frame.hand, frame.see_through); @@ -3990,7 +4008,8 @@ impl Renderer { + translucent_crumbling_quads + water_mask_quads + shadow_quads - + translucent_particle_quads; + + translucent_particle_quads + + translucent_item_quads; let cloud_quads = if let Some(input) = &frame.clouds { let (rebuilt, uniform) = crate::spans::time("clouds", || self.cloud_mesh.prepare(input)); @@ -4513,6 +4532,17 @@ impl Renderer { pass.draw_indexed(0..entity_quads * 6, 0, 0..1); pass.set_bind_group(0, &self.group, &[]); } + if translucent_item_quads > 0 { + pass.set_pipeline(&self.translucent_item_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..translucent_item_quads * 6, + ((world_quads - translucent_item_quads) * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if !pack_draws_weather { self.weather.draw(&mut pass, &self.entity_group); } @@ -4530,7 +4560,11 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed( 0..shadow_quads * 6, - ((world_quads - translucent_particle_quads - shadow_quads) * 4) as i32, + ((world_quads + - translucent_item_quads + - translucent_particle_quads + - shadow_quads) + * 4) as i32, 0..1, ); pass.set_bind_group(0, &self.group, &[]); @@ -4611,7 +4645,8 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed( 0..translucent_particle_quads * 6, - ((world_quads - translucent_particle_quads) * 4) as i32, + ((world_quads - translucent_item_quads - translucent_particle_quads) * 4) + as i32, 0..1, ); pass.set_bind_group(0, &self.group, &[]); @@ -5240,7 +5275,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1, 0, 1, 1]); + assert_eq!(counts, [4, 1, 1, 0, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 8153699fc..9d5e27a82 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -5,14 +5,18 @@ use super::Vertex; /// ordinary entities, breaking cracks (11), translucent breaking cracks (12), /// the boat water mask (13, `RenderPipelines.WATER_MASK`), entity shadows /// (14, `RenderPipelines.ENTITY_SHADOW`) and translucent-layer particles (15, -/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`). -const MATERIALS: usize = 6; +/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) +/// and translucent item quads (32, drawn without depth writes). +const MATERIALS: usize = 7; /// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). pub const WATER_MASK_OVERLAY: u32 = 13; /// The overlay of entity shadow quads (`RenderTypes.entityShadow`). pub const SHADOW_OVERLAY: u32 = 14; /// The overlay of translucent-layer particles (`SingleQuadParticle.Layer.translucent`). pub const TRANSLUCENT_PARTICLE_OVERLAY: u32 = 15; +/// The overlay of item quads with translucent pixels (`Sheets.translucentItemSheet`, +/// `RenderPipelines.ITEM_TRANSLUCENT`); past the creeper swell range (16 to 31). +pub const TRANSLUCENT_ITEM_OVERLAY: u32 = 32; #[derive(Default)] pub(super) struct EntityBatch { @@ -45,6 +49,7 @@ impl EntityBatch { WATER_MASK_OVERLAY => 3, SHADOW_OVERLAY => 4, TRANSLUCENT_PARTICLE_OVERLAY => 5, + TRANSLUCENT_ITEM_OVERLAY => 6, _ => 0, }; self.buckets[material][counts[material]] = index; diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 4f981b874..e098b31d7 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -46,6 +46,9 @@ pub struct ItemQuad { pub foil: Foil, /// `MaterialInfo.lightEmission` (block light floor). pub light_emission: u8, + /// The quad's sprite has translucent pixels (`MaterialInfo.itemRenderType` + /// is a translucent sheet): drawn with the translucent entities. + pub translucent: bool, } /// Which glint render type a quad uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -159,7 +162,7 @@ impl ItemRenderState { let m = pose * layer.matrix; match &layer.geometry { LayerGeometry::Quads(baked) => { - submit_quads(baked, layer, self.display, m, sprites, sink); + submit_quads(renderer, baked, layer, self.display, m, sprites, sink); } LayerGeometry::Special { model, argument } => special::submit( renderer, @@ -203,6 +206,7 @@ pub fn argb(color: i32) -> u32 { /// `ItemFeatureRenderer.prepareMainSubmit` for one cuboid layer. fn submit_quads( + renderer: &ItemRenderer, baked: &BakedItemModel, layer: &LayerRender, display: DisplayContext, @@ -216,6 +220,8 @@ fn submit_quads( FoilType::Special => Foil::Special, }; let _ = display; + // Quads of one layer mostly share a sprite: look its translucency up once. + let mut last: Option<(&str, bool)> = None; for q in &baked.quads { let Some(r) = sprites .get(sprite_name(&q.material.sprite)) @@ -239,6 +245,17 @@ fn submit_quads( let pos = q.positions.map(|p| m.transform_point3(Vec3::from(p))); let uv = q.uv.map(|[u, v]| [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v]); + let translucent = match last { + Some((sprite, translucent)) if sprite == q.material.sprite => translucent, + _ => { + let translucent = q.material.force_translucent + || renderer + .sprites + .translucent(sprite_name(&q.material.sprite)); + last = Some((&q.material.sprite, translucent)); + translucent + } + }; sink.quad(ItemQuad { pos, uv, @@ -246,6 +263,7 @@ fn submit_quads( color: argb(color), foil, light_emission: q.light_emission, + translucent, }); } } @@ -260,6 +278,9 @@ struct FileSprites { root: PathBuf, permutations: Vec, cache: Mutex>>, + /// Sprites with a pixel that is neither fully transparent nor opaque + /// (`Transparency.hasTranslucent`), filled in as sprites load. + translucent: Mutex>, } impl SpriteLookup for FileSprites { fn mask(&self, sprite: &str) -> Option { @@ -283,6 +304,13 @@ fn argb_pixels(rgba: &[u8]) -> Vec { .collect() } impl FileSprites { + fn translucent(&self, sprite: &str) -> bool { + let known = |this: &Self| this.translucent.lock().ok()?.get(sprite).copied(); + known(self).unwrap_or_else(|| { + self.mask(sprite); + known(self).unwrap_or(false) + }) + } fn png(&self, sprite: &str, directory: &str) -> PathBuf { crate::atlas_sources::texture_path(&self.root, sprite, directory) } @@ -303,6 +331,10 @@ impl FileSprites { (w, h, pixels) } }; + let translucent = argb.iter().any(|p| matches!(p >> 24, 1..=254)); + if let Ok(mut cache) = self.translucent.lock() { + cache.insert(sprite.to_owned(), translucent); + } let alpha: Vec = argb.iter().map(|p| (p >> 24) as u8).collect(); let animation = fs::read_to_string(png.with_extension("png.mcmeta")) .ok() @@ -452,6 +484,7 @@ impl ItemRenderer { root: root.to_path_buf(), permutations, cache: Mutex::default(), + translucent: Mutex::default(), }, baked: Mutex::default(), extents: Mutex::default(), @@ -693,7 +726,11 @@ impl ItemSink for WorldSink<'_> { } else { self.light }; - let overlay = if q.foil == Foil::None { 0 } else { 7 }; + let overlay = match (q.foil, q.translucent) { + (Foil::None, true) => crate::gfx::TRANSLUCENT_ITEM_OVERLAY, + (Foil::None, false) => 0, + _ => 7, + }; for (p, uv) in q.pos.iter().zip(q.uv) { self.out.push(Vertex { normal: [0; 4], diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index ff25fff1d..e0c901c0e 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -358,6 +358,7 @@ mod tests { color, foil: Foil::None, light_emission: 0, + translucent: false, } } diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index d42378db1..dc023f756 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -119,6 +119,7 @@ fn draw( color, foil, light_emission: 0, + translucent: false, }); } for (child_name, child) in &part.children { From 951b88a3c299c1221cbd317481e6bbf1c9d1b8f1 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 16:36:53 -0400 Subject: [PATCH 087/195] Read an End gateway's exit from its block entity Horizon had no End gateway block entity: game/end.rs kept each gateway's exit in its own side file and gateway_job only looked there, so a gateway set with /setblock end_gateway{exit_portal:[I;..],ExactTeleport:1b} (or the exit worldgen writes) was ignored, and /data get block said the block was not a block entity. TheEndGatewayBlockEntity stores Age, exit_portal and ExactTeleport. BlockEntity::EndGateway now holds them with vanilla's NBT and the spawnable-bounds check. gateway_job reads the block entity's exit first and keeps the side file and the 512-block End-spawn rule as fallbacks, so older saves and gateways without data behave as before. The exits Horizon creates are stored in the block entity as well, a new exit keeps the gateway's own ExactTeleport (setExitPosition), and a command that only changes a block entity's NBT now marks its chunk modified so the change is saved. Fixes #1517. Implementation by Codex (GPT-6.1 Sol), reviewed and extended by Claude. Co-Authored-By: Codex (GPT-6.1 Sol) Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/block_entity_nbt.rs | 15 +- crates/horizon-client/src/containers.rs | 16 ++ crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/commands.rs | 3 +- crates/horizon-client/src/game/end.rs | 177 +++++++++++++++--- crates/horizon-client/src/save.rs | 97 ++++++++++ crates/horizon-client/src/structure_blocks.rs | 20 ++ 7 files changed, 302 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/src/block_entity_nbt.rs b/crates/horizon-client/src/block_entity_nbt.rs index a4c02ba3b..67cd3591f 100644 --- a/crates/horizon-client/src/block_entity_nbt.rs +++ b/crates/horizon-client/src/block_entity_nbt.rs @@ -61,6 +61,16 @@ fn f32_tag(v: f32) -> Tag { Tag::Float(v.to_bits()) } +/// `TheEndGatewayBlockEntity.loadAdditional`: BlockPos.CODEC and Level.isInSpawnableBounds. +pub(crate) fn gateway_exit(tag: &Tag) -> Option<[i32; 3]> { + let Tag::IntArray(v) = tag else { return None }; + let p: [i32; 3] = v.as_slice().try_into().ok()?; + ((-30_000_000..30_000_000).contains(&p[0]) + && (-20_000_000..20_000_000).contains(&p[1]) + && (-30_000_000..30_000_000).contains(&p[2])) + .then_some(p) +} + /// What a block entity reads and writes, in `saveAdditional` order. struct Fields<'a> { input: &'a Tag, @@ -424,10 +434,7 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:end_gateway" => { f.long("Age", 0); - f.keep("exit_portal", |t| { - is_pos(t) - && matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000) - }); + f.keep("exit_portal", |t| gateway_exit(t).is_some()); if flag(tag.get("ExactTeleport")) == Some(true) { f.put("ExactTeleport", boolean(true)); } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 8ca9af0ad..81c453f32 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -98,10 +98,19 @@ pub enum BlockEntity { Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), + /// `TheEndGatewayBlockEntity`: its age and configured destination. + EndGateway(EndGateway), /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, } +/// `TheEndGatewayBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub exit_portal: Option<[i32; 3]>, + pub exact_teleport: bool, +} /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). #[derive(Clone, Debug, Default, PartialEq)] @@ -366,6 +375,9 @@ impl BlockEntity { if is_skull(name) { return Some(Self::Skull(Skull::default())); } + if name == "minecraft:end_gateway" { + return Some(Self::EndGateway(EndGateway::default())); + } if name == "minecraft:daylight_detector" { return Some(Self::DaylightDetector); } @@ -418,6 +430,7 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::EndGateway(_) => "minecraft:end_gateway", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", } @@ -436,6 +449,7 @@ impl BlockEntity { | Self::Vault(_) | Self::Beehive(_) | Self::CommandBlock(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), @@ -456,6 +470,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, @@ -480,6 +495,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 20f6e01bc..145e55554 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5455,6 +5455,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), @@ -5727,6 +5728,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 22041c3b2..b9a462d87 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1896,8 +1896,7 @@ impl Game<'_> { return false; } self.world.block_entities.insert(key, new); - let state = self.world.block(pos[0], pos[1], pos[2]); - let _ = self.world.set(pos[0], pos[1], pos[2], state); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); true } /// RandomizableContainer.tryLoadLootTable for a tag a command gives a diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 32d5113b0..e8b9a96e3 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,6 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, + containers::BlockEntity, environment::Environment, items::ItemStack, mesher::Vertex, @@ -27,14 +28,53 @@ const GATEWAY_Y: i32 = 75; const GATEWAY_FILE: &str = "horizon-end-gateways.json"; /// A gateway teleport waiting for its destination chunks. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum GatewayJob { /// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway. - Find { gateway: [i32; 3] }, + /// `exact` is the gateway's own `ExactTeleport`, read while its chunk is loaded. + Find { gateway: [i32; 3], exact: bool }, /// A known exit (exact, or findExitPosition around it). Known { exit: [i32; 3], exact: bool }, } +impl GatewayJob { + /// TheEndGatewayBlockEntity.getPortalPosition, with legacy save fallbacks. + fn for_gateway( + gateway: [i32; 3], + entity: Option<&BlockEntity>, + legacy: Option<([i32; 3], bool)>, + ) -> Self { + let configured = match entity { + Some(BlockEntity::EndGateway(g)) => g.exit_portal.map(|exit| (exit, g.exact_teleport)), + _ => None, + }; + match configured.or(legacy) { + Some((exit, exact)) => Self::Known { exit, exact }, + // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. + None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => Self::Known { + exit: END_SPAWN, + exact: true, + }, + None => Self::Find { + gateway, + exact: exact_teleport(entity), + }, + } + } +} + +/// `TheEndGatewayBlockEntity.exactTeleport` of the block entity at a gateway +/// (false without one). +fn exact_teleport(entity: Option<&BlockEntity>) -> bool { + matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) +} + +/// The end of `getPortalPosition`: the exit itself when the teleport is exact, +/// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). +fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { + if exact { exit } else { find(exit) } +} + #[derive(Default)] pub(super) struct EndState { /// Gateway position -> (exit, exact teleport); loaded lazily from the save. @@ -754,6 +794,11 @@ impl Game<'_> { } } } + self.world + .block_entities + .get_or_insert_with((origin[0], origin[1], origin[2]), || { + BlockEntity::EndGateway(Default::default()) + }); Ok(()) } @@ -776,6 +821,21 @@ impl Game<'_> { } fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // side map below still records the exit. + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + } self.gateway_exits().insert(gateway, (exit, exact)); let list: Vec<_> = self .gateway_exits() @@ -808,24 +868,20 @@ impl Game<'_> { /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { let known = self.gateway_exits().get(&gateway).copied(); - let job = match known { - Some((exit, exact)) => GatewayJob::Known { exit, exact }, - // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. - None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => { - GatewayJob::Known { - exit: END_SPAWN, - exact: true, - } - } - None => GatewayJob::Find { gateway }, - }; + let job = GatewayJob::for_gateway( + gateway, + self.world + .block_entities + .get(&(gateway[0], gateway[1], gateway[2])), + known, + ); let destination = match job { GatewayJob::Known { exit, .. } => Vec3::new( f64::from(exit[0]) + 0.5, f64::from(exit[1]), f64::from(exit[2]) + 0.5, ), - GatewayJob::Find { gateway } => { + GatewayJob::Find { gateway, .. } => { let d = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero() * 1024.0; @@ -882,12 +938,10 @@ impl Game<'_> { [p[0], p[1] + 1, p[2]] }; match job { - GatewayJob::Known { exit, exact } => Ok(bottom_center(if exact { - exit - } else { - find_exit(self, exit) - })), - GatewayJob::Find { gateway } => { + GatewayJob::Known { exit, exact } => Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))), + GatewayJob::Find { gateway, exact } => { // findExitPortalXZPosTentative over the loaded chunks. let dir = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero(); @@ -947,8 +1001,11 @@ impl Game<'_> { let exit = [tallest[0], tallest[1] + 10, tallest[2]]; self.place_gateway(exit)?; self.set_gateway_exit(exit, gateway, false)?; - self.set_gateway_exit(gateway, exit, false)?; - Ok(bottom_center(find_exit(self, exit))) + // setExitPosition keeps the gateway's own exactTeleport. + self.set_gateway_exit(gateway, exit, exact)?; + Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))) } } } @@ -1245,3 +1302,79 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::containers::EndGateway; + + #[test] + fn a_new_exit_keeps_the_gateways_exact_teleport() { + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + let plain = BlockEntity::EndGateway(EndGateway::default()); + assert!(exact_teleport(Some(&exact))); + assert!(!exact_teleport(Some(&plain))); + assert!(!exact_teleport(None)); + assert!(!exact_teleport(Some(&BlockEntity::DaylightDetector))); + let exit = [8, 100, 0]; + // Exact: the exit itself, nothing is searched for. + assert_eq!(exit_target(exit, true, |_| panic!("searched")), exit); + assert_eq!( + exit_target(exit, false, |e| [e[0], e[1] + 11, e[2]]), + [8, 111, 0] + ); + } + + #[test] + fn end_gateway_job_prefers_block_entity_then_legacy_then_heuristic() { + let gateway = [702, 100, 0]; + let exit = [8, 100, 0]; + for exact in [true, false] { + let entity = BlockEntity::EndGateway(EndGateway { + exit_portal: Some(exit), + exact_teleport: exact, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(gateway, Some(&entity), Some((END_SPAWN, !exact))), + GatewayJob::Known { exit, exact }, + ); + } + let empty = BlockEntity::EndGateway(EndGateway::default()); + for entity in [None, Some(&empty)] { + assert_eq!( + GatewayJob::for_gateway(gateway, entity, Some((exit, false))), + GatewayJob::Known { exit, exact: false } + ); + assert_eq!( + GatewayJob::for_gateway(gateway, entity, None), + GatewayJob::Known { + exit: END_SPAWN, + exact: true + } + ); + let nearby = [96, 75, 0]; + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(nearby, Some(&exact), None), + GatewayJob::Find { + gateway: nearby, + exact: true + } + ); + assert_eq!( + GatewayJob::for_gateway(nearby, entity, None), + GatewayJob::Find { + gateway: nearby, + exact: false + } + ); + } + } +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5431adcd6..d398a2ac1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -643,6 +643,16 @@ pub fn encode_block_entity( entries.push(("custom_name", name.clone())); } } + // TheEndGatewayBlockEntity.saveAdditional. + BlockEntity::EndGateway(g) => { + entries.push(("Age", Tag::Long(g.age))); + if let Some(exit) = g.exit_portal { + entries.push(("exit_portal", Tag::IntArray(exit.to_vec()))); + } + if g.exact_teleport { + entries.push(("ExactTeleport", Tag::Byte(1))); + } + } BlockEntity::Spawner(s) => entries.extend(s.save()), BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Vault(v) => entries.extend(v.save()), @@ -702,11 +712,24 @@ fn roll_loaded_loot( biome, )) } +/// `TheEndGatewayBlockEntity.loadAdditional`. +pub fn decode_end_gateway(tag: &Tag) -> crate::containers::EndGateway { + crate::containers::EndGateway { + age: number(tag.get("Age")).unwrap_or(0), + exit_portal: tag + .get("exit_portal") + .and_then(crate::block_entity_nbt::gateway_exit), + exact_teleport: number(tag.get("ExactTeleport")).unwrap_or(0) != 0, + } +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); let id = text(tag.get("id"))?; let pos = (int("x")?, int("y")?, int("z")?); + if id == "minecraft:end_gateway" { + return Some((pos, BlockEntity::EndGateway(decode_end_gateway(tag)))); + } if id == "minecraft:jukebox" { let record = tag.get("RecordItem").and_then(item_from_nbt); let ticks = number(tag.get("ticks_since_song_started")).unwrap_or(0); @@ -846,6 +869,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), @@ -4660,6 +4684,79 @@ mod tests { } use super::*; + #[test] + fn end_gateway_block_entity_round_trips() { + use crate::containers::{BlockEntity, EndGateway}; + let plain = BlockEntity::for_block("minecraft:end_gateway").expect("gateway"); + assert!(matches!(&plain, BlockEntity::EndGateway(g) if *g == EndGateway::default())); + for exit in [None, Some([8, 100, 0])] { + for exact in [false, true] { + let gateway = EndGateway { + age: 201, + exit_portal: exit, + exact_teleport: exact, + }; + let tag = encode_block_entity( + (702, 100, 0), + &BlockEntity::EndGateway(gateway.clone()), + "minecraft:end_gateway", + ); + assert_eq!( + text(tag.get("id")).as_deref(), + Some("minecraft:end_gateway") + ); + assert_eq!(tag.get("Age"), Some(&Tag::Long(201))); + assert_eq!( + tag.get("exit_portal"), + exit.map(|p| Tag::IntArray(p.to_vec())).as_ref() + ); + assert_eq!( + tag.get("ExactTeleport"), + exact.then_some(Tag::Byte(1)).as_ref() + ); + let (pos, back) = decode_block_entity(&tag).expect("gateway"); + assert_eq!(pos, (702, 100, 0)); + assert!(matches!(back, BlockEntity::EndGateway(g) if g == gateway)); + } + } + } + + #[test] + fn end_gateway_exit_requires_spawnable_bounds() { + for (exit, valid) in [ + (vec![-30_000_000, -20_000_000, -30_000_000], true), + (vec![29_999_999, 19_999_999, 29_999_999], true), + (vec![30_000_000, 0, 0], false), + (vec![0, 0, 30_000_000], false), + (vec![-30_000_001, 0, 0], false), + (vec![0, 0, -30_000_001], false), + (vec![0, 20_000_000, 0], false), + (vec![0, -20_000_001, 0], false), + (vec![i32::MIN, 0, 0], false), + (vec![0, 100], false), + ] { + let tag = Tag::compound([ + ("id", string("minecraft:end_gateway")), + ("x", Tag::Int(702)), + ("y", Tag::Int(100)), + ("z", Tag::Int(0)), + ("exit_portal", Tag::IntArray(exit)), + ]); + let (_, crate::containers::BlockEntity::EndGateway(g)) = + decode_block_entity(&tag).unwrap() + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal.is_some(), valid); + let canonical = crate::block_entity_nbt::canonical(&tag).expect("gateway NBT"); + assert_eq!(canonical.get("exit_portal").is_some(), valid); + } + assert_eq!( + decode_end_gateway(&Tag::Compound(Compound::new())), + crate::containers::EndGateway::default() + ); + } + #[test] fn skull_block_entity_keeps_its_profile() { // A placed `player_head` as vanilla saves it: the owning player's diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..45eccbac7 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -199,6 +199,9 @@ fn generated_block_entity(block: &str, nbt: &Compound) -> Option { BlockEntity::Vault(v) => **v = crate::vault::Vault::load(&Tag::Compound(nbt.clone())), // BannerBlockEntity.loadAdditional: the End cities' black triangles. BlockEntity::Banner(b) => *b = crate::save::decode_banner(&Tag::Compound(nbt.clone())), + BlockEntity::EndGateway(g) => { + *g = crate::save::decode_end_gateway(&Tag::Compound(nbt.clone())) + } _ => {} } Some(entity) @@ -242,6 +245,23 @@ mod tests { use super::*; use horizon_world::loot::{ExplorationMap, LootStack}; + #[test] + fn generated_end_gateway_keeps_its_exit() { + let Tag::Compound(nbt) = Tag::compound([ + ("exit_portal", Tag::IntArray(vec![100, 50, 0])), + ("ExactTeleport", Tag::Byte(1)), + ]) else { + unreachable!() + }; + let Some(BlockEntity::EndGateway(g)) = + generated_block_entity("minecraft:end_gateway", &nbt) + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal, Some([100, 50, 0])); + assert!(g.exact_teleport); + } + #[test] fn placed_chest_loot_keeps_its_enchantments_and_potions() { let stack = From a529be89156d129a359fdfc1004390ecc3f82045 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:40:21 +0100 Subject: [PATCH 088/195] Keep translucent item rendering with enchantment glint --- crates/horizon-client/src/entity.wgsl | 2 +- crates/horizon-client/src/gfx.rs | 3 ++- crates/horizon-client/src/gfx/entity_batch.rs | 4 +++- crates/horizon-client/src/item_render.rs | 12 ++++++------ 4 files changed, 12 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 79e11719f..7d3f06040 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -203,7 +203,7 @@ fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, // lit texture, then the lightmap, then the glint and fog. color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a); color *= in.light_color; - if in.overlay == 7u || in.overlay == 8u { + if in.overlay == 7u || in.overlay == 8u || in.overlay == 33u { // Enchantment glint (overlay 7, 8 with the hurt tint): the purple // enchanted_glint sheen drifting diagonally over the item's shape. let px = in.uv * vec2(textureDimensions(atlas)); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index b1afa4105..580e8493a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -38,7 +38,8 @@ mod entity_batch; mod weather; use entity_batch::EntityBatch; pub use entity_batch::{ - SHADOW_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, + SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, + TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, }; /// Window.getAppropriateLineWidth, in framebuffer pixels. diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 9d5e27a82..08d749b54 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -17,6 +17,8 @@ pub const TRANSLUCENT_PARTICLE_OVERLAY: u32 = 15; /// The overlay of item quads with translucent pixels (`Sheets.translucentItemSheet`, /// `RenderPipelines.ITEM_TRANSLUCENT`); past the creeper swell range (16 to 31). pub const TRANSLUCENT_ITEM_OVERLAY: u32 = 32; +/// A translucent item with an enchantment glint. +pub const TRANSLUCENT_GLINT_ITEM_OVERLAY: u32 = 33; #[derive(Default)] pub(super) struct EntityBatch { @@ -49,7 +51,7 @@ impl EntityBatch { WATER_MASK_OVERLAY => 3, SHADOW_OVERLAY => 4, TRANSLUCENT_PARTICLE_OVERLAY => 5, - TRANSLUCENT_ITEM_OVERLAY => 6, + TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 6, _ => 0, }; self.buckets[material][counts[material]] = index; diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index e098b31d7..75f947eec 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -248,10 +248,9 @@ fn submit_quads( let translucent = match last { Some((sprite, translucent)) if sprite == q.material.sprite => translucent, _ => { - let translucent = q.material.force_translucent - || renderer - .sprites - .translucent(sprite_name(&q.material.sprite)); + let translucent = renderer + .sprites + .translucent(sprite_name(&q.material.sprite)); last = Some((&q.material.sprite, translucent)); translucent } @@ -263,7 +262,7 @@ fn submit_quads( color: argb(color), foil, light_emission: q.light_emission, - translucent, + translucent: translucent || q.material.force_translucent, }); } } @@ -729,7 +728,8 @@ impl ItemSink for WorldSink<'_> { let overlay = match (q.foil, q.translucent) { (Foil::None, true) => crate::gfx::TRANSLUCENT_ITEM_OVERLAY, (Foil::None, false) => 0, - _ => 7, + (_, true) => crate::gfx::TRANSLUCENT_GLINT_ITEM_OVERLAY, + (_, false) => 7, }; for (p, uv) in q.pos.iter().zip(q.uv) { self.out.push(Vertex { From b90f9ec1efc6ed34d815ad8652c5accab5600c73 Mon Sep 17 00:00:00 2001 From: Carlos Nunez Date: Mon, 26 Oct 2026 16:57:07 -0400 Subject: [PATCH 089/195] Make an End gateway's block entity the source of its exit The side file kept an entry for a gateway after Horizon created its exit, so removing the exit with /data remove block ... exit_portal, or placing a different gateway there, sent the player to the old exit again. Once the gateway's chunk is loaded, gateway_job moves an entry the side file still holds into the block entity (unless the block entity has an exit of its own) and drops the entry. set_gateway_exit writes only the block entity when the chunk is loaded, and leaves an entry in the side file only when the chunk is already unloaded. Co-Authored-By: Claude Sonnet 5.5 --- crates/horizon-client/src/game/end.rs | 97 +++++++++++++++++++++------ 1 file changed, 78 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index e8b9a96e3..687ba6bb4 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,7 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, - containers::BlockEntity, + containers::{BlockEntity, EndGateway}, environment::Environment, items::ItemStack, mesher::Vertex, @@ -69,6 +69,17 @@ fn exact_teleport(entity: Option<&BlockEntity>) -> bool { matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) } +/// Moves an exit that only the side file knew into the gateway's block entity, unless the block +/// entity has its own; true when it took the saved one. +fn adopt_saved_exit(entity: &mut EndGateway, (exit, exact): ([i32; 3], bool)) -> bool { + if entity.exit_portal.is_some() { + return false; + } + entity.exit_portal = Some(exit); + entity.exact_teleport = exact; + true +} + /// The end of `getPortalPosition`: the exit itself when the teleport is exact, /// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { @@ -820,23 +831,7 @@ impl Game<'_> { self.end.exits.as_mut().expect("loaded exits") } - fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { - // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). - let key = (gateway[0], gateway[1], gateway[2]); - let chunk = (gateway[0] >> 4, gateway[2] >> 4); - // The gateway's chunk can be unloaded by now (travel waits for the destination): the - // side map below still records the exit. - if self.world.chunks.contains_key(&chunk) - && let BlockEntity::EndGateway(g) = self - .world - .block_entities - .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) - { - g.exit_portal = Some(exit); - g.exact_teleport = exact; - self.world.modified.insert(chunk); - } - self.gateway_exits().insert(gateway, (exit, exact)); + fn save_gateway_exits(&mut self) -> Result<()> { let list: Vec<_> = self .gateway_exits() .iter() @@ -848,6 +843,35 @@ impl Game<'_> { Ok(()) } + /// Drops a gateway's entry from the side file: its block entity is the source of truth. + fn forget_gateway_exit(&mut self, gateway: [i32; 3]) -> Result<()> { + if self.gateway_exits().remove(&gateway).is_some() { + self.save_gateway_exits()?; + } + Ok(()) + } + + fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // exit then waits in the side file until the gateway is used again (`gateway_job`). + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + return self.forget_gateway_exit(gateway); + } + self.gateway_exits().insert(gateway, (exit, exact)); + self.save_gateway_exits() + } + /// EndGatewayBlock.entityInside and TheEndGatewayBlockEntity.getPortalPosition: /// travel within the End, waiting for the destination chunks to load. fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> { @@ -867,7 +891,25 @@ impl Game<'_> { /// its exit, or the search for one, and the spot to load before either /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { - let known = self.gateway_exits().get(&gateway).copied(); + let mut known = self.gateway_exits().get(&gateway).copied(); + // Once the gateway's chunk is loaded its block entity is the source of truth: an exit the + // side file kept for it moves there, and the entry is dropped, so removing or replacing + // the exit (`/data remove block`) is not undone by an old entry. + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + if let Some(saved) = known + && self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + if adopt_saved_exit(g, saved) { + self.world.modified.insert(chunk); + } + known = None; + let _ = self.forget_gateway_exit(gateway); + } let job = GatewayJob::for_gateway( gateway, self.world @@ -1308,6 +1350,23 @@ mod tests { use super::*; use horizon_client::containers::EndGateway; + #[test] + fn a_saved_exit_moves_into_a_gateway_without_one() { + let saved = ([8, 100, 0], true); + let mut bare = EndGateway::default(); + assert!(adopt_saved_exit(&mut bare, saved)); + assert_eq!(bare.exit_portal, Some([8, 100, 0])); + assert!(bare.exact_teleport); + // The block entity's own exit wins over a stale entry. + let mut own = EndGateway { + exit_portal: Some([1, 2, 3]), + ..Default::default() + }; + assert!(!adopt_saved_exit(&mut own, saved)); + assert_eq!(own.exit_portal, Some([1, 2, 3])); + assert!(!own.exact_teleport); + } + #[test] fn a_new_exit_keeps_the_gateways_exact_teleport() { let exact = BlockEntity::EndGateway(EndGateway { From 6120c8c0ad40618ec4636041d995ca0842f17ef0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:03:17 +0100 Subject: [PATCH 090/195] Attack the block when a guest's START_DESTROY_BLOCK arrives --- crates/horizon-client/src/game/lan_actions.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0ad14bbcc..bc23314d0 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -921,6 +921,20 @@ impl Game<'_> { // The pause between two blocks is the client's (MultiPlayerGameMode's // destroyDelay); the server digs from the START it receives. play.destroy_delay = 0; + // ServerPlayerGameMode.handleBlockBreakAction: a survival START + // attacks the block at once, so a tap released in the same tick + // still plays a note. The dig is marked begun for tick_mining. + let pos = a.pos; + self.as_guest(host, conn, |g| { + if g.may_build() && !g.creative { + let _ = g.attack_block(pos); + g.mining = Some(Mining { + pos, + progress: 0.0, + ticks: 0, + }); + } + }); } 1 => {} 3 => { From ed9fdb5208fbf2e0fadf1722a376746350827741 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:04:40 +0100 Subject: [PATCH 091/195] Point an explosion's hurt tilt at the blast --- crates/horizon-client/src/game/explosion.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 6ecba3a54..789eb5442 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -305,6 +305,12 @@ impl Game<'_> { ) { outcome = o; + // dealDefaultKnockback's `indicateDamage` points at the blast + // (the source position), not the no-direction fallback. + if o.knockback && o.blocked <= 0.0 { + p.health + .indicate_damage(center[0] - feet[0], center[2] - feet[2], p.yaw); + } } if !spectator && !(creative && flying) { p.velocity = Vec3::new( From 6977659843800ded64f86b48ad744b9e0c940eb8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:06:50 +0100 Subject: [PATCH 092/195] Open the command block screen on a server's client and send its edits --- crates/horizon-client/src/command_block.rs | 17 ++++ .../horizon-client/src/game/command_blocks.rs | 83 ++++++++++++++++++- crates/horizon-client/src/game/lan_actions.rs | 1 + crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-protocol/src/packets/play.rs | 7 ++ 5 files changed, 106 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/command_block.rs b/crates/horizon-client/src/command_block.rs index 942e11ab6..47f808932 100644 --- a/crates/horizon-client/src/command_block.rs +++ b/crates/horizon-client/src/command_block.rs @@ -35,6 +35,23 @@ impl Mode { Self::Redstone => "minecraft:command_block", } } + /// `Enum.ordinal`, which `ServerboundSetCommandBlockPacket` writes. + pub fn ordinal(self) -> i32 { + match self { + Self::Sequence => 0, + Self::Auto => 1, + Self::Redstone => 2, + } + } + /// The mode of a packet's ordinal; `handleSetCommandBlock` treats any + /// other value as a plain command block (its `default` branch). + pub fn from_ordinal(ordinal: i32) -> Self { + match ordinal { + 0 => Self::Sequence, + 1 => Self::Auto, + _ => Self::Redstone, + } + } /// `CycleButton`: the next value, wrapping round. pub fn next(self) -> Self { match self { diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 76fc6d48c..868346452 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -2,7 +2,7 @@ //! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand` //! through the command system with the block's output, and //! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it. -use super::{Game, Screen, commands::execute::Source}; +use super::{Game, Screen, commands::execute::Source, lan::LanHost}; use horizon_client::{ command_block::{self, CommandBlock, Mode}, containers::BlockEntity, @@ -12,6 +12,7 @@ use horizon_client::{ world::World, }; use horizon_core::position::BlockPos; +use horizon_protocol::packets::play::{self, Serverbound as S}; use horizon_world::{ chunk::BlockState, level::flags, @@ -35,6 +36,16 @@ pub(super) struct CommandBlockScreen { auto: bool, } +/// What `ServerboundSetCommandBlockPacket` carries. +struct CommandBlockEdit { + pos: Pos, + command: String, + track_output: bool, + mode: Mode, + conditional: bool, + auto: bool, +} + #[derive(Clone, Copy, PartialEq)] enum Button { Output, @@ -186,6 +197,18 @@ impl Game<'_> { pub(super) fn can_use_game_master_blocks(&self) -> bool { self.creative && self.ui.registries.permission >= 2 } + /// `CommandBlock.useWithoutItem` on a server's client, which opens the + /// screen itself (`Player.openCommandBlock`) while the server only + /// answers the click: the block at `pos`, when it is a command block the + /// player may edit. + pub(super) fn open_command_block_if_editable(&mut self, pos: Pos) { + let is_command_block = self + .block_state_at(pos) + .is_some_and(|state| Mode::of_block(&state.name).is_some()); + if is_command_block && self.can_use_game_master_blocks() { + self.open_command_block(pos); + } + } fn command_block(&self, pos: Pos) -> Option<&CommandBlock> { match self.world.block_entities.get(&pos)? { BlockEntity::CommandBlock(c) => Some(c), @@ -572,12 +595,66 @@ impl Game<'_> { s.command.insert_text(&allowed); } } - /// `ServerGamePacketListenerImpl.handleSetCommandBlock`. + /// The edit screen's Done: a server's client sends the packet, the + /// window's own world applies it (`handleSetCommandBlock`). fn set_command_block(&mut self, s: &CommandBlockScreen) { if !self.can_use_game_master_blocks() { self.system_message(Text::translate("advMode.notAllowed", &[])); return; } + let edit = CommandBlockEdit { + pos: s.pos, + command: s.command.value.clone(), + track_output: s.track_output, + mode: s.mode, + conditional: s.conditional, + auto: s.auto, + }; + if self.remote.is_some() { + self.send(S::SetCommandBlock(play::SetCommandBlock { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + command: edit.command, + mode: edit.mode.ordinal(), + flags: i8::from(edit.track_output) + | (i8::from(edit.conditional) << 1) + | (i8::from(edit.auto) << 2), + })); + } else { + self.apply_command_block(&edit); + } + } + /// `ServerGamePacketListenerImpl.handleSetCommandBlock` for a guest: the + /// block is edited only by a creative player with game master commands. + pub(super) fn lan_set_command_block( + &mut self, + host: &mut LanHost, + conn: u32, + p: play::SetCommandBlock, + ) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let allowed = g.creative() && g.permission >= 2; + let edit = CommandBlockEdit { + pos: (p.pos[0], p.pos[1], p.pos[2]), + command: p.command, + track_output: p.flags & 1 != 0, + mode: Mode::from_ordinal(p.mode), + conditional: p.flags & 2 != 0, + auto: p.flags & 4 != 0, + }; + self.as_guest(host, conn, |game| { + if allowed { + game.apply_command_block(&edit); + // BaseCommandBlock.onUpdated: the clients get the new command. + game.mark_block_entity_updated(edit.pos); + } else { + game.system_message(Text::translate("advMode.notAllowed", &[])); + } + }); + } + /// What `handleSetCommandBlock` does once the player may edit the block. + fn apply_command_block(&mut self, s: &CommandBlockEdit) { let pos = s.pos; let registry = self.pack.assets.registry; let Some(current) = self.block_state_at(pos) else { @@ -609,7 +686,7 @@ impl Game<'_> { } let _ = self.process_level_events(); } - let command = s.command.value.clone(); + let command = s.command.clone(); let Some(c) = command_block_mut(&mut self.world, pos) else { return; }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 98162ae46..a24938014 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1200,6 +1200,7 @@ impl Game<'_> { } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), S::SignUpdate(p) => self.lan_sign_update(host, conn, p), + S::SetCommandBlock(p) => self.lan_set_command_block(host, conn, p), S::EditBook(p) => self.lan_edit_book(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..6538fbaae 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4064,6 +4064,7 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + self.open_command_block_if_editable((hit.pos[0], hit.pos[1], hit.pos[2])); } else if let Some(stack) = held.as_ref() && self.predict_item_on_block(stack, &hit) { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 26bc09a84..6140a3b55 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2160,6 +2160,12 @@ packet!( /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } ); +packet!( + /// ServerboundSetCommandBlockPacket: the command block's command, its + /// mode (`CommandBlockEntity.Mode` ordinal) and the track output (1), + /// conditional (2) and automatic (4) flags. + SetCommandBlock { pos: [i32; 3] => Pos, command: String => Str, mode: i32 => VarInt, flags: i8 => Byte } +); packet!( /// ServerboundEditBookPacket: the book's slot (a hotbar slot, or 40 for /// the off hand), its pages and, to sign it, its title. @@ -2320,6 +2326,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { SelectTrade(SelectTrade) = SELECT_TRADE, SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, + SetCommandBlock(SetCommandBlock) = SET_COMMAND_BLOCK, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, SignUpdate(SignUpdate) = SIGN_UPDATE, UseItem(UseItem) = USE_ITEM, From 8f78fdeb7bec717e91fa24394b9bcb940cfc8ae5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:08:35 +0100 Subject: [PATCH 093/195] Keep leash knot ids per level and clear remote knots with the other remote objects --- crates/horizon-client/src/game/levels.rs | 4 ++++ crates/horizon-client/src/game/remote_objects.rs | 1 + 2 files changed, 5 insertions(+) diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 8d2e0a4a2..09de6ab62 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -66,6 +66,8 @@ pub(super) struct Parked { tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, mobs: Vec, + /// The entity ids of the level's fence knots (`knot_ids`). + knot_ids: HashMap<[i32; 3], u32>, projectiles: Vec, dropped: Vec, orbs: Vec, @@ -153,6 +155,7 @@ impl Game<'_> { tnts: Vec::new(), hoppers: HashMap::new(), mobs: Vec::new(), + knot_ids: HashMap::new(), projectiles: Vec::new(), dropped: Vec::new(), orbs: Vec::new(), @@ -205,6 +208,7 @@ impl Game<'_> { swap(&mut self.tnts, &mut p.tnts); swap(&mut self.hoppers, &mut p.hoppers); swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.knot_ids, &mut p.knot_ids); swap(&mut self.creatures.projectiles, &mut p.projectiles); swap(&mut self.dropped, &mut p.dropped); swap(&mut self.orbs, &mut p.orbs); diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index f6afba1b2..7f484c35f 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -315,6 +315,7 @@ impl Game<'_> { /// Every object a server sent (a new connection, level or dimension). pub(super) fn clear_remote_objects(&mut self) { self.text_displays.clear(); + self.remote_knots.clear(); self.carts.clear(); self.boats.clear(); self.armor_stands.clear(); From 6c716f457b7609e96bf6bc1642d0917cb615c1e4 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 21:16:23 +0100 Subject: [PATCH 094/195] Mobs: farm animals and frogs keep their variant; sound variants are saved finalizeSpawn picks the variant of a pig, cow, chicken or frog and the sound variant of a pig, cow, chicken, cat or wolf, but the save wrote neither for these: pigs, cows, chickens and frogs came back temperate after a reload, and every cat and wolf was saved with the classic sounds whatever it rolled. Chickens also lost their egg timer. Every mob with a variant component now saves and loads `variant` through finalize::species_variant_component / variant_index (the cat and wolf code used its own copy). The sound variant is kept as an index into the species' registry (None is the default, classic) and is saved and read back; Chicken also saves `EggLayTime`. Co-Authored-By: Claude Opus 5.5 --- .../examples/probe/finalize_spawn_fixture.rs | 8 +- crates/horizon-client/src/entity_nbt.rs | 125 ++++++++++++++---- crates/horizon-client/src/mobs.rs | 5 +- crates/horizon-client/src/mobs/finalize.rs | 13 +- 4 files changed, 120 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index b1b25e723..067d545a8 100644 --- a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -154,11 +154,11 @@ const MEMORIES: [&str; 7] = [ fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { use Species as S; let s = m.species(); - let named = |reg: &finalize::VariantRegistry, i: u8| { - format!( - "minecraft:{}", + let named = |reg: &finalize::VariantRegistry, i: Option| { + let name = i.map_or("classic", |i| { reg.names.get(i as usize).map_or("?", |n| n.as_str()) - ) + }); + format!("minecraft:{name}") }; let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant)); match s { diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 161ca12e9..8926b3bbe 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -225,6 +225,24 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { if is_animal(id) { map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); } + let species = m.species(); + if let Some((_, variant)) = + crate::mobs::finalize::species_variant_component(species, m.extra.variant) + { + map.insert("variant".into(), string(&variant)); + } + if species == crate::mobs::Species::Chicken { + map.insert("EggLayTime".into(), Tag::Int(m.extra.egg_time)); + } + let sounds = crate::mobs::finalize::sound_variants(species); + if !sounds.is_empty() { + let sound = m.extra.sound_variant.and_then(|i| sounds.get(i as usize)); + let sound = sound.copied().unwrap_or("classic"); + map.insert( + "sound_variant".into(), + string(&format!("minecraft:{sound}")), + ); + } match id { "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { @@ -241,10 +259,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::CAT_VARIANTS[(m.extra.variant as usize).min(10)]; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:wolf" => { if let Some(owner) = m.extra.owner { @@ -254,10 +268,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::WOLF_VARIANTS[(m.extra.variant as usize).min(8)].0; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { map.insert( @@ -793,20 +803,27 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.vector[0] = 0.7; } } + if crate::mobs::finalize::species_variant_component(m.species(), 0).is_some() + && let Some(v) = text(tag.get("variant")) + { + m.extra.variant = crate::mobs::finalize::variant_index(m.species(), &v); + } + if m.species() == crate::mobs::Species::Chicken + && let Some(t) = number(tag.get("EggLayTime")) + { + m.extra.egg_time = t as i32; + } + if let Some(v) = text(tag.get("sound_variant")) { + let v = v.trim_start_matches("minecraft:"); + let sounds = crate::mobs::finalize::sound_variants(m.species()); + m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8); + } if m.species() == crate::mobs::Species::Cat { m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); m.extra.tame = m.extra.owner.is_some(); m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::CAT_VARIANTS - .iter() - .position(|n| *n == v) - .unwrap_or(0) as u8; - } } if m.species() == crate::mobs::Species::Wolf { let health = m.health; @@ -817,14 +834,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::WOLF_VARIANTS - .iter() - .position(|(n, _)| *n == v) - .unwrap_or(0) as u8; - } } if matches!( m.species(), @@ -2425,6 +2434,74 @@ mod sheep_nbt_tests { let back = mob_from_nbt(&tag, &types, 2).unwrap(); assert_eq!((back.extra.color, back.extra.sheared), (14, true)); } + + #[test] + fn farm_animals_keep_their_variant_and_sound_variant() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let mut m = Mob::new( + 1, + types["minecraft:pig"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!( + text(tag.get("variant")).as_deref(), + Some("minecraft:temperate") + ); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:classic") + ); + // Spawned in a warm biome with the mini sounds. + (m.extra.variant, m.extra.sound_variant) = (1, Some(2)); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:warm")); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:mini") + ); + let back = mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!((back.extra.variant, back.extra.sound_variant), (1, Some(2))); + let mut hen = Mob::new( + 3, + types["minecraft:chicken"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + (hen.extra.variant, hen.extra.egg_time) = (2, 7795); + let tag = mob_to_nbt(&hen, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:cold")); + let back = mob_from_nbt(&tag, &types, 4).unwrap(); + assert_eq!((back.extra.variant, back.extra.egg_time), (2, 7795)); + // The sound variants are indices into the registries finalizeSpawn draws from. + use crate::mobs::{Species, finalize}; + let registries = finalize::SpawnRegistries::load(&root); + for (species, registry) in [ + (Species::Pig, ®istries.pig_sound), + (Species::Cow, ®istries.cow_sound), + (Species::Chicken, ®istries.chicken_sound), + (Species::Cat, ®istries.cat_sound), + (Species::Wolf, ®istries.wolf_sound), + ] { + assert_eq!( + finalize::sound_variants(species), + registry.names, + "{species:?}" + ); + } + } } #[cfg(test)] diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f4086216d..9933f2a4e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -763,8 +763,9 @@ pub struct Extra { pub drop_chances: Option>, /// `Mob.leftHanded`. pub left_handed: bool, - /// The sound variant: index in the species' `*_sound_variant` registry. - pub sound_variant: u8, + /// The sound variant: index in the species' `*_sound_variant` registry + /// (`finalize::sound_variants`); None is the default, `classic`. + pub sound_variant: Option, /// `Zombie.canBreakDoors`. pub can_break_doors: bool, /// A goat's `IsScreamingGoat` and the horns it lost (left, right). diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 6e5daff1f..ccf4564ca 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1508,7 +1508,7 @@ impl Ctx<'_, L, R> { } fn sound(&mut self, m: &mut Mob, registry: fn(&SpawnRegistries) -> &VariantRegistry) { let r = registry(self.data.registries); - m.extra.sound_variant = r.random(self.random) as u8; + m.extra.sound_variant = Some(r.random(self.random) as u8); } /// `finalizeSpawn` of the mob's class. @@ -2014,6 +2014,17 @@ pub fn species_variant_component(s: Species, variant: u8) -> Option<(&'static st }; Some((component, format!("minecraft:{}", variant_name(s, variant)))) } +/// The `*_sound_variant` registry of a species, in registry order. +pub fn sound_variants(s: Species) -> &'static [&'static str] { + match s { + Species::Pig => &["big", "classic", "mini"], + Species::Cow => &["classic", "moody"], + Species::Chicken => &["classic", "picky"], + Species::Cat => &["classic", "royal"], + Species::Wolf => &["angry", "big", "classic", "cute", "grumpy", "puglin", "sad"], + _ => &[], + } +} /// The registry name of the game's variant index. pub fn variant_name(s: Species, index: u8) -> &'static str { let i = index as usize; From a55c82546773cc719e2e8dd291476c87be1b7686 Mon Sep 17 00:00:00 2001 From: FusselTV Date: Mon, 26 Oct 2026 21:46:35 +0100 Subject: [PATCH 095/195] Minecarts save HasTicked and Fire 0 AbstractMinecart saves Entity.firstTick as HasTicked, and a cart's fire stays 0: Entity.move sets it to -getFireImmuneTicks(), which is 0 for everything but players. A mineshaft's chest minecart was saved without HasTicked and with Fire -1; vanilla's generated chunk saves it with HasTicked 1 and Fire 0, and a cart that has ticked with HasTicked 0 and Fire 0. The mineshaft writes both as the proto chunk saves a new cart, and a cart keeps first_tick from its save until its first tick. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/minecarts.rs | 35 +++++++++++++++++++ .../src/worldgen/structure/mineshaft.rs | 3 ++ 2 files changed, 38 insertions(+) diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..dcb5421e2 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -90,6 +90,8 @@ pub(super) struct Minecart { /// Chest minecarts: the loot table rolled into `items` on load, saved /// again while the items are still that roll. pub loot: Option, + /// `Entity.firstTick`: not ticked yet (saved as `HasTicked`). + pub first_tick: bool, } pub(super) const WIDTH: f64 = 0.98; pub(super) const HEIGHT: f64 = 0.7; @@ -186,6 +188,7 @@ impl Minecart { fuse: -1, enabled: true, loot: None, + first_tick: true, } } pub fn bounds(&self) -> Aabb { @@ -536,6 +539,7 @@ impl Game<'_> { } /// `AbstractMinecart.tick` for one cart; returns false once it is gone. fn tick_cart(&mut self, c: &mut Minecart, intent: [f64; 2]) -> bool { + c.first_tick = false; c.previous = c.position; c.previous_yaw = c.yaw; c.hurt_time = (c.hurt_time - 1).max(0); @@ -1509,6 +1513,10 @@ impl Minecart { map.insert(JavaString::from(k), v); }; put("FlippedRotation", Tag::Byte(i8::from(self.flipped))); + // AbstractMinecart saves firstTick as HasTicked. A cart never burns: + // Entity.move sets -getFireImmuneTicks(), 0 for all but players. + put("HasTicked", Tag::Byte(i8::from(self.first_tick))); + put("Fire", Tag::Short(0)); match self.kind { CartKind::Chest | CartKind::Hopper => { put("Items", horizon_client::save::encode_items(&self.items)); @@ -1558,6 +1566,7 @@ impl Minecart { _ => 0.0, }; c.flipped = int("FlippedRotation").unwrap_or(0) != 0; + c.first_tick = int("HasTicked").unwrap_or(0) != 0; if kind.slots() > 0 { c.items = horizon_client::save::decode_items(tag.get("Items"), kind.slots()); } @@ -1582,4 +1591,30 @@ mod tests { assert_eq!(display_offset(CartKind::CommandBlock), 6.0); assert_eq!(display_offset(CartKind::Rideable), 6.0); } + + #[test] + fn a_cart_saves_as_never_ticked_until_it_ticks() { + use horizon_world::nbt::Tag; + let generated = Tag::compound([ + ("id", Tag::String("minecraft:chest_minecart".into())), + ( + "Pos", + Tag::List( + [0.5f64, 40.5, 0.5] + .map(|v| Tag::Double(v.to_bits())) + .to_vec(), + ), + ), + ("HasTicked", Tag::Byte(1)), + ("Fire", Tag::Short(0)), + ]); + let mut cart = Minecart::from_nbt(&generated, 1, CartKind::Chest).unwrap(); + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(1))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + cart.first_tick = false; + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(0))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + } } diff --git a/crates/horizon-world/src/worldgen/structure/mineshaft.rs b/crates/horizon-world/src/worldgen/structure/mineshaft.rs index 0c2d32c08..082afd0cd 100644 --- a/crates/horizon-world/src/worldgen/structure/mineshaft.rs +++ b/crates/horizon-world/src/worldgen/structure/mineshaft.rs @@ -616,6 +616,9 @@ impl MineshaftPiece { // A chest minecart with the mineshaft loot table. let seed = c.random.long(); let mut nbt = super::legacy::spawn_nbt("minecraft:chest_minecart", pos, false, false); + // As the proto chunk saves the new cart: not ticked, not burning. + nbt.insert("HasTicked".into(), Tag::Byte(1)); + nbt.insert("Fire".into(), Tag::Short(0)); let p = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, From a146754b0bad67a3985da78346bf8d2487009bfb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:28:10 +0100 Subject: [PATCH 096/195] Make the Particles option thin every particle, explosion debris and rain splash The Particles option only changed two effects. Follow ClientLevel.doAddParticle and calculateParticleLevel in the one add path: Decreased drops a third, Minimal drops all but the always-visible and limiter-overriding particles. Explosion block debris is thrown only on All, and rain splashes halve on Decreased and stop on Minimal. --- crates/horizon-client/src/animate_tick.rs | 12 ++-- crates/horizon-client/src/game/dragon.rs | 4 +- .../horizon-client/src/game/lan_particles.rs | 10 +-- .../src/game/level_particles.rs | 5 +- .../src/game/remote_projectiles.rs | 2 +- crates/horizon-client/src/game/render_tick.rs | 8 ++- crates/horizon-client/src/particles.rs | 64 ++++++++++++------- 7 files changed, 65 insertions(+), 40 deletions(-) diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 28b28544b..92445433e 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -357,6 +357,10 @@ impl AnimateContext<'_> { fn add(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { engine.add(&ParticleOptions::simple(ty), p, v); } +/// `Level.addAlwaysVisibleParticle`: still shown under the Minimal option now and then. +fn add_visible(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { + engine.add_with(&ParticleOptions::simple(ty), p, v, false, true); +} fn sound(engine: &mut ParticleEngine, name: &'static str, p: [f64; 3], volume: f32, pitch: f32) { engine.sounds.push((name, p, volume, pitch)); } @@ -869,7 +873,7 @@ fn block_animate_tick( fy + 1.0 + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::SulfurBubbles, p, [0.0; 3]); + add_visible(engine, T::SulfurBubbles, p, [0.0; 3]); } if next_int(engine.random(), 10) == 0 { let name = "minecraft:block.potent_sulfur.noxious_gas"; @@ -1086,7 +1090,7 @@ fn block_animate_tick( } Animate::BubbleColumn { drag } => { if drag { - add(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); + add_visible(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); @@ -1099,7 +1103,7 @@ fn block_animate_tick( ); } } else { - add( + add_visible( engine, T::BubbleColumnUp, [fx + 0.5, fy, fz + 0.5], @@ -1111,7 +1115,7 @@ fn block_animate_tick( fy + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); + add_visible(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..f7df7c816 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2127,10 +2127,12 @@ impl Game<'_> { c.at[1], c.at[2] + f64::from(a.sin() * d), ]; - self.particles.add( + self.particles.add_with( &ParticleOptions::simple(ParticleType::DragonBreath), at, [0.0, 0.0, 0.0], + false, + true, ); } // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index c41fdf1ad..dc014cd57 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -151,14 +151,10 @@ impl Game<'_> { return; }; let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); - // ClientLevel.addParticle: the camera's 32 blocks unless the packet - // (`force`) or the type overrides the limiter. + // ClientLevel.addParticle: the camera's 32 blocks and the Particles + // option, unless the packet or the type overrides the limiter. let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { - if p.override_limiter { - particles.create(&options, at, v); - } else { - particles.add(&options, at, v); - } + particles.add_with(&options, at, v, p.override_limiter, p.always_show); }; if p.count == 0 { add( diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..ca7d71a46 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -9,13 +9,12 @@ use horizon_world::level::LevelEvent; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { - self.particles - .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); + self.particles.block_teleportation(pos, data, [16, 8, 16]); } /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { self.particles - .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); + .block_teleportation(pos, data, [127, 127, 127]); } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 897999c6b..b8a747624 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -452,7 +452,7 @@ impl Game<'_> { ]; (c.particle.clone(), v) }; - self.particles.add(&options, at, velocity); + self.particles.add_with(&options, at, velocity, false, true); } } } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..c9e4c6fb0 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -244,6 +244,7 @@ impl Game<'_> { 1.0, ); } + self.particles.particle_level = self.settings.particles; if let Some(e) = eye { self.particles.camera = e; } @@ -292,7 +293,8 @@ impl Game<'_> { let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); let radius = 10; let diameter = 2 * radius + 1; - let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; + let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32 + / if self.settings.particles == 1 { 2 } else { 1 }; for _ in 0..count { let x = block[0] + random.next_int_bound(diameter).unwrap_or(0) - radius; let z = block[2] + random.next_int_bound(diameter).unwrap_or(0) - radius; @@ -304,6 +306,10 @@ impl Game<'_> { { continue; } + // The Minimal option stops at the first spot that rains. + if self.settings.particles >= 2 { + break; + } let below = top - 1; let (bx, bz) = (random.next_double(), random.next_double()); let state = world.block(x, below, z); diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..1a5cd979b 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1188,6 +1188,8 @@ pub struct ParticleEngine { emitters: Vec<(ParticleOptions, [f64; 3], f64, f64, u32)>, /// Camera position for the 32-block spawn limiter. pub camera: [f64; 3], + /// The Particles option (`ParticleStatus`): 0 all, 1 decreased, 2 minimal. + pub particle_level: u8, /// FireworkParticles.Starter instances. starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). @@ -1218,6 +1220,7 @@ impl ParticleEngine { emitters: Vec::new(), starters: Vec::new(), camera: [0.0; 3], + particle_level: 0, sounds: Vec::new(), made: Default::default(), item_sprites: HashMap::new(), @@ -1328,30 +1331,48 @@ impl ParticleEngine { &mut self.level_random } /// `ClientLevel.addParticle`: dropped beyond 32 blocks of the camera unless - /// the type overrides the limiter. + /// the type overrides the limiter, and thinned by the Particles option. pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { + self.add_with(options, p, v, false, false); + } + /// `ClientLevel.addParticle(particle, overrideLimiter, alwaysShow, ...)` + /// (`doAddParticle`). `always_show` is `addAlwaysVisibleParticle`'s flag. + pub fn add_with( + &mut self, + options: &ParticleOptions, + p: [f64; 3], + v: [f64; 3], + override_limiter: bool, + always_show: bool, + ) { let c = self.camera; let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); if let Some(requested) = &mut self.requested { requested.push((options.clone(), p, v)); return; } - if !options.ty.override_limiter() && d2 > 1024.0 { - return; + let minimal = self.calculate_particle_level(always_show) == 2; + if override_limiter || options.ty.override_limiter() || (d2 <= 1024.0 && !minimal) { + self.create(options, p, v); } - self.create(options, p, v); + } + /// `ClientLevel.calculateParticleLevel`: minimal still shows one in ten + /// always-visible particles as decreased, and decreased drops a third. + fn calculate_particle_level(&mut self, always_show: bool) -> u8 { + let mut level = self.particle_level.min(2); + if always_show && level == 2 && self.level_random.next_int_bound(10).unwrap_or(0) == 0 { + level = 1; + } + if level == 1 && self.level_random.next_int_bound(3).unwrap_or(0) == 0 { + level = 2; + } + level } /// `LevelEventHandler.singleBlockTeleportationParticles` towards /// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon /// egg's event 2015 packs offsets within (16, 8, 16), a consumable's /// teleport (2017) within (127, 127, 127). - pub fn block_teleportation( - &mut self, - from: [i32; 3], - data: i32, - radius: [i32; 3], - particle_level: u8, - ) { + pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, radius: [i32; 3]) { let to = [ from[0].wrapping_add(((data >> 16) & 255) - radius[0]), from[1].wrapping_add(((data >> 8) & 255) - radius[1]), @@ -1369,15 +1390,7 @@ impl ParticleEngine { to[1] + t * (from[1] - to[1]) + r.next_double() - 0.5, to[2] + t * (from[2] - to[2]) + (r.next_double() - 0.5) + 0.5, ]; - // The option roll shares the level random and precedes the distance check. - let limited = match particle_level { - 1 => r.next_int_bound(3).unwrap_or(0) == 0, - 2 => true, - _ => false, - }; - if !limited { - self.add(&options, position, velocity); - } + self.add(&options, position, velocity); } } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the @@ -1406,6 +1419,10 @@ impl ParticleEngine { block_count: usize, is_air: &dyn Fn([i32; 3]) -> bool, ) { + // ClientExplosionTracker.tick: only the All option throws the debris. + if self.particle_level != 0 { + return; + } for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( @@ -3970,7 +3987,7 @@ mod tests { let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new()); engine.seed_randoms(0, 0, 0); // Destination offset (-15, 7, 15); the unused top byte is ignored. - engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0); + engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16]); assert_eq!(engine.pending.len(), 128); assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); let first = &engine.pending[0]; @@ -3997,7 +4014,7 @@ mod tests { // TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition // of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4). let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127); - engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0); + engine.block_teleportation([4, 12, -5], data, [127, 127, 127]); assert_eq!(engine.pending.len(), 128); for p in &engine.pending { let [x, y, z] = p.position; @@ -4023,7 +4040,8 @@ mod tests { if distant { engine.camera = [1000.0; 3]; } - engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option); + engine.particle_level = option; + engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16]); assert_eq!(engine.pending.len(), if distant { 0 } else { count }); assert_eq!(engine.level_random.state(), state); } From cb488cf51591d7a948b948bbcccc1c2123935823 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:29:18 +0100 Subject: [PATCH 097/195] Rain splashes follow the Weather Radius and the Weather option Splashes always used a radius of 10 blocks; vanilla uses the Weather Radius option. The Horizon Weather toggle now also stops the splashes and the rain sound, not only the falling rain. --- crates/horizon-client/src/game.rs | 15 +++++++++------ crates/horizon-client/src/game/render_tick.rs | 7 ++++--- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 807a1d2cf..605732b3c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9910,12 +9910,15 @@ impl Game<'_> { } else { ("minecraft:weather.rain", 0.2, 1.0) }; - self.audio.play( - name, - Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), - volume, - pitch, - ); + // The Horizon Weather option off silences the rain too. + if self.settings.horizon.weather { + self.audio.play( + name, + Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), + volume, + pitch, + ); + } } } } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..04c4660d8 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -287,10 +287,11 @@ impl Game<'_> { e[2].floor() as i32, ]; animate_tick(self.res.animate(), &mut self.particles, &ctx, block); - if rain > 0.0 { - // ClientLevel.tickWeatherEffects: rain splashes (weather radius 10). + // The Horizon Weather option off means no rain visuals at all. + if rain > 0.0 && self.settings.horizon.weather { + // ClientLevel.tickWeatherEffects: rain splashes within the weather radius. let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); - let radius = 10; + let radius = self.settings.weather_radius; let diameter = 2 * radius + 1; let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; for _ in 0..count { From 190cf4e0c27e3b2a8485c1706397d48771239015 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:30:03 +0100 Subject: [PATCH 098/195] Changing Chunk Builder sets the graphics preset to Custom --- crates/horizon-client/src/options_ui.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 61fda9878..ac23bba9b 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -680,6 +680,7 @@ impl Opt { | Opt::CutoutLeaves | Opt::ImprovedTransparency | Opt::MenuBlur + | Opt::ChunkBuilder ) } /// Advance a cycle button (CycleButton.cycleValue). From 1596b8429921fc07f98620908b61c6d21c90ab45 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:37:24 +0100 Subject: [PATCH 099/195] Create New World: the Game Rules button opens the rules screen and the choices are saved with the world --- crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/lan_screen.rs | 8 +- .../horizon-client/src/game/startup_menu.rs | 5 ++ .../horizon-client/src/game/world_loading.rs | 2 + .../src/{game => }/game_rules_screen.rs | 68 +++++++++------- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/title.rs | 79 +++++++++++++++++++ .../horizon-client/src/title/create_world.rs | 8 +- crates/horizon-client/src/title/tests.rs | 7 +- 9 files changed, 140 insertions(+), 42 deletions(-) rename crates/horizon-client/src/{game => }/game_rules_screen.rs (91%) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..a82c23692 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -62,7 +62,6 @@ mod frames; mod friends; mod functions; mod game_mode; -mod game_rules_screen; mod gamemode_switcher; mod ghasts; mod golems; @@ -11879,7 +11878,8 @@ impl ApplicationHandler for Game<'_> { let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height)); t.press_field(atlas, self.cursor, (b.width, b.height), shift); - clicked + let rules = t.press_rules(atlas, self.cursor, (b.width, b.height)); + (clicked.0, clicked.1 || rules) }); self.save_title_options(); if sound { diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 260cc76c3..055d1ea1f 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -5,14 +5,10 @@ //! forcing the game mode. Its difficulty lock asks first (PopupScreen), and //! Restrictions opens RestrictionsScreen. //! Parity reference: https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/WorldOptionsScreen -use super::{ - Game, Screen, - game_rules_screen::{Exit, RulesScreen}, - integrated::ServerOptions, - lan::LanSettings, -}; +use super::{Game, Screen, integrated::ServerOptions, lan::LanSettings}; use horizon_client::{ font::Font, + game_rules_screen::{Exit, RulesScreen}, hud::{HudBatch, rgba}, text::{Text, named_color}, ui::{self, EditBox}, diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index ed5971324..fdeb726ae 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -546,6 +546,11 @@ impl Loading { (batch.width, batch.height), self.menu.modifiers.shift_key(), ); + title.press_rules( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + ); self.menu_action(event_loop, action); } } diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index e9ee8e3e8..7aa55d21d 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -94,6 +94,8 @@ impl WorldRequest { level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); level.allow_commands = Some(o.commands(creative)); horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + // WorldCreationUiState.getGameRules, written with the level. + level.game_rules = o.rules.by_name(); } // Worlds made without the Create New World screen (--world, the // control socket) take its default: commands on for Creative only. diff --git a/crates/horizon-client/src/game/game_rules_screen.rs b/crates/horizon-client/src/game_rules_screen.rs similarity index 91% rename from crates/horizon-client/src/game/game_rules_screen.rs rename to crates/horizon-client/src/game_rules_screen.rs index 0992f7689..7f7c307b6 100644 --- a/crates/horizon-client/src/game/game_rules_screen.rs +++ b/crates/horizon-client/src/game_rules_screen.rs @@ -1,8 +1,9 @@ -//! InWorldGameRulesScreen (AbstractGameRulesScreen), opened from World -//! Options: the rules by category under a search box, a switch or a number -//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket). -//! Leaving with changes asks first (ConfirmScreen). -use horizon_client::{ +//! AbstractGameRulesScreen: the rules by category under a search box, a +//! switch or a number box each. InWorldGameRulesScreen, opened from World +//! Options, sends the changed ones on Done (ServerboundSetGameRulePacket) and +//! asks before leaving with changes (ConfirmScreen); WorldCreationGameRulesScreen, +//! opened from Create New World, hands them back and leaves without asking. +use crate::{ confirm_screen::Confirm, font::Font, gamerules::{self, GameRules, RULES, Rule, Value}, @@ -32,14 +33,14 @@ enum Row { /// What a click or Escape asks of World Options. #[derive(Debug, PartialEq)] -pub(super) enum Exit { +pub enum Exit { /// Done: the rules that changed. Apply(Vec<(&'static str, Value)>), /// Cancel, or discarding the changes. Discard, } -pub(super) struct RulesScreen { +pub struct RulesScreen { search: EditBox, values: GameRules, initial: GameRules, @@ -49,6 +50,8 @@ pub(super) struct RulesScreen { scroll: ui::Scroll, /// ConfirmScreen "Game Rule Changes" in its place. confirm: bool, + /// InWorldGameRulesScreen rather than WorldCreationGameRulesScreen. + in_world: bool, } fn name_key(r: &Rule) -> String { @@ -102,7 +105,15 @@ fn confirm(font: &Font, size: (f32, f32)) -> Confirm { } impl RulesScreen { - pub(super) fn new(rules: &GameRules) -> Self { + /// InWorldGameRulesScreen over the world's rules. + pub fn new(rules: &GameRules) -> Self { + Self::build(rules, true) + } + /// WorldCreationGameRulesScreen over the new world's rules. + pub fn for_creation(rules: &GameRules) -> Self { + Self::build(rules, false) + } + fn build(rules: &GameRules, in_world: bool) -> Self { // setInitialFocus: the search box. let search = EditBox::new(0.0, 0.0, SEARCH_WIDTH, 15.0); let numbers = RULES @@ -123,6 +134,7 @@ impl RulesScreen { numbers, scroll: ui::Scroll::default(), confirm: false, + in_world, } } @@ -197,9 +209,10 @@ impl RulesScreen { }) .collect() } - /// InWorldGameRulesScreen.onClose: pending changes ask first. + /// InWorldGameRulesScreen.onClose: pending changes ask first; + /// WorldCreationGameRulesScreen.onClose discards them. fn close(&mut self) -> Option { - if self.changes().is_empty() { + if !self.in_world || self.changes().is_empty() { Some(Exit::Discard) } else { self.confirm = true; @@ -207,7 +220,7 @@ impl RulesScreen { } } /// Escape: ConfirmScreen answers no; the rules close. - pub(super) fn escape(&mut self) -> Option { + pub fn escape(&mut self) -> Option { if self.confirm { self.confirm = false; None @@ -216,7 +229,7 @@ impl RulesScreen { } } /// The mouse wheel (AbstractSelectionList: half an entry a step). - pub(super) fn wheel(&mut self, delta: f32, h: f32) { + pub fn wheel(&mut self, delta: f32, h: f32) { if !self.confirm { let content = self.content(); self.scroll @@ -224,20 +237,20 @@ impl RulesScreen { } } /// A press on the scrollbar holds it (AbstractSelectionList.updateScrolling). - pub(super) fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool { + pub fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool { let content = self.content(); self.scroll .press(cursor, Self::bar(w), HEADER, h - FOOTER, content) } /// The pointer moved while the scrollbar is held. - pub(super) fn drag(&mut self, y: f32, h: f32) { + pub fn drag(&mut self, y: f32, h: f32) { if self.scroll.held() { let content = self.content(); self.scroll.drag(y, HEADER, h - FOOTER, content); } } /// The button came up: the scrollbar lets go. - pub(super) fn release(&mut self) { + pub fn release(&mut self) { self.scroll.release(); } fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> { @@ -272,7 +285,7 @@ impl RulesScreen { } } /// Run an edit on the focused box, then its responder. - pub(super) fn edit(&mut self, f: impl FnOnce(&mut EditBox)) { + pub fn edit(&mut self, f: impl FnOnce(&mut EditBox)) { let Some((rule, b)) = self.focused() else { return; }; @@ -282,12 +295,12 @@ impl RulesScreen { self.edited(rule); } } - pub(super) fn typing(&self) -> bool { + pub fn typing(&self) -> bool { !self.confirm && (self.search.focused || self.numbers.iter().any(|(_, b)| b.focused)) } /// A left click; Some when the screen closes. - pub(super) fn click( + pub fn click( &mut self, atlas: &HudAtlas, cursor: (f32, f32), @@ -355,12 +368,7 @@ impl RulesScreen { } } /// Whether a click lands on a button (for its sound). - pub(super) fn clicks_button( - &self, - atlas: &HudAtlas, - cursor: (f32, f32), - size: (f32, f32), - ) -> bool { + pub fn clicks_button(&self, atlas: &HudAtlas, cursor: (f32, f32), size: (f32, f32)) -> bool { let (w, h) = size; let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0); if self.confirm { @@ -377,9 +385,9 @@ impl RulesScreen { }) } - pub(super) fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { + pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { let (w, h) = (batch.width, batch.height); - ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world); if self.confirm { let labels = [ Text::translate("gui.yes", &[]), @@ -393,7 +401,7 @@ impl RulesScreen { self.scroll.clamp(HEADER, h - FOOTER, content); // RuleList: the in-world list background, its entries clipped to it, // then the separators and scrollbar. - ui::list_background(batch, atlas, HEADER, h - FOOTER, true); + ui::list_background(batch, atlas, HEADER, h - FOOTER, self.in_world); let first = batch.vertices.len(); let hovered = self.hovered(rows.len(), cursor, (w, h)); let (left, x) = (row_left(w), control_x(w)); @@ -450,7 +458,7 @@ impl RulesScreen { } } batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); - ui::separators(batch, atlas, HEADER, h - FOOTER, true); + ui::separators(batch, atlas, HEADER, h - FOOTER, self.in_world); ui::scrollbar( batch, atlas, @@ -526,8 +534,8 @@ mod tests { #[test] fn box_colours_are_vanillas() { - assert_eq!(VALID, horizon_client::hud::rgba(224, 224, 224, 255)); - assert_eq!(INVALID, horizon_client::hud::rgba(255, 0, 0, 255)); + assert_eq!(VALID, crate::hud::rgba(224, 224, 224, 255)); + assert_eq!(INVALID, crate::hud::rgba(255, 0, 0, 255)); } #[test] diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index ebfbdea58..c2b308817 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -79,6 +79,7 @@ pub mod fog; pub mod font; pub mod friends_screen; pub mod game_mode_switcher; +pub mod game_rules_screen; pub mod gamepad; pub mod gamerules; pub mod gfx; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 87bd05fd0..9984cdcdf 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1,6 +1,7 @@ //! Title, world selection and world creation screens (TitleScreen, //! SelectWorldScreen, CreateWorldScreen layouts), drawn as HUD quads. use crate::{ + game_rules_screen::{Exit, RulesScreen}, hud::{HudAtlas, HudBatch, rgba}, lang, save::Level, @@ -144,6 +145,8 @@ pub struct Title { splash: Option, /// The saves listed for Home, re-read every couple of seconds. recent: std::cell::RefCell)>>, + /// WorldCreationGameRulesScreen, over Create New World while it is open. + rules: RefCell>, } pub(crate) struct Button { x: f32, @@ -252,6 +255,7 @@ impl Title { (today.month(), today.day()), ), recent: std::cell::RefCell::new(None), + rules: RefCell::new(None), } } /// Vanilla bypasses the selector when there are no saves. @@ -360,6 +364,9 @@ impl Title { } /// The pointer moved with the button held (`mouseDragged`). pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { + if let Some(rules) = self.rules.get_mut() { + return rules.drag(cursor.1, size.1.ceil()); + } if let Mode::Multiplayer(screen) = &mut self.mode { return screen.drag(cursor.1, size); } @@ -372,6 +379,9 @@ impl Title { } /// The button was released (`onRelease`). pub fn release(&mut self) { + if let Some(rules) = self.rules.get_mut() { + rules.release(); + } if let Mode::Multiplayer(screen) = &mut self.mode { screen.release(); } @@ -379,6 +389,9 @@ impl Title { } /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Some(rules) = self.rules.get_mut() { + return rules.wheel(delta, size.1.ceil()); + } if let Mode::Multiplayer(screen) = &mut self.mode { screen.wheel(delta, cursor, size); return; @@ -566,6 +579,10 @@ impl Title { folder } fn buttons(&self, w: f32, h: f32) -> Vec