From a7ff22eea05de72275341d7346252fc5d2ecdbb6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 23:05:12 +0100 Subject: [PATCH 001/102] 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/102] 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/102] 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/102] 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/102] 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/102] 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 5c0f7142f36cad8e1a1e7adffe3c6c5902328edb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:03:44 +0100 Subject: [PATCH 007/102] 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 6bc8a8b8899fc5be2e6c03485db8b6b9b47ff05d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:09:45 +0100 Subject: [PATCH 008/102] 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 009/102] 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 010/102] 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 011/102] 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 012/102] 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 013/102] 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 014/102] 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 015/102] 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 016/102] 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 017/102] 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 018/102] 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 019/102] 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 020/102] 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 a5fa40d2eea6609a3c567601059cdcf29415c4a3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:12:48 +0100 Subject: [PATCH 021/102] 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 022/102] 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 023/102] 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 e2a399aff0ee5463e9059a9a3dd49cb67e5167db Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:19 +0100 Subject: [PATCH 024/102] 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 84aba7b3d494f6d1315214c41a27464e14e8be87 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:27 +0100 Subject: [PATCH 025/102] 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 79bfb8fcb81860893bd4664d4f3e86effd015eef Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:26 +0100 Subject: [PATCH 026/102] 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 4c72a3a44f41278aa0481f95acf0d184bf540421 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:42 +0100 Subject: [PATCH 027/102] 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 028/102] 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 029/102] 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 030/102] 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 031/102] 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 032/102] 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 728bf14aa7db38211cd50d751f38486194d28de3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:06 +0100 Subject: [PATCH 033/102] 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 601e7918a844884574222a26ec75d05169499386 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:43 +0100 Subject: [PATCH 034/102] 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 035/102] 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 036/102] 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 037/102] 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 038/102] 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 039/102] 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 2f3dade42ffd73511b597f8993b3f94b564ca310 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:19:53 +0100 Subject: [PATCH 040/102] 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 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 041/102] 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 7a3a19697a75e9f7bcf42da70d9f665b7937239c Mon Sep 17 00:00:00 2001 From: socksprox Date: Mon, 26 Oct 2026 18:13:22 +0100 Subject: [PATCH 042/102] 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 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 043/102] 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 044/102] 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 91d6bdba85be4bc2f81b5f44ab896257799ecbf5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:11:21 +0100 Subject: [PATCH 045/102] 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 046/102] 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 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 047/102] 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 048/102] 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 049/102] 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 a529be89156d129a359fdfc1004390ecc3f82045 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:40:21 +0100 Subject: [PATCH 050/102] 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 6977659843800ded64f86b48ad744b9e0c940eb8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:06:50 +0100 Subject: [PATCH 051/102] 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 cb488cf51591d7a948b948bbcccc1c2123935823 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:29:18 +0100 Subject: [PATCH 052/102] 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 053/102] 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 054/102] 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