From 408a75aeb32f1f1e34d03f4ff9a42098fcf8514b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 11:45:03 +0100 Subject: [PATCH 001/221] Decorated pot: draw one face of its top and bottom planes --- .../horizon-client/src/block_entity_render.rs | 23 ++++++++++++++++++- .../horizon-client/src/item_render/special.rs | 2 +- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 10c5e2509..3d8c0258b 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -66,6 +66,24 @@ impl ModelPart { children, } } + /// `parse` of the entity model layer `layer`. Vanilla culls back faces for the pot's + /// `top` and `bottom` planes (`DecoratedPotRenderer.createBaseLayer`), so only the + /// up face of `top` and the down face of `bottom` show; ours draws both faces of each + /// plane, which fight for the same pixels, so the culled face is dropped here. + pub fn parse_layer(layer: &str, v: &Value) -> Self { + let mut part = Self::parse(v); + if layer == "minecraft:decorated_pot_base#main" { + // `ModelPart.Cube` polygon order: down, up, west, north, east, south. + for (name, face) in [("top", 1), ("bottom", 0)] { + if let Some((_, plane)) = part.children.iter_mut().find(|(n, _)| n == name) + && let Some(&polygon) = plane.polygons.get(face) + { + plane.polygons = vec![polygon]; + } + } + } + part + } pub fn child(&self, name: &str) -> Option<&ModelPart> { self.children .iter() @@ -794,7 +812,10 @@ impl BlockEntityRenderer { let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; let models = MODELS .iter() - .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) + .filter_map(|(key, layer)| { + all.get(*layer) + .map(|v| (*key, ModelPart::parse_layer(layer, v))) + }) .collect(); let mut renderer = Self::new(models, registry); renderer.visibility = Some(Mutex::new(crate::models::load_visibility(root, registry)?)); diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index d42378db1..6f4980169 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -60,7 +60,7 @@ pub(super) fn load_parts(root: &Path) -> HashMap { .chain(COPPER_GOLEM_LAYERS.iter()) .filter_map(|(key, layer)| { all.get(*layer) - .map(|v| ((*key).to_owned(), ModelPart::parse(v))) + .map(|v| ((*key).to_owned(), ModelPart::parse_layer(layer, v))) }) .collect() } From 946f47b3ec6c79f21a67e4637f24869285321de4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 12:48:36 +0100 Subject: [PATCH 002/221] Keep a happy ghast solid and still under a rider who gets off it On the server thread the window never learned the ghast was on its still timeout, and its copy trailed the server's, so a rider dropped through the ghast and the ghast flew off. Sync STAYS_STILL, assume the timeout on dismount, and put the window's ghast under the landing spot. --- crates/horizon-client/src/game/lan.rs | 11 ++++++ crates/horizon-client/src/game/remote.rs | 38 +++++++++++++++++++ .../src/game/remote_mob_data.rs | 4 ++ .../src/game/remote_vehicles.rs | 11 ++++++ 4 files changed, 64 insertions(+) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 50fa222e6..4b028ee9f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -264,6 +264,14 @@ fn mob_meta( meta.push((19, serializer::BOOLEAN, Value::Bool(true))); } } + // HappyGhast.STAYS_STILL (after AgeableMob's two and IS_LEASH_HOLDER), + // set while `serverStillTimeout > 0` (`syncStayStillFlag`). + "minecraft:happy_ghast" => { + if horizon_client::mobs::happy_ghast::on_still_timeout(m) { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } // Villager.DATA_VILLAGER_DATA and ZombieVillager's (after Zombie's three). "minecraft:villager" | "minecraft:zombie_villager" => { use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; @@ -836,6 +844,9 @@ impl Game<'_> { e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; mob_meta(m, hub, &mut e.meta, &mut e.defaults); + // HappyGhast.aiStep: requiresPrecisePosition while on a still timeout. + e.precise = m.species() == horizon_client::mobs::Species::HappyGhast + && horizon_client::mobs::happy_ghast::on_still_timeout(m); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); e.leash = leash; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5651647b7..eda1e2aca 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -154,6 +154,9 @@ pub(super) struct Remote { stepped: HashMap, /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. head_lerps: HashMap, + /// The happy ghast the player just got off, until the server's teleport + /// puts the player on top of it (`place_ghast_under`). + pub(super) ghast_dismount: Option, /// Item entities waiting for their item data: where they are and their /// motion. pending_items: HashMap, @@ -451,6 +454,7 @@ impl Game<'_> { lerps: HashMap::new(), stepped: HashMap::new(), head_lerps: HashMap::new(), + ghast_dismount: None, pending_items: HashMap::new(), health: (20.0, 20, 5.0), flash_on_set_health: false, @@ -2969,6 +2973,37 @@ impl Game<'_> { p.health.food.saturation = saturation; } } + /// `ServerPlayer.dismountTo` lands a rider at the ghast's own (x, maxY, z) + /// (`HappyGhast.getDismountLocationForPassenger`). A vanilla client + /// simulates the ghast it rides, so its copy is where the server has it; + /// this window's copy trails the server's by the stepped interpolation and + /// would rise into the rider's feet, which lets the rider fall through. + /// Put the copy under the landing spot. + fn place_ghast_under(&mut self, id: u32, spot: Vec3) { + let Some(m) = self + .mobs + .iter_mut() + .find(|m| m.id == id && m.species() == horizon_client::mobs::Species::HappyGhast) + else { + return; + }; + let at = Vec3::new(spot.x, spot.y - f64::from(m.height()), spot.z); + // Only a teleport that is that dismount: right above the ghast. + if (at.x - m.position.x).powi(2) + (at.z - m.position.z).powi(2) > 25.0 + || (at.y - m.position.y).abs() > 5.0 + { + return; + } + m.position = at; + m.previous = at; + if let Some(handler) = self + .remote + .as_mut() + .and_then(|r| r.stepped.get_mut(&(id as i32))) + { + handler.cancel(); + } + } /// ClientPacketListener.handleMovePlayer. fn remote_teleport(&mut self, p: &play::PlayerPosition) -> Result<()> { use play::relative as rel; @@ -3028,6 +3063,9 @@ impl Game<'_> { self.previous_position = position; self.yaw = yaw; self.pitch = pitch; + if let Some(id) = self.remote.as_mut().and_then(|r| r.ghast_dismount.take()) { + self.place_ghast_under(id, position); + } if let Some(r) = self.remote.as_mut() { // handleMovePlayer does not change LocalPlayer.sendPosition's // baseline: the next tick must still report the corrected state. diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index fbfc5a4fb..bde97febf 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -67,6 +67,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, + // HappyGhast.STAYS_STILL (after AgeableMob's two and IS_LEASH_HOLDER): + // `isOnStillTimeout` on a client, which keeps the ghast solid to + // the player (`canBeCollidedWith`). + (Species::HappyGhast, 19, Value::Bool(still)) => m.extra.counter = i32::from(*still), // SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose. (Species::Evoker | Species::Illusioner, 17, Value::Byte(spell)) => { m.extra.variant2 = (*spell).max(0) as u8; diff --git a/crates/horizon-client/src/game/remote_vehicles.rs b/crates/horizon-client/src/game/remote_vehicles.rs index 620aff97c..b3d031ff3 100644 --- a/crates/horizon-client/src/game/remote_vehicles.rs +++ b/crates/horizon-client/src/game/remote_vehicles.rs @@ -121,6 +121,17 @@ impl Game<'_> { } else if self.riding == Some(vehicle_id) { // The server takes the player out, then teleports it. self.riding = None; + // HappyGhast.removePassenger: a still timeout of 10 (the server's + // STAYS_STILL confirms it), and the rider lands on top of the ghast + // (`place_ghast_under`). + if let Some(m) = self.mobs.iter_mut().find(|m| { + m.id == vehicle_id && m.species() == horizon_client::mobs::Species::HappyGhast + }) { + m.extra.counter = 10; + if let Some(r) = self.remote.as_mut() { + r.ghast_dismount = Some(vehicle_id); + } + } } } From 5d72fdd8c24ce81f53a5f307cf8f0bc855852231 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 13:02:23 +0100 Subject: [PATCH 003/221] Add ambient effects for levers, repeaters, dripstone, wither roses, End gateways and lightning rods These blocks have an animateTick in vanilla but nothing happened around them in Horizon. Each gets the same particles and odds as vanilla. --- .../examples/probe/emitter_particles_probe.rs | 2 +- .../examples/probe/marker_particles_probe.rs | 4 + crates/horizon-client/src/animate_tick.rs | 236 +++++++++++++++++- .../horizon-client/src/block_entity_render.rs | 42 ++-- .../src/game/level_particles.rs | 2 +- crates/horizon-client/src/game/render_tick.rs | 14 ++ crates/horizon-client/src/particles.rs | 8 +- 7 files changed, 286 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/examples/probe/emitter_particles_probe.rs b/crates/horizon-client/examples/probe/emitter_particles_probe.rs index 6349eb8dc..949b306ff 100644 --- a/crates/horizon-client/examples/probe/emitter_particles_probe.rs +++ b/crates/horizon-client/examples/probe/emitter_particles_probe.rs @@ -54,7 +54,7 @@ pub fn main() -> Result<()> { match c["axis"].as_i64() { Some(axis @ 0..=2) => { let line = record("electric_spark"); - particles::along_axis(&mut random, axis as usize, p, |p, v| { + particles::along_axis(&mut random, axis as usize, p, (10, 19), |p, v| { lines.push(line(p, v)) }); } diff --git a/crates/horizon-client/examples/probe/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs index 72ebaff22..3041a84d7 100644 --- a/crates/horizon-client/examples/probe/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -75,6 +75,10 @@ pub fn main() -> Result<()> { registry: assets.registry, raining_at: &|_| false, marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)), + model_offset: &|_, _, _| None, + gateway_particles: &|_, _| 0, + thundering: false, + ultrawarm: false, }; engine.seed_randoms(1057, 0, 0); engine.requested = Some(Vec::new()); diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 48e8f16f4..ad160d787 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -8,7 +8,7 @@ use crate::{ blocks::{BlockFacts, Fluid}, command::args::GameMode, items::ItemStack, - particles::{ParticleEngine, ParticleOptions, ParticleType as T}, + particles::{ParticleEngine, ParticleOptions, ParticleType as T, along_axis}, world::World, }; use horizon_core::{ @@ -67,6 +67,22 @@ enum Animate { waterlogged: bool, }, EndPortal, + /// A powered lever: its facing and the direction it is attached toward. + Lever { + facing: [i32; 3], + connected: [i32; 3], + }, + /// A powered repeater. + Repeater { + facing: [i32; 3], + delay: i32, + }, + /// A free-hanging stalactite tip that is not waterlogged. + PointedDripstone, + WitherRose, + EndGateway, + /// A lightning rod, by the axis it points along (0, 1, 2 for X, Y, Z). + LightningRod(usize), } fn step(facing: &str) -> [i32; 3] { match facing { @@ -81,6 +97,7 @@ fn step(facing: &str) -> [i32; 3] { fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { let name = name.strip_prefix("minecraft:").unwrap_or(name); let lit = prop("lit").as_deref() == Some("true"); + let powered = prop("powered").as_deref() == Some("true"); let facing = || step(&prop("facing").unwrap_or_default()); match name { "torch" => Animate::Torch(T::Flame), @@ -145,6 +162,38 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { waterlogged: prop("waterlogged").as_deref() == Some("true"), }, "end_portal" => Animate::EndPortal, + "lever" if powered => Animate::Lever { + facing: facing(), + // FaceAttachedHorizontalDirectionalBlock.getConnectedDirection. + connected: match prop("face").as_deref() { + Some("ceiling") => [0, -1, 0], + Some("floor") => [0, 1, 0], + _ => facing(), + }, + }, + "repeater" if powered => Animate::Repeater { + facing: facing(), + delay: prop("delay").and_then(|d| d.parse().ok()).unwrap_or(1), + }, + "pointed_dripstone" + if prop("vertical_direction").as_deref() == Some("down") + && prop("thickness").as_deref() == Some("tip") + && prop("waterlogged").as_deref() != Some("true") => + { + Animate::PointedDripstone + } + "wither_rose" => Animate::WitherRose, + "end_gateway" => Animate::EndGateway, + _ if name == "lightning_rod" || name.ends_with("_lightning_rod") => { + let [dx, dy, _] = facing(); + Animate::LightningRod(if dx != 0 { + 0 + } else if dy != 0 { + 1 + } else { + 2 + }) + } "sculk_sensor" | "calibrated_sculk_sensor" if prop("sculk_sensor_phase").as_deref() == Some("active") => { @@ -192,6 +241,8 @@ pub struct AnimateTables { dried_ghast_sounds: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). ambient: Vec>, + /// Per state: 1 for a pointed dripstone, 2 for one whose tip points down. + dripstone: Vec, } impl AnimateTables { pub fn load(root: &Path, registry: &BlockRegistry, biomes: &Biomes) -> crate::Result { @@ -242,8 +293,25 @@ impl AnimateTables { } } } + let dripstone = (0..registry.len() as u32) + .map(|id| { + registry.state(BlockStateId(id)).map_or(0, |s| { + let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name); + if name != "pointed_dripstone" { + 0 + } else if s.properties.get("vertical_direction").map(String::as_str) + == Some("down") + { + 2 + } else { + 1 + } + }) + }) + .collect(); Ok(Self { kinds, + dripstone, impermeable: by_state("minecraft:impermeable"), power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), @@ -274,6 +342,14 @@ pub struct AnimateContext<'a> { pub raining_at: &'a dyn Fn([i32; 3]) -> bool, /// Creative main-hand marker block and a resolver for each placed state's sprite. pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option)>, + /// `BlockState.getOffset` of a state at (x, z), for blocks with a random model offset. + pub model_offset: &'a dyn Fn(BlockStateId, i32, i32) -> Option<[f64; 3]>, + /// `TheEndGatewayBlockEntity.getParticleAmount` of the gateway state at a position. + pub gateway_particles: &'a dyn Fn(BlockStateId, [i32; 3]) -> usize, + /// `Level.isThundering`. + pub thundering: bool, + /// The dimension has `water_evaporates` and drips lava from dripstone (the Nether). + pub ultrawarm: bool, } /// `ClientLevel.getMarkerParticleTarget`: only the selected main-hand item counts. @@ -322,6 +398,9 @@ impl AnimateContext<'_> { ], )) } + fn offset_of(&self, state: BlockStateId, p: [i32; 3]) -> [f64; 3] { + (self.model_offset)(state, p[0], p[2]).unwrap_or([0.0; 3]) + } fn foliage(&self, p: [i32; 3]) -> u32 { let biome = self .world @@ -919,6 +998,99 @@ fn block_animate_tick( let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()]; add(engine, T::Smoke, p, [0.0; 3]); } + Animate::Lever { facing, connected } => { + // LeverBlock.animateTick: a powered lever puffs red dust a quarter of the time. + if engine.random().next_float() < 0.25 { + // LeverBlock.makeParticle with scale 0.5. + let at = |base: f64, i: usize| { + base + 0.5 + 0.1 * f64::from(-facing[i]) + 0.2 * f64::from(-connected[i]) + }; + let p = [at(fx, 0), at(fy, 1), at(fz, 2)]; + engine.add(&ParticleOptions::dust([1.0, 0.0, 0.0], 0.5), p, [0.0; 3]); + } + } + Animate::Repeater { facing, delay } => { + // RepeaterBlock.animateTick: dust at one of the torches. + let r = engine.random(); + let x = fx + 0.5 + (r.next_double() - 0.5) * 0.2; + let y = fy + 0.4 + (r.next_double() - 0.5) * 0.2; + let z = fz + 0.5 + (r.next_double() - 0.5) * 0.2; + let mut offset = -5.0f32; + if r.next_boolean() { + offset = (delay * 2 - 1) as f32; + } + offset /= 16.0; + let xo = f64::from(offset * facing[0] as f32); + let zo = f64::from(offset * facing[2] as f32); + redstone(engine, [x + xo, y, z + zo]); + } + Animate::PointedDripstone => dripstone_drip(tables, engine, ctx, state, pos), + Animate::WitherRose => { + // WitherRoseBlock.animateTick: smoke puffs at the centre of the shape. + let center = ctx.shape_y(pos).map_or([0.5; 2], |s| { + [(s.2[0] + s.2[1]) / 2.0, (s.2[2] + s.2[3]) / 2.0] + }); + let offset = ctx.offset_of(state, pos); + let x = fx + center[0] + offset[0]; + let z = fz + center[1] + offset[2]; + for _ in 0..3 { + let r = engine.random(); + if r.next_boolean() { + let p = [ + x + r.next_double() / 5.0, + fy + (0.5 - r.next_double()), + z + r.next_double() / 5.0, + ]; + add(engine, T::Smoke, p, [0.0; 3]); + } + } + } + Animate::EndGateway => { + // EndGatewayBlock.animateTick: portal particles, one for each visible face. + for _ in 0..(ctx.gateway_particles)(state, pos) { + let r = engine.random(); + let mut p = [ + fx + r.next_double(), + fy + r.next_double(), + fz + r.next_double(), + ]; + let mut v = [ + (r.next_double() - 0.5) * 0.5, + (r.next_double() - 0.5) * 0.5, + (r.next_double() - 0.5) * 0.5, + ]; + let flip = next_int(r, 2) * 2 - 1; + if r.next_boolean() { + p[2] = fz + 0.5 + 0.25 * f64::from(flip); + v[2] = f64::from(r.next_float() * 2.0 * flip as f32); + } else { + p[0] = fx + 0.5 + 0.25 * f64::from(flip); + v[0] = f64::from(r.next_float() * 2.0 * flip as f32); + } + add(engine, T::Portal, p, v); + } + } + Animate::LightningRod(axis) => { + // LightningRodBlock.animateTick: in a thunderstorm, sparks along the + // topmost rod, more often as the game time within 200 ticks grows. + if ctx.thundering + && i64::from(next_int(engine.level_random(), 200)) <= ctx.world.game_time % 200 + && pos[1] + == ctx + .world + .world_surface(pos[0], pos[2], |id| ctx.facts.is_air(id)) + - 1 + { + let mut sparks = Vec::new(); + along_axis(engine.level_random(), axis, pos, (1, 2), |p, v| { + sparks.push((p, v)); + }); + let options = ParticleOptions::simple(T::ElectricSpark); + for (p, v) in sparks { + engine.add(&options, p, v); + } + } + } Animate::EnderChest => { for _ in 0..3 { let r = engine.random(); @@ -1118,6 +1290,68 @@ fn block_animate_tick( } } } +/// `PointedDripstoneBlock.animateTick`: a free-hanging stalactite tip drips the +/// fluid above the root of its stalactite. +fn dripstone_drip( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + let roll = engine.random().next_float(); + if roll > 0.12 { + return; + } + // getFluidAboveStalactite: findRootBlock climbs at most ten blocks of + // stalactite and stops at the first block that is not pointed dripstone. + let mut root = None; + for step in 1..11 { + let p = [pos[0], pos[1] + step, pos[2]]; + match tables + .dripstone + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(0) + { + 0 => { + root = Some(p); + break; + } + 2 => {} + _ => return, + } + } + let Some(root) = root else { + return; + }; + let above = ctx.facts.get(ctx.state([root[0], root[1] + 1, root[2]])); + // Mud above the root counts as a water source unless water evaporates here. + let (fluid, source) = if &*above.name == "minecraft:mud" && !ctx.ultrawarm { + (Fluid::Water, true) + } else { + (above.fluid, above.fluid_level >= 8 && !above.fluid_falling) + }; + // canFillCauldron: only a water or lava source passes below a 2% roll. + if roll >= 0.02 && !(fluid != Fluid::None && source) { + return; + } + // getDripParticle: no fluid drips what the dimension's default says. + let lava = fluid == Fluid::Lava || (fluid == Fluid::None && ctx.ultrawarm); + let ty = if lava { + T::DrippingDripstoneLava + } else { + T::DrippingDripstoneWater + }; + let offset = ctx.offset_of(state, pos); + // STALACTITE_DRIP_START_PIXEL is the tip's lowest point, 5/16. + let p = [ + f64::from(pos[0]) + 0.5 + offset[0], + f64::from(pos[1]) + 0.3125 - 0.0625, + f64::from(pos[2]) + 0.5 + offset[2], + ]; + add(engine, ty, p, [0.0; 3]); +} /// `AbstractCandleBlock.addParticlesAndSound`. fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { let r = engine.random(); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 10c5e2509..b8146a63f 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -931,6 +931,30 @@ impl BlockEntityRenderer { let lights = diffuse_lights(scene.nether); self.render_one(scene, pos, kind, base, packed, lights, false, false, out); } + /// `TheEndGatewayBlockEntity.shouldRenderFace` for each face of the gateway + /// at `pos`: the faces its portal is drawn on. + pub fn gateway_faces( + &self, + world: &World, + state: BlockStateId, + pos: [i32; 3], + ) -> Vec { + Direction::ALL + .into_iter() + .filter(|&d| { + let [dx, dy, dz] = d.normal(); + let neighbor = world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); + self.visibility.as_ref().is_none_or(|v| { + v.lock() + .map(|mut v| { + v.should_render_face(state, neighbor, d, true) + .unwrap_or(true) + }) + .unwrap_or(true) + }) + }) + .collect() + } /// Whether this block state has a block-entity renderer here. pub fn renders(&self, state: u32) -> bool { !matches!(self.kind(state), Kind::None) @@ -1431,22 +1455,8 @@ impl BlockEntityRenderer { out, ); } - // AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace. - let faces: Vec = Direction::ALL - .into_iter() - .filter(|&d| { - let [dx, dy, dz] = d.normal(); - let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz); - self.visibility.as_ref().is_none_or(|v| { - v.lock() - .map(|mut v| { - v.should_render_face(BlockStateId(*state), neighbor, d, true) - .unwrap_or(true) - }) - .unwrap_or(true) - }) - }) - .collect(); + // AbstractEndPortalRenderer.extractRenderState. + let faces = self.gateway_faces(scene.world, BlockStateId(*state), pos); portal_cube(base, &faces, END_GATEWAY_LAYER, out); } Kind::Conduit => { diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index f12aedc5b..deb739f96 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -33,7 +33,7 @@ impl Game<'_> { // 3002 with an axis: a lightning rod; otherwise copper cleaned by lightning. match usize::try_from(data) { Ok(axis) if id == 3002 && axis < 3 => { - particles::along_axis(random, axis, p, |p, v| spawned.push((p, v))); + particles::along_axis(random, axis, p, (10, 19), |p, v| spawned.push((p, v))); } _ => particles::on_block_faces(random, p, |p, v| spawned.push((p, v))), } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..45d777986 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -271,6 +271,16 @@ impl Game<'_> { && motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1] && rains_at(world, biomes, p[0], p[1], p[2]) }; + let tables = &self.pack.context.tables; + let model_offset = |state, x, z| tables.offset(state, x, z); + let gateway_particles = |state, p| { + self.res + .block_entity_render() + .gateway_faces(world, state, p) + .len() + }; + // Level.isThundering: a thunder level above 0.9 where the sky is open. + let thundering = self.dim == Dim::Overworld && world.weather.levels(1.0).1 > 0.9; let ctx = AnimateContext { world, facts, @@ -279,6 +289,10 @@ impl Game<'_> { registry: self.pack.assets.registry, raining_at: &raining_at, marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)), + model_offset: &model_offset, + gateway_particles: &gateway_particles, + thundering, + ultrawarm: self.dim == Dim::Nether, }; if let Some(e) = eye { let block = [ diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index fa9dc9c6e..0c43204e8 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -782,15 +782,17 @@ pub fn on_block_faces( } } /// `ParticleUtils.spawnParticlesAlongAxis(axis, level, pos, 0.125, particle, -/// UniformInt.of(10, 19))` (level event 3002 on a lightning rod): sparks along -/// the rod, moving along it. `axis` is 0, 1, 2 for X, Y, Z. +/// UniformInt.of(min, max))` (`count` is the range; level event 3002 on a +/// lightning rod uses 10 to 19): sparks along the rod, moving along it. +/// `axis` is 0, 1, 2 for X, Y, Z. pub fn along_axis( random: &mut impl RandomSource, axis: usize, pos: [i32; 3], + (min, max): (i32, i32), mut emit: impl FnMut([f64; 3], [f64; 3]), ) { - let count = random.next_int_bound(19 - 10 + 1).unwrap_or(0) + 10; + let count = random.next_int_bound(max - min + 1).unwrap_or(0) + min; for _ in 0..count { let p: [f64; 3] = std::array::from_fn(|i| { f64::from(pos[i]) From d338bcd070a6c2bf2568c1f57900bf222299929b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:16:31 +0100 Subject: [PATCH 004/221] Decorated pot: say why only the outer faces stay Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/block_entity_render.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 3d8c0258b..1bbc7a207 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -66,10 +66,10 @@ impl ModelPart { children, } } - /// `parse` of the entity model layer `layer`. Vanilla culls back faces for the pot's - /// `top` and `bottom` planes (`DecoratedPotRenderer.createBaseLayer`), so only the - /// up face of `top` and the down face of `bottom` show; ours draws both faces of each - /// plane, which fight for the same pixels, so the culled face is dropped here. + /// `parse` of the entity model layer `layer`. The pot's `top` and `bottom` are flat + /// boxes (`DecoratedPotRenderer.createBaseLayer`) drawn with a culling render type, so + /// from outside only `top`'s up face and `bottom`'s down face show. Both faces of each + /// plane would fight for the same pixels here: keep the outer one. pub fn parse_layer(layer: &str, v: &Value) -> Self { let mut part = Self::parse(v); if layer == "minecraft:decorated_pot_base#main" { From 27d750f1c9367ef8c66ca17752c1a21f284abdca Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:46:38 +0100 Subject: [PATCH 005/221] Split horizon-items out of horizon-client Second slice of the crate split, a pure move like the first: blocks (+ blocks/), items, item_data, enchant, cooldowns, bundle and random_sequences move to horizon-items. They are the first layer mobs/ needs, after horizon-client-core. Items moved out of lib modules that sit in the big cycle, unchanged: - firework shapes, explosions and dye colours (particles.rs) -> firework.rs; - BannerLayer and its NBT form (banner.rs) -> banner_layer.rs; - the ItemStack NBT codec (save.rs) -> item_nbt.rs; - consumable_animation (first_person.rs) -> use_animation.rs; - the content namespaces (mod_content.rs) -> content_namespaces.rs; - save.rs's NBT value helpers -> horizon-client-core's nbt_value.rs, and name_text (entity_nbt.rs) -> core's component.rs. horizon-client re-exports every module and item under its old path. Test helpers other client tests use (Items::for_tests, enchant::tests) are behind horizon-items' `test-support` feature, enabled by horizon-client's dev-dependency. The items test that loads the client's assets moved to the client: always_edible_and_consume_effects_loaded, to assets.rs. particles.rs' test module moved to the end of the file (clippy's items_after_test_module had been quiet only thanks to the derives that moved out). Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 +- Cargo.lock | 12 ++ Cargo.toml | 2 +- crates/horizon-client-core/src/component.rs | 10 ++ crates/horizon-client-core/src/lib.rs | 1 + crates/horizon-client-core/src/nbt_value.rs | 24 ++++ crates/horizon-client/Cargo.toml | 2 + .../examples/gameplay_decode_profile.rs | 2 +- crates/horizon-client/src/assets.rs | 78 +++++++++++ crates/horizon-client/src/banner.rs | 54 +------- crates/horizon-client/src/entity_nbt.rs | 10 +- crates/horizon-client/src/first_person.rs | 13 +- crates/horizon-client/src/lib.rs | 14 +- crates/horizon-client/src/mod_content.rs | 27 +--- crates/horizon-client/src/particles.rs | 122 +++++------------- crates/horizon-client/src/save.rs | 82 +----------- crates/horizon-items/Cargo.toml | 21 +++ crates/horizon-items/src/banner_layer.rs | 56 ++++++++ .../src/blocks.rs | 0 .../src/blocks/decode.rs | 0 .../src/blocks/decode_tests.rs | 0 .../src/bundle.rs | 0 .../horizon-items/src/content_namespaces.rs | 29 +++++ .../src/cooldowns.rs | 0 .../src/enchant.rs | 12 +- crates/horizon-items/src/firework.rs | 61 +++++++++ .../src/item_data.rs | 37 +++--- crates/horizon-items/src/item_nbt.rs | 62 +++++++++ .../src/items.rs | 83 +----------- crates/horizon-items/src/lib.rs | 19 +++ .../src/random_sequences.rs | 0 crates/horizon-items/src/use_animation.rs | 14 ++ docs/architecture.md | 7 +- tools/test_block_particles_parity.py | 2 +- tools/test_fire_starter_sound_parity.py | 2 +- tools/test_firework_tooltip_parity.py | 4 +- tools/test_lore_tooltip_parity.py | 2 +- 37 files changed, 484 insertions(+), 385 deletions(-) create mode 100644 crates/horizon-client-core/src/nbt_value.rs create mode 100644 crates/horizon-items/Cargo.toml create mode 100644 crates/horizon-items/src/banner_layer.rs rename crates/{horizon-client => horizon-items}/src/blocks.rs (100%) rename crates/{horizon-client => horizon-items}/src/blocks/decode.rs (100%) rename crates/{horizon-client => horizon-items}/src/blocks/decode_tests.rs (100%) rename crates/{horizon-client => horizon-items}/src/bundle.rs (100%) create mode 100644 crates/horizon-items/src/content_namespaces.rs rename crates/{horizon-client => horizon-items}/src/cooldowns.rs (100%) rename crates/{horizon-client => horizon-items}/src/enchant.rs (99%) create mode 100644 crates/horizon-items/src/firework.rs rename crates/{horizon-client => horizon-items}/src/item_data.rs (96%) create mode 100644 crates/horizon-items/src/item_nbt.rs rename crates/{horizon-client => horizon-items}/src/items.rs (95%) create mode 100644 crates/horizon-items/src/lib.rs rename crates/{horizon-client => horizon-items}/src/random_sequences.rs (100%) create mode 100644 crates/horizon-items/src/use_animation.rs diff --git a/AGENTS.md b/AGENTS.md index 24dc38b8e..a6406ebdc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | Crate | Owns | |---|---| -| `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-client` | The game: a lib (`src/lib.rs`, ~170 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | +| `horizon-items` | Blocks and items below gameplay: `blocks.rs` (block facts), `items.rs`, `item_data.rs` (components), `enchant.rs`, `cooldowns.rs`, `bundle.rs`, `item_nbt.rs`. Re-exported as `horizon_client::items`... | | `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` | | `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) | | `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | @@ -117,7 +118,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Block behaviour | `crates/horizon-world/src/level/` (`mod.rs`, `tick.rs`, `hooks.rs`, `redstone.rs`, `place.rs`, `interact.rs`); game.rs `fn tick_blocks`, `fn process_level_events` | | Mobs | L: `mobs.rs` (types), `mobs/` (`ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `species.rs`, `spawning.rs`, `render.rs`, `anim.rs`); G: `creatures.rs` (ticking, spawning, mob events), one file per mob family (`dragon.rs`, `wither.rs`, `villagers.rs`, `piglins.rs`, `golems.rs`...), `natural_spawning.rs` | | Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | -| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | +| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`; crate `horizon-items`: `items.rs`, `item_data.rs`, `enchant.rs`, `blocks.rs` | | Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | | Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` | | UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | diff --git a/Cargo.lock b/Cargo.lock index 1d3b52a3b..400355a70 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1370,6 +1370,7 @@ dependencies = [ "horizon-core", "horizon-dualsense", "horizon-friends", + "horizon-items", "horizon-mods", "horizon-protocol", "horizon-server-files", @@ -1445,6 +1446,17 @@ dependencies = [ "spake2", ] +[[package]] +name = "horizon-items" +version = "0.1.0" +dependencies = [ + "horizon-client-core", + "horizon-core", + "horizon-world", + "serde", + "serde_json", +] + [[package]] name = "horizon-mod-sdk" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 181ab1832..5af77974b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", "crates/horizon-command", "crates/horizon-items", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-client-core/src/component.rs b/crates/horizon-client-core/src/component.rs index 5b828b305..64ea6d75c 100644 --- a/crates/horizon-client-core/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -1,6 +1,7 @@ //! Text components from commands: `ComponentArgument` reads an SNBT (or JSON) //! value, `ComponentSerialization` turns it into styled text. use crate::text::{Style, Text, named_color}; +use horizon_world::nbt::Tag; use serde_json::{Map, Value}; /// `SnbtGrammar`, enough for components: compounds, lists, quoted and @@ -271,6 +272,15 @@ pub fn to_text_with( } } +/// `CustomName` as text: a string keeps its legacy formatting codes, anything +/// else is a component (`ComponentSerialization`). +pub fn name_text(tag: &Tag) -> Text { + match tag { + Tag::String(s) => Text::legacy(&s.to_string_lossy()), + t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs index ca40141d1..77516add3 100644 --- a/crates/horizon-client-core/src/lib.rs +++ b/crates/horizon-client-core/src/lib.rs @@ -13,6 +13,7 @@ pub mod identifier; pub mod key_display; pub mod lang; pub mod nbt_path; +pub mod nbt_value; pub mod particle_type; pub mod registries; pub mod scoreboard; diff --git a/crates/horizon-client-core/src/nbt_value.rs b/crates/horizon-client-core/src/nbt_value.rs new file mode 100644 index 000000000..7f7d728b0 --- /dev/null +++ b/crates/horizon-client-core/src/nbt_value.rs @@ -0,0 +1,24 @@ +//! Reading and writing single NBT values the way vanilla's codecs accept them. +use horizon_world::nbt::Tag; + +pub fn string(s: &str) -> Tag { + Tag::String(s.into()) +} +pub fn text(tag: Option<&Tag>) -> Option { + match tag { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } +} +/// Any numeric tag as i64 (vanilla's `getIntOr` etc. accept every number type). +pub fn number(tag: Option<&Tag>) -> Option { + Some(match tag? { + Tag::Byte(v) => i64::from(*v), + Tag::Short(v) => i64::from(*v), + Tag::Int(v) => i64::from(*v), + Tag::Long(v) => *v, + Tag::Float(b) => f32::from_bits(*b) as i64, + Tag::Double(b) => f64::from_bits(*b) as i64, + _ => return None, + }) +} diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 923a48a34..37a1560c0 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -11,6 +11,7 @@ description = "Horizon native development client" horizon-assets = { path = "../horizon-assets" } horizon-client-core = { path = "../horizon-client-core" } horizon-command = { path = "../horizon-command" } +horizon-items = { path = "../horizon-items" } horizon-core = { path = "../horizon-core" } # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). horizon-threads = { path = "../horizon-threads" } @@ -103,5 +104,6 @@ path = "examples/probe/main.rs" workspace = true [dev-dependencies] +horizon-items = { path = "../horizon-items", features = ["test-support"] } # Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests). naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] } diff --git a/crates/horizon-client/examples/gameplay_decode_profile.rs b/crates/horizon-client/examples/gameplay_decode_profile.rs index 60260452f..2731b9e88 100644 --- a/crates/horizon-client/examples/gameplay_decode_profile.rs +++ b/crates/horizon-client/examples/gameplay_decode_profile.rs @@ -2,7 +2,7 @@ //! Build with `cargo build --release -p horizon-client --example gameplay_decode_profile`. //! Each invocation runs one phase in a separate process for CPU/RSS measurements. #[allow(dead_code)] -#[path = "../src/blocks/decode.rs"] +#[path = "../../horizon-items/src/blocks/decode.rs"] mod decode; use std::{hint::black_box, path::Path, time::Instant}; diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index beafa96fd..99d169c93 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -234,3 +234,81 @@ impl RenderAssets { }) } } + +#[cfg(test)] +mod tests { + use crate::items::ConsumeEffect; + + #[test] + fn always_edible_and_consume_effects_loaded() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap(); + + let apple = items.get("minecraft:golden_apple").expect("golden apple"); + assert!(apple.can_always_eat); + assert!(apple.food.is_some()); + assert!(!apple.consumable.as_ref().unwrap().effects.is_empty()); + + let enchanted = items + .get("minecraft:enchanted_golden_apple") + .expect("enchanted golden apple"); + assert!(enchanted.can_always_eat); + assert!(enchanted.food.is_some()); + assert!(!enchanted.consumable.as_ref().unwrap().effects.is_empty()); + + let beef = items.get("minecraft:cooked_beef").expect("cooked beef"); + assert!(!beef.can_always_eat); + assert!(beef.food.is_some()); + + // Consumables without food, their style and their remainders. + use horizon_world::consumable::UseAnimation; + let milk = items.get("minecraft:milk_bucket").expect("milk bucket"); + let drink = milk.consumable.as_ref().unwrap(); + assert!(milk.food.is_none()); + assert_eq!(drink.effects, [ConsumeEffect::ClearAllEffects]); + assert_eq!((drink.ticks(), drink.animation), (32, UseAnimation::Drink)); + assert_eq!(drink.sound, "minecraft:entity.generic.drink"); + assert!(!drink.particles); + assert_eq!(milk.use_remainder.as_deref(), Some("minecraft:bucket")); + let honey = items.get("minecraft:honey_bottle").expect("honey bottle"); + let sip = honey.consumable.as_ref().unwrap(); + assert_eq!(sip.ticks(), 40); + assert_eq!(sip.sound, "minecraft:item.honey_bottle.drink"); + assert_eq!( + sip.effects, + [ConsumeEffect::RemoveEffects(vec![ + "minecraft:poison".into() + ])] + ); + assert_eq!( + honey.use_remainder.as_deref(), + Some("minecraft:glass_bottle") + ); + let kelp = items.get("minecraft:dried_kelp").unwrap(); + let bite = kelp.consumable.as_ref().unwrap(); + assert_eq!((bite.ticks(), bite.animation), (16, UseAnimation::Eat)); + assert_eq!(bite.sound, "minecraft:entity.generic.eat"); + assert!(bite.particles && kelp.use_remainder.is_none()); + let chorus = items.get("minecraft:chorus_fruit").unwrap(); + assert_eq!( + chorus.consumable.as_ref().unwrap().effects, + [ConsumeEffect::TeleportRandomly( + horizon_world::teleport_consume::TeleportConsume { + diameter: 16.0, + directional_particles: true, + } + )] + ); + let chicken = items.get("minecraft:chicken").unwrap(); + assert!(matches!( + chicken.consumable.as_ref().unwrap().effects[..], + [ConsumeEffect::ApplyEffects { probability, .. }] if probability == 0.3 + )); + } +} diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs index aa470a552..a8ffe735b 100644 --- a/crates/horizon-client/src/banner.rs +++ b/crates/horizon-client/src/banner.rs @@ -3,24 +3,10 @@ //! banners, and the loom rules of `LoomMenu` (selectable patterns, the //! six-layer limit and the result stack). use crate::{block_entity_render::DYES, items::ItemStack, items::Items}; -use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::HashMap, fs, path::Path, sync::Arc}; -/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct BannerLayer { - pub pattern: Arc, - pub color: Arc, -} -impl BannerLayer { - pub fn new(pattern: &str, color: &str) -> Self { - Self { - pattern: Arc::from(pattern), - color: Arc::from(color), - } - } -} +pub use horizon_items::banner_layer::{BannerLayer, layers_from_nbt, layers_to_nbt}; /// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`). pub const MAX_LAYERS: usize = 6; @@ -224,44 +210,6 @@ pub fn has_max_layers(banner: &ItemStack) -> bool { layers(banner).len() >= MAX_LAYERS } -/// The `banner_patterns` NBT list of layers. -pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { - Tag::List( - layers - .iter() - .map(|l| { - Tag::compound([ - ("pattern", Tag::String((&*l.pattern).into())), - ("color", Tag::String((&*l.color).into())), - ]) - }) - .collect(), - ) -} -pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { - let Some(Tag::List(list)) = tag else { - return Vec::new(); - }; - list.iter() - .filter_map(|e| { - let text = |k: &str| match e.get(k) { - Some(Tag::String(s)) => Some(s.to_string_lossy()), - _ => None, - }; - let pattern = text("pattern")?; - let color = text("color")?; - Some(BannerLayer::new( - &if pattern.contains(':') { - pattern - } else { - format!("minecraft:{pattern}") - }, - &color, - )) - }) - .collect() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 00576ea02..4fb579925 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -13,7 +13,6 @@ use crate::{ doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text, uuid_from_tag, }, - text::Text, }; use horizon_core::geometry::Vec3; use horizon_world::nbt::{Compound, Tag}; @@ -600,14 +599,7 @@ fn custom_name(tag: &Tag) -> Option { _ => None, } } -/// `CustomName` as text: a string keeps its legacy formatting codes, anything -/// else is a component (`ComponentSerialization`). -pub fn name_text(tag: &Tag) -> Text { - match tag { - Tag::String(s) => Text::legacy(&s.to_string_lossy()), - t => crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t)), - } -} +pub use horizon_client_core::component::name_text; pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) -> Option { let kind = types.get(&self::kind(tag)?)?.clone(); let position = position(tag)?; diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 0735ce2ba..816c1c0fd 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -426,18 +426,7 @@ impl UseResult { matches!(self, Self::Success { swing: true }) && before == after } } -pub fn consumable_animation(v: &serde_json::Value) -> horizon_world::consumable::UseAnimation { - use horizon_world::consumable::UseAnimation; - match v - .get("animation") - .and_then(serde_json::Value::as_str) - .unwrap_or("eat") - { - "eat" => UseAnimation::Eat, - "drink" => UseAnimation::Drink, - _ => UseAnimation::None, - } -} +pub use horizon_items::use_animation::consumable_animation; /// What the click handling reads and does in the world. pub trait HandWorld { fn hit(&mut self) -> Hit; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 232904b7a..d99066d1e 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -21,12 +21,10 @@ pub mod block_entity_anim; pub mod block_entity_item; pub mod block_entity_render; pub mod block_transform; -pub mod blocks; pub mod border_render; pub mod boss_overlay; pub mod breaking; pub mod brewing; -pub mod bundle; pub mod camera; pub mod cauldron; pub mod chat; @@ -42,7 +40,6 @@ pub mod confirm_screen; pub mod container_screen; pub mod containers; pub mod control; -pub mod cooldowns; pub mod crafting; pub mod crash; pub mod creative; @@ -56,7 +53,6 @@ pub mod dialog_screen; pub mod discord_presence; pub mod dynamic_light; pub mod effects; -pub mod enchant; pub mod end_crystal; pub mod entities; pub mod entity_culling; @@ -91,11 +87,9 @@ pub mod input; pub mod interaction_input; pub mod inv_sort; pub mod inventory_effects; -pub mod item_data; pub mod item_render; pub mod item_sync; pub mod item_tooltip; -pub mod items; pub mod java_text; pub mod key_names; pub mod keybinds; @@ -145,7 +139,6 @@ pub mod pose; pub mod pregen; pub mod projectiles; pub mod raid; -pub mod random_sequences; pub mod random_tick_sections; pub mod recipe_book; pub mod recipe_book_screen; @@ -206,3 +199,10 @@ pub use horizon_client_core::scoreboard; pub use horizon_client_core::snbt; pub use horizon_client_core::text; pub use horizon_command as command; +pub use horizon_items::blocks; +pub use horizon_items::bundle; +pub use horizon_items::cooldowns; +pub use horizon_items::enchant; +pub use horizon_items::item_data; +pub use horizon_items::items; +pub use horizon_items::random_sequences; diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index cb96fea06..2d8d2de3b 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -673,37 +673,14 @@ const NBT_TABLES: [&str; 6] = [ "worldgen/blocks/cached-support.nbt", "worldgen/blocks/cached-collision.nbt", ]; -/// In a root built here: the namespaces the content mods own (their ids and -/// listed namespaces), which loaders read besides `minecraft`. -const MARKER: &str = "horizon-mod-content.json"; +use horizon_items::content_namespaces::MARKER; +pub use horizon_items::content_namespaces::{namespaces, tag_namespaces}; /// Block states a world can hold. Chunk sections widen their global palette /// past vanilla's 16 bits to fit the registry (crate::chunk::set_block_states); /// this caps it at 20 bits, about 29 times vanilla's 35,723 states. Mods past /// it are refused, not wrapped onto other blocks. pub const MAX_STATES: u32 = 1 << 20; -/// The content mods' namespaces in a root built by [`build`]; none in any -/// other root, so vanilla's loaders read exactly what they did. -pub fn namespaces(root: &Path) -> Vec { - fs::read(root.join(MARKER)) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) - .unwrap_or_default() -} - -/// The namespaces whose tags loaders read in `root`: `minecraft`, and in a -/// root built by [`build`] the convention tags (`c`, shared between mods as -/// on NeoForge and Fabric) and the content mods' own. -pub fn tag_namespaces(root: &Path) -> Vec { - let mods = namespaces(root); - let mut out = vec!["minecraft".to_owned()]; - if !mods.is_empty() { - out.push("c".to_owned()); - out.extend(mods); - } - out -} - /// Bundles of block tag files (tag id → the tag file's text). const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; /// The worldgen loader's bundle of biome tags. diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 17064c163..701422b02 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -24,6 +24,7 @@ use std::{ }; pub use horizon_client_core::particle_type::ParticleType; +pub use horizon_items::firework::{DYE_FIREWORK_COLORS, FireworkExplosion, FireworkShape}; /// `ParticleOptions` with the parameters of the option classes used here. #[derive(Clone, Debug)] @@ -3756,6 +3757,38 @@ fn lifetime_alpha(a: [f32; 4], age: i32, lifetime: i32, partial: f32) -> f32 { a[0] + (a[1] - a[0]) * t.clamp(0.0, 1.0) } +struct Starter { + at: [f64; 3], + v: [f64; 3], + explosions: Vec, + life: i32, + lifetime: i32, + twinkle_delay: bool, + far: bool, +} +const STAR: [[f64; 2]; 6] = [ + [0.0, 1.0], + [0.3455, 0.309], + [0.9511, 0.309], + [0.379_591_836_734_693_9, -0.126_530_612_244_897_95], + [0.612_244_897_959_183_7, -0.804_081_632_653_061_2], + [0.0, -0.359_183_673_469_387_73], +]; +const CREEPER: [[f64; 2]; 12] = [ + [0.0, 0.2], + [0.2, 0.2], + [0.2, 0.6], + [0.6, 0.6], + [0.6, 0.2], + [0.2, 0.2], + [0.2, 0.0], + [0.4, 0.0], + [0.4, -0.6], + [0.2, -0.6], + [0.2, -0.4], + [0.0, -0.4], +]; + #[cfg(test)] mod tests { use super::*; @@ -3942,92 +3975,3 @@ mod tests { assert!((lifetime_alpha(a, 40, 40, 0.0) - 0.6).abs() < 1e-6); } } -/// FireworkExplosion.Shape. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] -pub enum FireworkShape { - #[default] - SmallBall, - LargeBall, - Star, - Creeper, - Burst, -} -impl FireworkShape { - pub fn from_name(name: &str) -> Self { - match name { - "large_ball" => Self::LargeBall, - "star" => Self::Star, - "creeper" => Self::Creeper, - "burst" => Self::Burst, - _ => Self::SmallBall, - } - } - pub fn name(self) -> &'static str { - match self { - Self::SmallBall => "small_ball", - Self::LargeBall => "large_ball", - Self::Star => "star", - Self::Creeper => "creeper", - Self::Burst => "burst", - } - } -} -/// `DyeColor` names and `getFireworkColor`, by dye id (white to black). -pub const DYE_FIREWORK_COLORS: [(&str, u32); 16] = [ - ("white", 0xF0F0F0), - ("orange", 0xEB8844), - ("magenta", 0xC354CD), - ("light_blue", 0x6689D3), - ("yellow", 0xDECF2A), - ("lime", 0x41CD34), - ("pink", 0xD88198), - ("gray", 0x434343), - ("light_gray", 0xABABAB), - ("cyan", 0x287697), - ("purple", 0x7B2FBE), - ("blue", 0x253192), - ("brown", 0x51301A), - ("green", 0x3B511A), - ("red", 0xB3312C), - ("black", 0x1E1B1B), -]; -/// The `firework_explosion` component. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct FireworkExplosion { - pub shape: FireworkShape, - pub colors: Vec, - pub fade: Vec, - pub trail: bool, - pub twinkle: bool, -} -struct Starter { - at: [f64; 3], - v: [f64; 3], - explosions: Vec, - life: i32, - lifetime: i32, - twinkle_delay: bool, - far: bool, -} -const STAR: [[f64; 2]; 6] = [ - [0.0, 1.0], - [0.3455, 0.309], - [0.9511, 0.309], - [0.379_591_836_734_693_9, -0.126_530_612_244_897_95], - [0.612_244_897_959_183_7, -0.804_081_632_653_061_2], - [0.0, -0.359_183_673_469_387_73], -]; -const CREEPER: [[f64; 2]; 12] = [ - [0.0, 0.2], - [0.2, 0.2], - [0.2, 0.6], - [0.6, 0.6], - [0.6, 0.2], - [0.2, 0.2], - [0.2, 0.0], - [0.4, 0.0], - [0.4, -0.6], - [0.2, -0.6], - [0.2, -0.4], - [0.0, -0.4], -]; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 6f4082ec3..3f45caddf 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -104,27 +104,8 @@ pub fn chunks_with_block_entities<'a>( .collect() } -fn string(s: &str) -> Tag { - Tag::String(s.into()) -} -pub fn text(tag: Option<&Tag>) -> Option { - match tag { - Some(Tag::String(s)) => Some(s.to_string_lossy()), - _ => None, - } -} -/// Any numeric tag as i64 (vanilla's `getIntOr` etc. accept every number type). -pub fn number(tag: Option<&Tag>) -> Option { - Some(match tag? { - Tag::Byte(v) => i64::from(*v), - Tag::Short(v) => i64::from(*v), - Tag::Int(v) => i64::from(*v), - Tag::Long(v) => *v, - Tag::Float(b) => f32::from_bits(*b) as i64, - Tag::Double(b) => f64::from_bits(*b) as i64, - _ => return None, - }) -} +use horizon_client_core::nbt_value::string; +pub use horizon_client_core::nbt_value::{number, text}; pub(crate) fn float(tag: Option<&Tag>) -> Option { Some(match tag? { Tag::Float(b) => f64::from(f32::from_bits(*b)), @@ -391,62 +372,9 @@ fn fluid_id(name: &str) -> Option { } as u32) } -fn encode_item(stack: &crate::items::ItemStack) -> Vec<(&'static str, Tag)> { - let mut entries = vec![ - ("id", string(&stack.item)), - ("count", Tag::Int(stack.count as i32)), - ]; - if let Some(components) = crate::item_data::encode_components(stack) { - entries.push(("components", components)); - } - entries -} -/// ItemStack.CODEC (id, count, components). -pub fn item_to_nbt(stack: &crate::items::ItemStack) -> Tag { - Tag::compound(encode_item(stack)) -} -pub fn item_from_nbt(tag: &Tag) -> Option { - let id = text(tag.get("id"))?; - if id == "minecraft:air" { - return None; - } - let count = number(tag.get("count")) - .or_else(|| number(tag.get("Count"))) - .unwrap_or(1) - .max(1) as u32; - let (damage, extra) = crate::item_data::decode_components(tag.get("components")); - Some(crate::items::ItemStack { - item: Arc::from(id.as_str()), - count, - damage, - extra, - }) -} -pub fn encode_items(slots: &[Option]) -> Tag { - Tag::List( - slots - .iter() - .enumerate() - .filter_map(|(i, s)| { - let mut entries = vec![("Slot", Tag::Byte(i as i8))]; - entries.extend(encode_item(s.as_ref()?)); - Some(Tag::compound(entries)) - }) - .collect(), - ) -} -pub fn decode_items(tag: Option<&Tag>, size: usize) -> Vec> { - let mut slots = vec![None; size]; - if let Some(Tag::List(items)) = tag { - for it in items { - let slot = number(it.get("Slot")).unwrap_or(0) as u8 as usize; - if let Some(cell) = slots.get_mut(slot) { - *cell = item_from_nbt(it); - } - } - } - slots -} +pub use horizon_items::item_nbt::{ + decode_items, encode_item, encode_items, item_from_nbt, item_to_nbt, +}; /// The block entity type ID for the block it sits in (a chest-like container /// is a chest, trapped chest or barrel). fn block_entity_id(e: &crate::containers::BlockEntity, block: &str) -> String { diff --git a/crates/horizon-items/Cargo.toml b/crates/horizon-items/Cargo.toml new file mode 100644 index 000000000..0662999bf --- /dev/null +++ b/crates/horizon-items/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "horizon-items" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "Blocks and items as the client knows them: block facts, item stacks and their data components, enchantments, cooldowns, bundles, and items in NBT" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +horizon-core = { path = "../horizon-core" } +horizon-world = { path = "../horizon-world" } +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1.0.151", features = ["raw_value"] } + +[features] +# Test helpers (`Items::for_tests`, `enchant::tests`) for horizon-client's unit tests. +test-support = [] + +[lints] +workspace = true diff --git a/crates/horizon-items/src/banner_layer.rs b/crates/horizon-items/src/banner_layer.rs new file mode 100644 index 000000000..5f76ad575 --- /dev/null +++ b/crates/horizon-items/src/banner_layer.rs @@ -0,0 +1,56 @@ +//! Banner pattern layers (`BannerPatternLayers`) and their NBT form. +use horizon_world::nbt::Tag; +use std::sync::Arc; + +/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BannerLayer { + pub pattern: Arc, + pub color: Arc, +} +impl BannerLayer { + pub fn new(pattern: &str, color: &str) -> Self { + Self { + pattern: Arc::from(pattern), + color: Arc::from(color), + } + } +} + +/// The `banner_patterns` NBT list of layers. +pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { + Tag::List( + layers + .iter() + .map(|l| { + Tag::compound([ + ("pattern", Tag::String((&*l.pattern).into())), + ("color", Tag::String((&*l.color).into())), + ]) + }) + .collect(), + ) +} +pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + list.iter() + .filter_map(|e| { + let text = |k: &str| match e.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let pattern = text("pattern")?; + let color = text("color")?; + Some(BannerLayer::new( + &if pattern.contains(':') { + pattern + } else { + format!("minecraft:{pattern}") + }, + &color, + )) + }) + .collect() +} diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-items/src/blocks.rs similarity index 100% rename from crates/horizon-client/src/blocks.rs rename to crates/horizon-items/src/blocks.rs diff --git a/crates/horizon-client/src/blocks/decode.rs b/crates/horizon-items/src/blocks/decode.rs similarity index 100% rename from crates/horizon-client/src/blocks/decode.rs rename to crates/horizon-items/src/blocks/decode.rs diff --git a/crates/horizon-client/src/blocks/decode_tests.rs b/crates/horizon-items/src/blocks/decode_tests.rs similarity index 100% rename from crates/horizon-client/src/blocks/decode_tests.rs rename to crates/horizon-items/src/blocks/decode_tests.rs diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-items/src/bundle.rs similarity index 100% rename from crates/horizon-client/src/bundle.rs rename to crates/horizon-items/src/bundle.rs diff --git a/crates/horizon-items/src/content_namespaces.rs b/crates/horizon-items/src/content_namespaces.rs new file mode 100644 index 000000000..07d4c5685 --- /dev/null +++ b/crates/horizon-items/src/content_namespaces.rs @@ -0,0 +1,29 @@ +//! The namespaces content mods add to a resource root, which loaders read +//! besides `minecraft`. +use std::{fs, path::Path}; + +/// In a root built here: the namespaces the content mods own (their ids and +/// listed namespaces), which loaders read besides `minecraft`. +pub const MARKER: &str = "horizon-mod-content.json"; + +/// The content mods' namespaces in a root built by `mod_content::build`; none in any +/// other root, so vanilla's loaders read exactly what they did. +pub fn namespaces(root: &Path) -> Vec { + fs::read(root.join(MARKER)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + +/// The namespaces whose tags loaders read in `root`: `minecraft`, and in a +/// root built by `mod_content::build` the convention tags (`c`, shared between mods as +/// on NeoForge and Fabric) and the content mods' own. +pub fn tag_namespaces(root: &Path) -> Vec { + let mods = namespaces(root); + let mut out = vec!["minecraft".to_owned()]; + if !mods.is_empty() { + out.push("c".to_owned()); + out.extend(mods); + } + out +} diff --git a/crates/horizon-client/src/cooldowns.rs b/crates/horizon-items/src/cooldowns.rs similarity index 100% rename from crates/horizon-client/src/cooldowns.rs rename to crates/horizon-items/src/cooldowns.rs diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-items/src/enchant.rs similarity index 99% rename from crates/horizon-client/src/enchant.rs rename to crates/horizon-items/src/enchant.rs index 2f418ae82..60b5dbfbc 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-items/src/enchant.rs @@ -334,14 +334,14 @@ impl Enchantments { } /// `Enchantment.getFullname` as plain text and whether it is a curse (red). pub fn full_name(&self, id: &str, level: u32) -> (String, bool) { - let language = crate::lang::current(); + let language = horizon_client_core::lang::current(); self.full_name_in(language.as_deref(), id, level) } /// `full_name` against `language`; `None` (no language loaded: a /// dedicated server, the probes) keeps the English names loaded above. pub fn full_name_in( &self, - language: Option<&crate::lang::Language>, + language: Option<&horizon_client_core::lang::Language>, id: &str, level: u32, ) -> (String, bool) { @@ -776,8 +776,8 @@ pub fn apply_value_effect( } } -#[cfg(test)] -pub(crate) mod tests { +#[cfg(any(test, feature = "test-support"))] +pub mod tests { use super::*; use serde_json::json; @@ -1110,7 +1110,7 @@ pub(crate) mod tests { #[test] fn names_follow_the_language() { struct Mem(HashMap>); - impl crate::lang::ResourceSource for Mem { + impl horizon_client_core::lang::ResourceSource for Mem { fn read(&self, path: &str) -> Option> { self.0.get(path).cloned() } @@ -1121,7 +1121,7 @@ pub(crate) mod tests { .as_bytes() .to_vec(), )])); - let ru = crate::lang::Language::load(&[&ru], "ru_ru"); + let ru = horizon_client_core::lang::Language::load(&[&ru], "ru_ru"); let e = sample(); assert_eq!( e.full_name_in(Some(&ru), "minecraft:sharpness", 5).0, diff --git a/crates/horizon-items/src/firework.rs b/crates/horizon-items/src/firework.rs new file mode 100644 index 000000000..9e6668e5d --- /dev/null +++ b/crates/horizon-items/src/firework.rs @@ -0,0 +1,61 @@ +//! Firework explosions (the `firework_explosion` component and its shapes) and +//! the dye colours fireworks use. + +/// FireworkExplosion.Shape. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] +pub enum FireworkShape { + #[default] + SmallBall, + LargeBall, + Star, + Creeper, + Burst, +} +impl FireworkShape { + pub fn from_name(name: &str) -> Self { + match name { + "large_ball" => Self::LargeBall, + "star" => Self::Star, + "creeper" => Self::Creeper, + "burst" => Self::Burst, + _ => Self::SmallBall, + } + } + pub fn name(self) -> &'static str { + match self { + Self::SmallBall => "small_ball", + Self::LargeBall => "large_ball", + Self::Star => "star", + Self::Creeper => "creeper", + Self::Burst => "burst", + } + } +} +/// `DyeColor` names and `getFireworkColor`, by dye id (white to black). +pub const DYE_FIREWORK_COLORS: [(&str, u32); 16] = [ + ("white", 0xF0F0F0), + ("orange", 0xEB8844), + ("magenta", 0xC354CD), + ("light_blue", 0x6689D3), + ("yellow", 0xDECF2A), + ("lime", 0x41CD34), + ("pink", 0xD88198), + ("gray", 0x434343), + ("light_gray", 0xABABAB), + ("cyan", 0x287697), + ("purple", 0x7B2FBE), + ("blue", 0x253192), + ("brown", 0x51301A), + ("green", 0x3B511A), + ("red", 0xB3312C), + ("black", 0x1E1B1B), +]; +/// The `firework_explosion` component. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct FireworkExplosion { + pub shape: FireworkShape, + pub colors: Vec, + pub fade: Vec, + pub trail: bool, + pub twinkle: bool, +} diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-items/src/item_data.rs similarity index 96% rename from crates/horizon-client/src/item_data.rs rename to crates/horizon-items/src/item_data.rs index c07e2f352..0267e63f0 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-items/src/item_data.rs @@ -28,7 +28,7 @@ pub struct StackData { pub charged: Vec, /// `minecraft:fireworks`: flight duration and explosions (None: the /// item's default). - pub fireworks: Option<(u8, Vec)>, + pub fireworks: Option<(u8, Vec)>, /// `minecraft:map_id` (filled maps). pub map_id: Option, /// `minecraft:writable_book_content` pages. @@ -36,7 +36,7 @@ pub struct StackData { /// `minecraft:written_book_content`. pub written: Option, /// `minecraft:banner_patterns` (banners and shields). - pub banner_patterns: Vec, + pub banner_patterns: Vec, /// `minecraft:base_color` (a shield's dye). pub base_color: Option>, /// The raid captain's banner: `minecraft:banner_patterns` with the @@ -47,7 +47,7 @@ pub struct StackData { /// `minecraft:dyed_color` (leather armour, wolf armour, ... as RGB). pub dyed_color: Option, /// `minecraft:firework_explosion` (a firework star). - pub firework_explosion: Option, + pub firework_explosion: Option, /// `minecraft:pot_decorations`: back, left, right, front sherds. pub pot_decorations: Option; 4]>>, /// `minecraft:bundle_contents`. @@ -297,13 +297,13 @@ fn read_text(t: &Tag) -> Option { // A component's root `text` may be empty with the visible words in // `extra` (every legacy display name ViaVersion produces looks like // this), so flatten the whole component instead of reading one key. - Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()), + Tag::Compound(_) => Some(horizon_client_core::component::name_text(t).plain()), _ => None, } } /// A `FireworkExplosion` as vanilla's codec writes it (defaults omitted). -fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag { +fn explosion_tag(e: &crate::firework::FireworkExplosion) -> Tag { let colors = |c: &[u32]| Tag::List(c.iter().map(|c| Tag::Int(*c as i32)).collect()); let mut fields = vec![("shape", Tag::String(e.shape.name().into()))]; if !e.colors.is_empty() { @@ -320,14 +320,14 @@ fn explosion_tag(e: &crate::particles::FireworkExplosion) -> Tag { } Tag::compound(fields) } -fn explosion_from(e: &Tag) -> crate::particles::FireworkExplosion { +fn explosion_from(e: &Tag) -> crate::firework::FireworkExplosion { let ints = |t: Option<&Tag>| match t { Some(Tag::IntArray(v)) => v.iter().map(|c| *c as u32).collect(), Some(Tag::List(v)) => v.iter().filter_map(int).map(|c| c as u32).collect(), _ => Vec::new(), }; - crate::particles::FireworkExplosion { - shape: crate::particles::FireworkShape::from_name( + crate::firework::FireworkExplosion { + shape: crate::firework::FireworkShape::from_name( e.get("shape") .and_then(string) .as_deref() @@ -436,7 +436,7 @@ pub fn canon_tag(tag: &Tag) -> String { pub fn canon_stack(stack: Option<&ItemStack>) -> String { stack.map_or_else( || "-".to_owned(), - |s| canon_tag(&crate::save::item_to_nbt(s)), + |s| canon_tag(&crate::item_nbt::item_to_nbt(s)), ) } /// The stack of an SNBT `ItemStack.CODEC` compound; None for "-". @@ -445,7 +445,7 @@ pub fn parse_stack(snbt: &str) -> Result, String> { return Ok(None); } let (tag, _) = horizon_world::nbt::parse_snbt(snbt)?; - Ok(crate::save::item_from_nbt(&tag)) + Ok(crate::item_nbt::item_from_nbt(&tag)) } /// The `components` compound for a stack, or None when every component is default. pub fn encode_components(stack: &ItemStack) -> Option { @@ -494,7 +494,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { if !d.banner_patterns.is_empty() { entries.push(( "minecraft:banner_patterns", - crate::banner::layers_to_nbt(&d.banner_patterns), + crate::banner_layer::layers_to_nbt(&d.banner_patterns), )); } if let Some(color) = &d.base_color { @@ -594,7 +594,7 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { if !d.charged.is_empty() { entries.push(( "minecraft:charged_projectiles", - Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()), + Tag::List(d.charged.iter().map(crate::item_nbt::item_to_nbt).collect()), )); } if d.ominous_banner { @@ -677,7 +677,7 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option) -> (u32, Option None, }, charged: match c.get("minecraft:charged_projectiles") { - Some(Tag::List(list)) => list.iter().filter_map(crate::save::item_from_nbt).collect(), + Some(Tag::List(list)) => list + .iter() + .filter_map(crate::item_nbt::item_from_nbt) + .collect(), _ => Vec::new(), }, container: match c.get("minecraft:container") { @@ -896,8 +899,8 @@ mod tests { let mut stack = ItemStack::new("minecraft:shield", 1); stack.data_mut().base_color = Some(Arc::from("red")); stack.data_mut().banner_patterns = vec![ - crate::banner::BannerLayer::new("minecraft:flower", "black"), - crate::banner::BannerLayer::new("minecraft:border", "white"), + crate::banner_layer::BannerLayer::new("minecraft:flower", "black"), + crate::banner_layer::BannerLayer::new("minecraft:border", "white"), ]; let tag = encode_components(&stack).expect("components"); let (_, extra) = decode_components(Some(&tag)); @@ -968,7 +971,7 @@ mod tests { assert_eq!(flight, 2); assert_eq!( explosions[0].shape, - crate::particles::FireworkShape::LargeBall + crate::firework::FireworkShape::LargeBall ); assert_eq!(explosions[0].colors, vec![0xFF0000]); assert!(explosions[0].twinkle && !explosions[0].trail); diff --git a/crates/horizon-items/src/item_nbt.rs b/crates/horizon-items/src/item_nbt.rs new file mode 100644 index 000000000..e0101228b --- /dev/null +++ b/crates/horizon-items/src/item_nbt.rs @@ -0,0 +1,62 @@ +//! Item stacks in NBT (`ItemStack.CODEC`): id, count and components, alone or in +//! slot lists. +use horizon_client_core::nbt_value::{number, string, text}; +use horizon_world::nbt::Tag; +use std::sync::Arc; + +pub fn encode_item(stack: &crate::items::ItemStack) -> Vec<(&'static str, Tag)> { + let mut entries = vec![ + ("id", string(&stack.item)), + ("count", Tag::Int(stack.count as i32)), + ]; + if let Some(components) = crate::item_data::encode_components(stack) { + entries.push(("components", components)); + } + entries +} +/// ItemStack.CODEC (id, count, components). +pub fn item_to_nbt(stack: &crate::items::ItemStack) -> Tag { + Tag::compound(encode_item(stack)) +} +pub fn item_from_nbt(tag: &Tag) -> Option { + let id = text(tag.get("id"))?; + if id == "minecraft:air" { + return None; + } + let count = number(tag.get("count")) + .or_else(|| number(tag.get("Count"))) + .unwrap_or(1) + .max(1) as u32; + let (damage, extra) = crate::item_data::decode_components(tag.get("components")); + Some(crate::items::ItemStack { + item: Arc::from(id.as_str()), + count, + damage, + extra, + }) +} +pub fn encode_items(slots: &[Option]) -> Tag { + Tag::List( + slots + .iter() + .enumerate() + .filter_map(|(i, s)| { + let mut entries = vec![("Slot", Tag::Byte(i as i8))]; + entries.extend(encode_item(s.as_ref()?)); + Some(Tag::compound(entries)) + }) + .collect(), + ) +} +pub fn decode_items(tag: Option<&Tag>, size: usize) -> Vec> { + let mut slots = vec![None; size]; + if let Some(Tag::List(items)) = tag { + for it in items { + let slot = number(it.get("Slot")).unwrap_or(0) as u8 as usize; + if let Some(cell) = slots.get_mut(slot) { + *cell = item_from_nbt(it); + } + } + } + slots +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-items/src/items.rs similarity index 95% rename from crates/horizon-client/src/items.rs rename to crates/horizon-items/src/items.rs index 8ac450bcb..0efa2ff82 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-items/src/items.rs @@ -297,7 +297,7 @@ fn load_songs(root: &Path) -> HashMap { } songs } -pub(crate) fn load_tags(root: &Path, kind: &str) -> Result>> { +pub fn load_tags(root: &Path, kind: &str) -> Result>> { Ok(load_tag_lists(root, kind)? .into_iter() .map(|(k, v)| (k, v.into_iter().collect())) @@ -337,7 +337,7 @@ pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result:blocks/...`. - for namespace in crate::mod_content::namespaces(root) { + for namespace in crate::content_namespaces::namespaces(root) { let dir = root.join(format!("data/{namespace}/loot_table")); if dir.is_dir() { walk_loot(&dir, &dir, &namespace, &mut loot)?; @@ -720,7 +720,7 @@ impl Items { }) } /// An item table with only tags, for unit tests of item rules. - #[cfg(test)] + #[cfg(any(test, feature = "test-support"))] pub fn for_tests(item_tags: HashMap>) -> Self { Self { items: HashMap::new(), @@ -1657,79 +1657,6 @@ mod tests { assert_eq!(&*drops[0].item, "minecraft:splash_potion"); assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance")); } - - #[test] - fn always_edible_and_consume_effects_loaded() { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../.local/horizon-client/26.3"); - if !root.join("items.json").exists() { - return; - } - let assets = crate::assets::Assets::load(&root).unwrap(); - let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); - let items = Items::load(&root, assets.registry, &facts).unwrap(); - - let apple = items.get("minecraft:golden_apple").expect("golden apple"); - assert!(apple.can_always_eat); - assert!(apple.food.is_some()); - assert!(!apple.consumable.as_ref().unwrap().effects.is_empty()); - - let enchanted = items - .get("minecraft:enchanted_golden_apple") - .expect("enchanted golden apple"); - assert!(enchanted.can_always_eat); - assert!(enchanted.food.is_some()); - assert!(!enchanted.consumable.as_ref().unwrap().effects.is_empty()); - - let beef = items.get("minecraft:cooked_beef").expect("cooked beef"); - assert!(!beef.can_always_eat); - assert!(beef.food.is_some()); - - // Consumables without food, their style and their remainders. - use horizon_world::consumable::UseAnimation; - let milk = items.get("minecraft:milk_bucket").expect("milk bucket"); - let drink = milk.consumable.as_ref().unwrap(); - assert!(milk.food.is_none()); - assert_eq!(drink.effects, [ConsumeEffect::ClearAllEffects]); - assert_eq!((drink.ticks(), drink.animation), (32, UseAnimation::Drink)); - assert_eq!(drink.sound, "minecraft:entity.generic.drink"); - assert!(!drink.particles); - assert_eq!(milk.use_remainder.as_deref(), Some("minecraft:bucket")); - let honey = items.get("minecraft:honey_bottle").expect("honey bottle"); - let sip = honey.consumable.as_ref().unwrap(); - assert_eq!(sip.ticks(), 40); - assert_eq!(sip.sound, "minecraft:item.honey_bottle.drink"); - assert_eq!( - sip.effects, - [ConsumeEffect::RemoveEffects(vec![ - "minecraft:poison".into() - ])] - ); - assert_eq!( - honey.use_remainder.as_deref(), - Some("minecraft:glass_bottle") - ); - let kelp = items.get("minecraft:dried_kelp").unwrap(); - let bite = kelp.consumable.as_ref().unwrap(); - assert_eq!((bite.ticks(), bite.animation), (16, UseAnimation::Eat)); - assert_eq!(bite.sound, "minecraft:entity.generic.eat"); - assert!(bite.particles && kelp.use_remainder.is_none()); - let chorus = items.get("minecraft:chorus_fruit").unwrap(); - assert_eq!( - chorus.consumable.as_ref().unwrap().effects, - [ConsumeEffect::TeleportRandomly( - horizon_world::teleport_consume::TeleportConsume { - diameter: 16.0, - directional_particles: true, - } - )] - ); - let chicken = items.get("minecraft:chicken").unwrap(); - assert!(matches!( - chicken.consumable.as_ref().unwrap().effects[..], - [ConsumeEffect::ApplyEffects { probability, .. }] if probability == 0.3 - )); - } } /// Minecraft.handleKeybinds: spectators cannot drop from the selected slot. diff --git a/crates/horizon-items/src/lib.rs b/crates/horizon-items/src/lib.rs new file mode 100644 index 000000000..6e05a7072 --- /dev/null +++ b/crates/horizon-items/src/lib.rs @@ -0,0 +1,19 @@ +//! Blocks and items as the client knows them, below gameplay: block facts +//! (`blocks`), item stacks and definitions (`items`), their data components +//! (`item_data`), enchantments, cooldowns, bundles and item stacks in NBT. +//! horizon-client re-exports each module under its old path +//! (`horizon_client::items`, ...). +#![forbid(unsafe_code)] +pub mod banner_layer; +pub mod blocks; +pub mod bundle; +pub mod content_namespaces; +pub mod cooldowns; +pub mod enchant; +pub mod firework; +pub mod item_data; +pub mod item_nbt; +pub mod items; +pub mod random_sequences; +pub mod use_animation; +pub use horizon_client_core::Result; diff --git a/crates/horizon-client/src/random_sequences.rs b/crates/horizon-items/src/random_sequences.rs similarity index 100% rename from crates/horizon-client/src/random_sequences.rs rename to crates/horizon-items/src/random_sequences.rs diff --git a/crates/horizon-items/src/use_animation.rs b/crates/horizon-items/src/use_animation.rs new file mode 100644 index 000000000..af7f66817 --- /dev/null +++ b/crates/horizon-items/src/use_animation.rs @@ -0,0 +1,14 @@ +//! The use animation a `consumable` component names. + +pub fn consumable_animation(v: &serde_json::Value) -> horizon_world::consumable::UseAnimation { + use horizon_world::consumable::UseAnimation; + match v + .get("animation") + .and_then(serde_json::Value::as_str) + .unwrap_or("eat") + { + "eat" => UseAnimation::Eat, + "drink" => UseAnimation::Drink, + _ => UseAnimation::None, + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 7646ccc17..f48856b22 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -5,7 +5,8 @@ counted only for the game loop because nearly every gameplay change touches it). organised and how to build and test are in [AGENTS.md](../AGENTS.md). Paths: `L/` = `crates/horizon-client/src/`, `G/` = `crates/horizon-client/src/game/`, `W/` = -`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`. +`crates/horizon-world/src/`, `K/` = `crates/horizon-client-core/src/`, `C/` = `crates/horizon-command/src/`, +`I/` = `crates/horizon-items/src/`. Checks: a bare name is a harness (`python3 tools/parity.py `, script `tools/test__parity.py`); `lan_e2e ` is `python3 tools/lan_e2e.py --check `. @@ -30,7 +31,7 @@ file selects ~103. | 12 | Guests' actions on a server (98) | `G/lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `G/lan_{attributes,pvp,chat,crafting,stations,trading,mount_menu,waypoints}.rs` | server_player_combat, server_player_damage, server_player_targets, lan_e2e (all) | | 13 | Modpack porting, mod content (97) | `crates/horizon-port-pack/`, `L/mod_content.rs`, `tools/port_*.py` | `cargo test -p horizon-port-pack`; `python3 tools/mod_port_harness.py` | | 14 | Mob AI (96) | `L/mobs/ai.rs`, `goals.rs`, `brain.rs`, `*_brain.rs`, `nav.rs`, `path.rs`, `control.rs` | mob_ai (probe `examples/mob_ai_probe.rs`; known failure on main: drowned_*, #290) | -| 15 | Items and item use (96) | `L/items.rs`, `L/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | +| 15 | Items and item use (96) | `I/items.rs`, `I/item_data.rs`, `G/hand.rs`, `G/consume.rs`, `G/potions.rs`, `L/effects.rs`; game.rs `fn use_hand`, `fn use_item` | use_item_on, item_use, item_use_lifecycle, consumable, consume_effect, status_effect | | 16 | Options and settings screens (93) | `L/options_ui.rs`, `G/options.rs`, `L/settings.rs`, `L/options_file.rs`, `L/graphics_ui.rs`, `L/graphics.rs` | options, toggle_keys | | 17 | HUD, chat, tab list (93) | `L/hud.rs`, `L/hud_layout.rs`, `L/hud_overlays.rs`, `L/chat.rs`, `G/chat.rs`, `L/tab_list.rs`, `L/locator_bar.rs`, `G/locator_bar.rs` | hud, tab_list, locator_bar, chat_screen, secure_chat | | 18 | Command execution (88) | `G/commands.rs`, `G/commands/*.rs`, `L/scoreboard_cmd.rs`, `L/data_cmd.rs`, `K/scoreboard.rs`, `G/functions.rs` | command_exec (corpus `tools/command_exec_corpus.py`), scoreboard, server_ops_feedback, lan_e2e commands | @@ -40,7 +41,7 @@ file selects ~103. | 22 | Player movement and collision (75) | `L/motion.rs` + `L/motion/`, `L/collisions.rs`, `W/entity_move.rs`, `W/player_travel.rs`, `W/collision.rs` | collision, entity_move, player_travel, living_motion, climbing, swimming; `python3 tools/test_native_scene_motion.py` | | 23 | Resource packs and models (65) | `L/packs.rs` + `L/packs/`, `L/pack_screen.rs`, `L/atlas_sources.rs`, `L/sprites.rs`, `L/model_library.rs`, `G/packs.rs`, `crates/horizon-assets/` | resource_pack, pack_selection, pack_screen, model_resolution, item_model, mipmap | | 24 | Container menus and inventory (61) | `L/menu.rs`, `L/container_screen.rs`, `L/containers.rs`, `L/creative.rs`; game.rs `fn menu_ops`, `fn click_inventory` | menu_click, container_screen, creative, lan_e2e containers clicks | -| 25 | Workstations (60) | `L/stations.rs`, `G/stations.rs`, `L/enchant.rs`, `L/brewing.rs` | enchanting, screen_layout, lan_e2e brewing loom stonecutter grindstone anvil smithing | +| 25 | Workstations (60) | `L/stations.rs`, `G/stations.rs`, `I/enchant.rs`, `L/brewing.rs` | enchanting, screen_layout, lan_e2e brewing loom stonecutter grindstone anvil smithing | | 26 | Crafting and the recipe book (59) | `L/crafting.rs`, `L/recipe_book.rs`, `L/recipe_book_screen.rs`, `G/recipe_book.rs`, `G/machines.rs`, `G/machines/crafter.rs` | recipe, recipe_book, recipe_book_view, place_recipe, ghost_recipe, crafter | | 27 | Vehicles and mounts (54) | `G/boats.rs`, `G/boat_passengers.rs`, `G/minecarts.rs`, `G/mounts.rs`, `G/mount_menu.rs`, `G/llamas.rs`, `G/passengers.rs` | server_entities, lan_e2e boats minecarts riding mounts | | 28 | Villagers, trading, raids (50) | `L/mobs/villager*.rs`, `L/merchant.rs`, `G/trading.rs`, `G/villagers.rs`, `L/raid.rs`, `G/raids.rs`, `L/gossip.rs` | trading, raid, mob_ai | diff --git a/tools/test_block_particles_parity.py b/tools/test_block_particles_parity.py index 7e08e98f8..ff50bd745 100644 --- a/tools/test_block_particles_parity.py +++ b/tools/test_block_particles_parity.py @@ -13,7 +13,7 @@ def main(): resources = lab.RESOURCES build = lab.LOCAL / "block-particles-parity" build.mkdir(exist_ok=True) - paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/probe/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] + paths = [lab.ROOT / p for p in ["tools/test_block_particles_parity.py", "tools/test_breaking_model_parity.py", "tools/oracle_harness.py", "tools/lab.py", "crates/horizon-client/src/particles.rs", "crates/horizon-client/src/game.rs", "crates/horizon-items/src/blocks.rs", "crates/horizon-client/src/mesher.rs", "crates/horizon-client/examples/probe/block_particles_fixture.rs", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockParticlesOracle.java", "crates/horizon-core/src/random.rs", "Cargo.lock", "mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameplayFactsExporter.java"]] tested = base.source_hashes(paths) rows = [dict(case=i, seed=(-1 if i % 2 else 1) * i * 987654321, **row) for i, row in enumerate(breaking.cases(resources))] rows[0]["seed"] = -(2**63) diff --git a/tools/test_fire_starter_sound_parity.py b/tools/test_fire_starter_sound_parity.py index bac04f4aa..b8b0696c1 100644 --- a/tools/test_fire_starter_sound_parity.py +++ b/tools/test_fire_starter_sound_parity.py @@ -25,7 +25,7 @@ def main(): 'FireChargeItem.useOn\'s choice between lighting and placing fire is not exercised.') harness.differential( 'rust-fire-starter-sound-parity', 'VanillaFireStarterSoundOracle', 'fire_starter_sound_probe', make_cases, - scope, sources=[lab.ROOT / 'crates/horizon-client/src/items.rs']) + scope, sources=[lab.ROOT / 'crates/horizon-items/src/items.rs']) if __name__ == '__main__': diff --git a/tools/test_firework_tooltip_parity.py b/tools/test_firework_tooltip_parity.py index 14a4138b5..5e971d8db 100644 --- a/tools/test_firework_tooltip_parity.py +++ b/tools/test_firework_tooltip_parity.py @@ -67,7 +67,7 @@ if __name__ == '__main__': 'firework-tooltip-parity', 'VanillaFireworkTooltipOracle', 'firework_tooltip_fixture', cases, 'Firework rocket and star tooltip lines: flight duration, explosions (counted runs), colours, fade, trail, ' 'twinkle, defaults and tooltip_display', - sources=[lab.ROOT / 'crates/horizon-client/src/enchant.rs', - lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-client/src/item_data.rs', + sources=[lab.ROOT / 'crates/horizon-items/src/enchant.rs', + lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', lab.ROOT / 'crates/horizon-items/src/item_data.rs', lab.ROOT / 'crates/horizon-client/src/particles.rs'], expected_lines=COUNT) diff --git a/tools/test_lore_tooltip_parity.py b/tools/test_lore_tooltip_parity.py index e6869f7e9..63f746392 100644 --- a/tools/test_lore_tooltip_parity.py +++ b/tools/test_lore_tooltip_parity.py @@ -34,7 +34,7 @@ if __name__ == '__main__': 'Item lore tooltip lines: dark purple italic, child colours, explicit non-italic, and tooltip_display', sources=[ lab.ROOT / 'crates/horizon-client/src/item_tooltip.rs', - lab.ROOT / 'crates/horizon-client/src/item_data.rs', + lab.ROOT / 'crates/horizon-items/src/item_data.rs', lab.ROOT / 'crates/horizon-client-core/src/text.rs', lab.ROOT / 'crates/horizon-client-core/src/component.rs', ], From 66637220efc12e298a565d7d569c689f8442e1d0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:13:58 +0100 Subject: [PATCH 006/221] Play the step sound of the block above the floor for the player Powder snow, lily pads, carpets, snow layers and similar blocks now sound like vanilla when walked on: inside blocks replace the floor's step, combination blocks play their own step with the floor's step muffled. --- .../examples/probe/scene_motion_probe.rs | 2 +- crates/horizon-client/src/game.rs | 6 +-- crates/horizon-client/src/game/remote.rs | 8 +-- crates/horizon-client/src/motion.rs | 51 ++++++++++++++++--- 4 files changed, 52 insertions(+), 15 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..67b2e1560 100644 --- a/crates/horizon-client/examples/probe/scene_motion_probe.rs +++ b/crates/horizon-client/examples/probe/scene_motion_probe.rs @@ -206,7 +206,7 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { )), MotionEvent::Emission { state, - in_water: true, + muffled: true, .. } => Some(format!("muffled-step {}", state.0)), MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!( diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..f2f12d802 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4349,13 +4349,11 @@ impl Game<'_> { for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), - MotionEvent::Emission { - state, in_water, .. - } if !crouching => { + MotionEvent::Emission { state, muffled, .. } if !crouching => { let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, // muffled under the swim sound in water. - let (volume, pitch) = if in_water { + let (volume, pitch) = if muffled { (sounds.volume * 0.05, sounds.pitch * 0.8) } else { (sounds.volume * 0.15, sounds.pitch) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..f5365034a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3233,12 +3233,12 @@ impl Game<'_> { let feet = [player.position.x, player.position.y, player.position.z]; for event in events { match event { - horizon_client::motion::MotionEvent::Emission { - state, in_water, .. - } if !crouching => { + horizon_client::motion::MotionEvent::Emission { state, muffled, .. } + if !crouching => + { let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. - let (volume, pitch) = if in_water { + let (volume, pitch) = if muffled { (sounds.volume * 0.05, sounds.pitch * 0.8) } else { (sounds.volume * 0.15, sounds.pitch) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..1f788fb50 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -51,6 +51,10 @@ pub struct MotionResources { pub blocks: BoundMovementProperties, pub climbable: BTreeSet, pub fall_reset: BTreeSet, + /// `BlockTags.INSIDE_STEP_SOUND_BLOCKS`. + pub inside_step_sound: BTreeSet, + /// `BlockTags.COMBINATION_STEP_SOUND_BLOCKS`. + pub combination_step_sound: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, pub fluids: FluidResources, @@ -109,6 +113,8 @@ impl MotionResources { })?, climbable: tag("minecraft:climbable")?, fall_reset: tag("minecraft:fall_damage_resetting")?, + inside_step_sound: tag("minecraft:inside_step_sound_blocks")?, + combination_step_sound: tag("minecraft:combination_step_sound_blocks")?, }) } } @@ -136,11 +142,12 @@ pub enum MotionEvent { position: BlockPos, }, /// `Entity.walkingStepSound` on this block: `Player.playStepSound` - /// muffles it under a swim sound when `in_water`. + /// mutes it (`playMuffledStepSound`) under a swim sound in water or + /// under a combination block's own step. Emission { position: BlockPos, state: BlockStateId, - in_water: bool, + muffled: bool, }, /// `Entity.waterSwimSound`: `entity.player.swim`. Swim { @@ -1973,16 +1980,48 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { fn in_water(&mut self) -> Result { Ok(self.player.fluids.was_touching_water) } - /// `Player.playStepSound`: in water a swim sound, then the step muffled. + /// `Player.playStepSound`: in water a swim sound, then the step muffled; + /// on land the step of an inside-sound block above the floor, or of a + /// combination block above it with the floor's step muffled. fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> { - let in_water = self.player.fluids.was_touching_water; - if in_water { + let muffled = self.player.fluids.was_touching_water; + if muffled { self.water_swim_sound()?; + } else { + // Entity.getPrimaryStepSoundBlockPos. + let above = BlockPos { + y: position.y + 1, + ..position + }; + let above_state = self.block(above); + let name = &self + .assets + .registry + .state(above_state) + .ok_or("missing scene state")? + .name; + let combination = self.resources.combination_step_sound.contains(name); + if combination || self.resources.inside_step_sound.contains(name) { + self.player.events.push(MotionEvent::Emission { + position: above, + state: above_state, + muffled: false, + }); + if combination { + // Entity.playCombinationStepSounds. + self.player.events.push(MotionEvent::Emission { + position, + state, + muffled: true, + }); + } + return Ok(()); + } } self.player.events.push(MotionEvent::Emission { position, state, - in_water, + muffled, }); Ok(()) } From 20630b1230e5b097631a2275adc5339669e7a7f9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:25 +0100 Subject: [PATCH 007/221] Fire the enchanted_item trigger when an enchanting table enchants --- crates/horizon-client/src/advancements.rs | 2 +- crates/horizon-client/src/game/advancements.rs | 16 ++++++++++++++++ crates/horizon-client/src/game/lan_stations.rs | 2 ++ crates/horizon-client/src/game/stations.rs | 2 ++ 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..e09f97b6d 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -458,7 +458,7 @@ fn range_f(v: &Value, x: f64) -> bool { _ => false, } } -fn range_i(v: &Value, x: i64) -> bool { +pub fn range_i(v: &Value, x: i64) -> bool { range_f(v, x as f64) } /// A registry id, `#tag`, or list matched against one id. diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..4c98275a8 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -708,6 +708,22 @@ impl Game<'_> { let it = item_view(stack); self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); } + /// `EnchantedItemTrigger`: the enchanted item and the levels it cost. + pub(super) fn trigger_enchanted_item(&mut self, stack: &ItemStack, levels: i32) { + let me = self.player_entity(); + let it = item_view(stack); + self.trigger("minecraft:enchanted_item", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::item(&c["item"], &it, w) + && adv::range_i(&c["levels"], i64::from(levels)) + }); + } /// `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_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 418ed9c2a..cfd65403a 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -317,6 +317,8 @@ impl Game<'_> { self.as_guest(host, conn, |game| { game.give_levels(-need); game.stats.custom("enchant_item", 1); + // CriteriaTriggers.ENCHANTED_ITEM, with the levels it cost. + game.trigger_enchanted_item(&enchanted, need); }); host.hub.guests[gi].xp_seed = self.world.random.next_int(); let env = self.menu_env(); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index f7f05e1c4..906c629b5 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -774,6 +774,7 @@ impl Game<'_> { return; }; let pos = s.pos; + let enchanted_item = enchanted.clone(); // Player.onEnchantmentPerformed self.give_levels(-(lapis_needed as i32)); self.level.xp_seed = self.world.random.next_int(); @@ -790,6 +791,7 @@ impl Game<'_> { } let pitch = self.world.random.next_float() * 0.1 + 0.9; self.stats.custom("enchant_item", 1); + self.trigger_enchanted_item(&enchanted_item, lapis_needed as i32); self.play_at("minecraft:block.enchantment_table.use", pos, 1.0, pitch); self.station_changed(); } From d2105fe66c17fa41a5efe66a5217dd5ef7e94c1f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:14:30 +0100 Subject: [PATCH 008/221] Round instant potion effects and measure splash range from the body Instant health and harm round to the nearest point instead of truncating. A splash potion measures the distance to the entity's box, not its centre, so a potion landing next to a player hits harder and reaches farther. --- crates/horizon-client/src/effects.rs | 7 +-- crates/horizon-client/src/game/potions.rs | 59 +++++++++++++++-------- 2 files changed, 44 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 17dce93ab..2ead9122b 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -129,15 +129,16 @@ fn periodic(id: &str, tick: i32, amp: i32) -> Option { _ => None, } } -/// `InstantenousMobEffect.applyInstantenousEffect` (potions apply these directly). +/// `HealOrHarmMobEffect.applyInstantaneousEffect` (potions apply these directly; +/// the amount rounds to the nearest whole point). pub fn instant(id: &str, amp: i32, scale: f64) -> Option { match id { "instant_health" => Some(EffectAction::Heal( - (scale * f64::from(4 << amp.min(30))) as i32 as f32, + (scale * f64::from(4 << amp.min(30)) + 0.5) as i32 as f32, )), "instant_damage" => Some(EffectAction::Hurt( "minecraft:magic", - (scale * f64::from(6 << amp.min(30))) as i32 as f32, + (scale * f64::from(6 << amp.min(30)) + 0.5) as i32 as f32, )), "saturation" => Some(EffectAction::Eat(amp + 1, 1.0)), _ => None, diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index b28c2fb4d..669cbea53 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -13,7 +13,10 @@ use horizon_client::{ items::ItemStack, mesher::Vertex, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] @@ -44,6 +47,22 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { .get(id) .copied() } +/// `ThrownSplashPotion.onHitAsPotion`: the squared distance from the potion's +/// box at the hit point to an entity's box grown by the hit margin +/// (`ProjectileUtil.computeMargin`), for entities that meet the potion's box +/// grown by (4, 2, 4); none when it is 16 or more. +fn splash_distance_sqr(at: Vec3, age: u32, bounds: Aabb) -> Option { + let potion = Aabb::new( + Vec3::new(at.x - 0.125, at.y, at.z - 0.125), + Vec3::new(at.x + 0.125, at.y + 0.25, at.z + 0.125), + ); + if !potion.inflate(Vec3::new(4.0, 2.0, 4.0)).intersects(bounds) { + return None; + } + let margin = ((f64::from(age) - 2.0) / 20.0).clamp(0.0, 0.3); + let d2 = potion.distance_squared_to_box(bounds.inflate(Vec3::new(margin, margin, margin))); + (d2 < 16.0).then_some(d2) +} impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). @@ -516,7 +535,7 @@ impl Game<'_> { } } if let Some(p) = hit { - landed.push((t.stack.clone(), p)); + landed.push((t.stack.clone(), p, t.age)); return false; } t.position = next; @@ -535,8 +554,8 @@ 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, age) in landed { + self.splash(&stack, at, age); } } /// `ThrownItemRenderer` for thrown splash and lingering potions and @@ -589,17 +608,20 @@ impl Game<'_> { &mut self, effects: &'static [(&'static str, i32, i32)], at: Vec3, + age: u32, scale: f64, ) { if let Some(p) = self.player.as_ref() { - let center = Vec3::new( - p.position.x, - p.position.y + f64::from(p.dimensions.height) / 2.0, - p.position.z, + let w = f64::from(p.dimensions.width) / 2.0; + let bounds = Aabb::new( + Vec3::new(p.position.x - w, p.position.y, p.position.z - w), + Vec3::new( + p.position.x + w, + p.position.y + f64::from(p.dimensions.height), + p.position.z + w, + ), ); - let d2 = - (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); - if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + if let Some(d2) = splash_distance_sqr(at, age, bounds) { let intensity = 1.0 - d2.sqrt() / 4.0; for (id, duration, amp) in effects { let instant = brewing::effect(id).is_some_and(|e| e.instant); @@ -620,7 +642,7 @@ impl Game<'_> { } } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3) { + fn splash(&mut self, stack: &ItemStack, at: Vec3, age: u32) { if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level // event 2002) and 3 to 11 experience. @@ -681,15 +703,14 @@ impl Game<'_> { }; // 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, age, scale)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); for (i, m) in self.mobs.iter().enumerate() { - let d2 = (m.position.x - at.x).powi(2) - + (m.position.y + m.kind.height / 2.0 - at.y).powi(2) - + (m.position.z - at.z).powi(2); - if m.alive() && d2 < 16.0 { + if m.alive() + && let Some(d2) = splash_distance_sqr(at, age, m.bounds()) + { let inverted = undead .get("minecraft:inverted_healing_and_harm") .is_some_and(|t| t.contains(&m.kind.id)); @@ -716,12 +737,12 @@ impl Game<'_> { let m = &mut self.mobs[i]; if harm { m.hurt( - (intensity * f64::from(6 << amp)) as i32 as f32, + (intensity * f64::from(6 << amp) + 0.5) as i32 as f32, Some([at.x, at.y, at.z]), &mut self.world.random, ); } else { - m.health = (m.health + (intensity * f64::from(4 << amp)) as i32 as f32) + m.health = (m.health + (intensity * f64::from(4 << amp) + 0.5) as i32 as f32) .min(m.kind.max_health); } } From 1b4fe0f06707a52a18540f36542ada812495849a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:28 +0100 Subject: [PATCH 009/221] Wither rose and open eyeblossom give bees an effect instead of breeding them --- crates/horizon-client/src/game/creatures.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..aff54b6da 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2797,6 +2797,22 @@ impl Game<'_> { self.trigger_entity("minecraft:tame_animal", "entity", &view); } } + // Bee.mobInteract: a wither rose or an open eyeblossom is eaten for + // its `getBeeInteractionEffect` instead of breeding the bee. + Species::Bee + if is_food + && matches!( + &*item, + "minecraft:wither_rose" | "minecraft:open_eyeblossom" + ) => + { + if &*item == "minecraft:wither_rose" { + m.add_effect("minecraft:wither", 40, 0); + } else { + m.add_effect("minecraft:poison", 25, 0); + } + consume = true; + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal From 581dc08cf5be4da424c2e308e7185b1f979a6d79 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:15:43 +0100 Subject: [PATCH 010/221] Fire shot_crossbow and killed_by_arrow advancement triggers --- crates/horizon-client/src/advancements.rs | 37 ++++++++++++++++++- crates/horizon-client/src/arrows.rs | 3 ++ .../horizon-client/src/game/advancements.rs | 13 +++++++ crates/horizon-client/src/game/creatures.rs | 11 ++++++ crates/horizon-client/src/game/crossbow.rs | 7 ++++ 5 files changed, 70 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..dda104281 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -4,7 +4,7 @@ //! conditions advancements use). use serde_json::Value; use std::{ - collections::{BTreeMap, HashMap}, + collections::{BTreeMap, BTreeSet, HashMap}, path::Path, }; @@ -703,6 +703,41 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo } true } +/// `KilledByArrowTrigger.TriggerInstance.matches`: the weapon, each listed +/// victim condition matched by a distinct victim, and the count of entity types. +pub fn killed_by_arrow( + c: &Value, + me: &EntityView, + victims: &[EntityView], + weapon: Option<&ItemView>, + w: &dyn World, +) -> bool { + fn ctx<'a>(e: &'a EntityView, me: &EntityView) -> Entities<'a> { + Entities { + this: Some(e), + origin: me.position, + tool: None, + block_pos: None, + } + } + if !conditions(&c["player"], &ctx(me, me), w) { + return false; + } + if !c["fired_from_weapon"].is_null() + && !weapon.is_some_and(|it| item(&c["fired_from_weapon"], it, w)) + { + return false; + } + let mut left: Vec<&EntityView> = victims.iter().collect(); + for want in c["victims"].as_array().into_iter().flatten() { + let Some(i) = left.iter().position(|e| conditions(want, &ctx(e, me), w)) else { + return false; + }; + left.remove(i); + } + let kinds: BTreeSet<&str> = victims.iter().map(|e| e.kind.as_str()).collect(); + range_i(&c["unique_entity_types"], kinds.len() as i64) +} /// The entities a loot-style condition list may refer to. pub struct Entities<'a> { pub this: Option<&'a EntityView>, diff --git a/crates/horizon-client/src/arrows.rs b/crates/horizon-client/src/arrows.rs index 30b501011..c23e2ec71 100644 --- a/crates/horizon-client/src/arrows.rs +++ b/crates/horizon-client/src/arrows.rs @@ -155,6 +155,8 @@ pub struct ArrowState { pub pickup: Pickup, /// `pickupItemStack`: what picking the arrow up gives. pub pickup_item: crate::items::ItemStack, + /// `AbstractArrow.firedFromWeapon`: the crossbow or bow it was shot from. + pub fired_from_weapon: Option, pub no_physics: bool, pub pierce: u8, /// `Entity.remainingFireTicks`. @@ -197,6 +199,7 @@ impl ArrowState { last_state: None, pickup: Pickup::Disallowed, pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1), + fired_from_weapon: None, no_physics: false, pierce: 0, fire_ticks: 0, diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..ed371417b 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -681,6 +681,19 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w) }); } + /// `KilledByArrowTrigger`: what the arrow killed and the weapon it came from. + pub(super) fn trigger_killed_by_arrow( + &mut self, + victims: &[EntityView], + weapon: Option<&ItemStack>, + ) { + let me = self.player_entity(); + let victims = victims.to_vec(); + let weapon = weapon.map(item_view); + self.trigger("minecraft:killed_by_arrow", move |c, w| { + adv::killed_by_arrow(c, &me, &victims, weapon.as_ref(), w) + }); + } /// A player condition plus one item (`item` key). pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) { let me = self.player_entity(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 194256040..0efef9bc6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2111,6 +2111,17 @@ impl Game<'_> { .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { self.last_hurt_by_player.insert(id, self.lan_acting); + // AbstractArrow.onHitEntity: KILLED_BY_ARROW for a kill + // (piercing arrows are not modelled). + if hurt + && let Some(m) = self.mobs.iter().find(|m| m.id == id) + && !m.alive() + { + let victim = self.mob_entity(m); + let weapon = + p.arrow.as_ref().and_then(|a| a.fired_from_weapon.as_ref()); + self.trigger_killed_by_arrow(&[victim], weapon); + } } hurt } diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index 70ccba8d3..0e0df1a62 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -152,6 +152,7 @@ impl Game<'_> { }; let charged = std::mem::take(&mut bow.data_mut().charged); bow.tidy(); + let weapon = bow.clone(); let count = charged.len(); // getShootingPower: a rocket among them slows every shot. let power = if charged.iter().any(|s| &*s.item == FIREWORK_ROCKET) { @@ -204,6 +205,7 @@ impl Game<'_> { if let Some(a) = arrow.arrow.as_mut() { a.set_item(ammo); a.set_owner(Some(Who::Player)); + a.fired_from_weapon = Some(weapon.clone()); } arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); self.creatures.projectiles.push(arrow); @@ -219,6 +221,11 @@ impl Game<'_> { .play("minecraft:item.crossbow.shoot", Some(eye), 1.0, pitch); self.damage_held(if rocket { 3 } else { 1 }); } + // CrossbowItem.performShooting: SHOT_CROSSBOW with the crossbow, which + // is an empty stack (no match) when the shots broke it. + if let Some(stack) = self.held().cloned() { + self.trigger_item("minecraft:shot_crossbow", &stack); + } } } From 94592a35ac5922d6f79b5ad53e1a3f71034d4c2e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:16:33 +0100 Subject: [PATCH 011/221] Use the flat world's horizon height for the dark disc and void fog --- crates/horizon-client/src/game.rs | 5 +++++ crates/horizon-client/src/game/lan.rs | 3 ++- crates/horizon-client/src/game/remote.rs | 4 ++++ crates/horizon-client/src/game/render_tick.rs | 20 ++++++++++++++++--- crates/horizon-client/src/lan/hub.rs | 6 +++++- 5 files changed, 33 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..23b66e649 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1389,6 +1389,8 @@ struct Game<'a> { sleep_timer: u32, dim: Dim, world_root: PathBuf, + /// The world's overworld is superflat (`ClientLevelData.isFlat`). + overworld_flat: bool, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, /// A server's players on their way to another level, each waiting for @@ -7936,6 +7938,8 @@ impl Game<'_> { book.to_be_displayed.retain(|r| index.contains(r)); self.dim = dim; self.world_root = save_root.clone(); + self.overworld_flat = + horizon_client::save::WorldGen::read(&save_root).is_some_and(|w| w.flat); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); self.clear_entities(); @@ -12272,6 +12276,7 @@ impl<'a> Game<'a> { sleep_timer: 0, dim: Dim::Overworld, world_root: PathBuf::new(), + overworld_flat: false, travelling: None, server_trips: Vec::new(), level_teleports: Vec::new(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 61003e085..30ba4bcb0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -582,7 +582,8 @@ impl Game<'_> { let host_uuid = host.unwrap_or(0); self.next_entity += 1; let host_entity = self.next_entity as i32; - let hub = Hub::new(lan, sync, encoder, config); + let mut hub = Hub::new(lan, sync, encoder, config); + hub.flat_overworld = self.overworld_flat; let port = hub.lan.port; self.world.block_log = Some(Vec::new()); self.world.light_log = Some(Default::default()); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 857f955da..b83bd6d66 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -189,6 +189,8 @@ pub(super) struct Remote { input: horizon_client::interaction_input::InteractionInput, stop_mining: bool, placing: Option<([i32; 3], u64)>, + /// `CommonPlayerSpawnInfo.isFlat`: the level is a superflat one. + pub(super) flat: bool, death_message: Option, player_type: Option>, /// Inventory as last synchronised, for creative-mode slot updates. @@ -472,6 +474,7 @@ impl Game<'_> { input: Default::default(), stop_mining: false, placing: None, + flat: false, death_message: None, player_type, synced: vec![None; 36], @@ -981,6 +984,7 @@ impl Game<'_> { r.chunk_format = Arc::new(r.chunk_format.with_dimension(&dimension)); r.dimension = dimension; r.game_mode = spawn.game_type; + r.flat = spawn.flat; r.loaded_sent = false; // A replacement LocalPlayer has a fresh sendPosition baseline. r.position_sender = Default::default(); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..36840dabd 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -93,7 +93,7 @@ impl Game<'_> { camera_y: camera.y, // level.getMinY(): the Nether and the End start at y 0. min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, - flat: false, + flat: self.level_flat(), forward: forward.map(|c| c as f32), rain, thunder, @@ -107,9 +107,23 @@ impl Game<'_> { }, ) } - /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. + /// `ClientLevelData.isFlat`: on the server thread, as its spawn info said. + fn level_flat(&self) -> bool { + match self.remote.as_ref() { + Some(r) => r.flat, + None => self.dim == Dim::Overworld && self.overworld_flat, + } + } + /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon and not under + /// water. `ClientLevelData.getHorizonHeight`: the bottom of a flat world, + /// otherwise y 63. pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { - camera.y < 63.0 + let horizon = if self.level_flat() { + f64::from(MIN_Y) + } else { + 63.0 + }; + camera.y < horizon && fog_type( &self.world, self.res.facts(), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 910911d80..96e043492 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -147,6 +147,9 @@ pub struct Hub { /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), /// whose moves are never checked. pub singleplayer_owner: Option, + /// The overworld is superflat (`ServerLevel.isFlat`, sent as + /// `CommonPlayerSpawnInfo.isFlat`). + pub flat_overworld: bool, /// Who rides what, set by the game before each tick. pub riding: super::entity::Riding, /// The scoreboard's teams, set by the game each tick, for players' @@ -321,6 +324,7 @@ impl Hub { ticks: 0, movement_checks: (true, true), singleplayer_owner: None, + flat_overworld: false, riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, @@ -548,7 +552,7 @@ impl Hub { game_type: game_mode, previous_game_type: None, debug: false, - flat: false, + flat: self.flat_overworld && self.config.dimension == "minecraft:overworld", last_death: None, portal_cooldown: 0, sea_level: 63, From e87e839c97ba351d519804aa2290cbc70bf1ad45 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:17:44 +0100 Subject: [PATCH 012/221] Fire the construct_beacon trigger when a beacon activates --- crates/horizon-client/src/advancements.rs | 2 +- .../horizon-client/src/game/advancements.rs | 13 ++++++++++ crates/horizon-client/src/game/beacon.rs | 24 +++++++++++++++++++ 3 files changed, 38 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..e09f97b6d 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -458,7 +458,7 @@ fn range_f(v: &Value, x: f64) -> bool { _ => false, } } -fn range_i(v: &Value, x: i64) -> bool { +pub fn range_i(v: &Value, x: i64) -> bool { range_f(v, x as f64) } /// A registry id, `#tag`, or list matched against one id. diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..ad7a2368b 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -708,6 +708,19 @@ impl Game<'_> { let it = item_view(stack); self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); } + /// `ConstructBeaconTrigger`: the pyramid levels of the new beacon. + pub(super) fn trigger_construct_beacon(&mut self, levels: i32) { + let me = self.player_entity(); + self.trigger("minecraft:construct_beacon", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) && adv::range_i(&c["level"], i64::from(levels)) + }); + } /// `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/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 24ead3a3d..8830547db 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -164,11 +164,35 @@ impl Game<'_> { let (was, is) = (previous > 0, b.levels > 0); if !was && is { self.beacon_sound([x, y, z], "minecraft:block.beacon.activate"); + let levels = b.levels; + self.for_each_player(|g| g.beacon_constructed([x, y, z], levels)); } else if was && !is { self.beacon_sound([x, y, z], "minecraft:block.beacon.deactivate"); } } } + /// `BeaconBlockEntity.tick` after activating: `CONSTRUCT_BEACON` for a + /// player in the box `AABB(x, y, z, x, y - 4, z).inflate(10, 5, 10)`. + fn beacon_constructed(&mut self, p: [i32; 3], levels: i32) { + let Some(bb) = self + .player + .as_ref() + .map(|pl| pl.dimensions.bounds(pl.position)) + else { + return; + }; + let (lo, hi) = (bb.min_position(), bb.max_position()); + let [x, y, z] = p.map(f64::from); + if lo.x < x + 10.0 + && hi.x > x - 10.0 + && lo.y < y + 5.0 + && hi.y > y - 9.0 + && lo.z < z + 10.0 + && hi.z > z - 10.0 + { + self.trigger_construct_beacon(levels); + } + } pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { let at = [ f64::from(p[0]) + 0.5, From 3c013dac75e558343c75932b154f7949227dfdaa Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 15:18:03 +0100 Subject: [PATCH 013/221] An axe turns an unoxidized copper golem statue back into a golem The golem stands where the statue was, facing the same way, the axe loses durability and the statue block is removed. --- crates/horizon-client/src/game.rs | 4 ++ .../horizon-client/src/game/copper_golems.rs | 58 +++++++++++++++++++ 2 files changed, 62 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 1d86fe990..b3906cc68 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3519,6 +3519,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_golem_statue(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/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 2f98e1c7e..e8b0687ee 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -204,6 +204,64 @@ impl Game<'_> { } } // ---- interactions ----------------------------------------------------- + /// `WeatheringCopperGolemStatueBlock.useItemOn`: an axe on an unoxidized + /// statue turns it back into a golem (`CopperGolemStatueBlockEntity.removeStatue`), + /// wearing the axe. Weathered statues are scraped by the axe's own + /// transform instead. + pub(super) fn use_golem_statue(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + if !held.is_some_and(|s| s.item.ends_with("_axe")) { + return false; + } + let registry = self.pack.assets.registry; + let Some(state) = registry.state(self.world.block(pos[0], pos[1], pos[2])) else { + return false; + }; + if state.name != "minecraft:copper_golem_statue" { + return false; + } + // `Direction.toYRot` of the statue's facing. + let yaw = match state.properties.get("facing").map(String::as_str) { + Some("west") => 90.0, + Some("north") => 180.0, + Some("east") => 270.0, + _ => 0.0, + }; + let waterlogged = state + .properties + .get("waterlogged") + .is_some_and(|w| w == "true"); + // initCopperGolem: at the block's feet, facing as the statue does. + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ]; + let Some(id) = self.spawn_mob("minecraft:copper_golem", at, true) else { + return false; + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.yaw = yaw; + m.previous_yaw = yaw; + m.body_yaw = yaw; + m.previous_body_yaw = yaw; + m.head_yaw = yaw; + m.previous_head_yaw = yaw; + } + self.damage_held(1); + self.audio + .play("minecraft:entity.copper_golem.spawn", Some(at), 1.0, 1.0); + // Level.removeBlock(pos, false): air, or the water the statue stood in. + let replacement = registry.default_state(if waterlogged { + "minecraft:water" + } else { + "minecraft:air" + }); + if let Some(replacement) = replacement { + let _ = self.level_set(pos, replacement); + } + self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); + true + } /// `CopperGolem.mobInteract`; true when handled. pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool { if self.mobs[index].species() != Species::CopperGolem || !self.mobs[index].alive() { From 775e5b19cb399f62c446745d22df950b2bf31f04 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:59:37 +0100 Subject: [PATCH 014/221] horizon-items: tests load prepared items without the client's Assets #2038's bundle tooltip tests and #2037's loot tests share one helper that reads the block registry and facts directly. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-items/src/bundle.rs | 9 +------- crates/horizon-items/src/items.rs | 36 +++++++++++++++--------------- 2 files changed, 19 insertions(+), 26 deletions(-) diff --git a/crates/horizon-items/src/bundle.rs b/crates/horizon-items/src/bundle.rs index 42473729f..efce3c822 100644 --- a/crates/horizon-items/src/bundle.rs +++ b/crates/horizon-items/src/bundle.rs @@ -322,14 +322,7 @@ mod tooltip_tests { /// The prepared resources, when they are on this machine: the tooltip /// asks the item registry whether a stack is a bundle. fn items() -> Option { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../.local/horizon-client/26.3"); - if !root.join("items.json").exists() { - return None; - } - let assets = crate::assets::Assets::load(&root).ok()?; - let facts = crate::blocks::BlockFacts::load(&root, assets.registry).ok()?; - Items::load(&root, assets.registry, &facts).ok() + crate::items::prepared_items() } fn bundle_with(counts: &[(&str, u32)]) -> ItemStack { diff --git a/crates/horizon-items/src/items.rs b/crates/horizon-items/src/items.rs index ecf3b9d63..ef8b9c810 100644 --- a/crates/horizon-items/src/items.rs +++ b/crates/horizon-items/src/items.rs @@ -1619,6 +1619,22 @@ mod bucket_use_tests { } } +/// The items of the prepared resources, when they are on this machine, for +/// tests: the block registry and facts as the client's `Assets::load` reads them. +#[cfg(test)] +pub(crate) fn prepared_items() -> Option { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return None; + } + let (registry, _) = + BlockRegistry::from_facts_json_with_flags(fs::File::open(root.join("facts.json")).ok()?) + .ok()?; + let facts = BlockFacts::load(&root, ®istry).ok()?; + Items::load(&root, ®istry, &facts).ok() +} + #[cfg(test)] mod tests { use super::*; @@ -1641,22 +1657,6 @@ mod tests { } } - /// The items of the prepared resources, when they are on this machine - /// (the block registry and facts as the client's `Assets::load` reads them). - fn prepared_items() -> Option { - let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../../.local/horizon-client/26.3"); - if !root.join("items.json").exists() { - return None; - } - let (registry, _) = BlockRegistry::from_facts_json_with_flags( - std::fs::File::open(root.join("facts.json")).ok()?, - ) - .ok()?; - let facts = BlockFacts::load(&root, ®istry).ok()?; - Items::load(&root, ®istry, &facts).ok() - } - #[test] fn fortune_silk_touch_and_looting() { let items = Items::for_tests(HashMap::new()); @@ -1746,7 +1746,7 @@ mod tests { /// `EnchantRandomlyFunction`) put their enchantments on the stack. #[test] fn loot_enchant_functions_enchant_the_rolled_item() { - let Some(items) = prepared_items() else { + let Some(items) = super::prepared_items() else { return; }; let props = BTreeMap::new(); @@ -1807,7 +1807,7 @@ mod tests { /// Mending book, then `set_count` uniform 1..64, is 46. #[test] fn a_single_level_enchantment_draws_no_level() { - let Some(items) = prepared_items() else { + let Some(items) = super::prepared_items() else { return; }; let props = BTreeMap::new(); From 83a6f5c7b9b76071bc7798b63f11085d37beb61a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:27:13 +0100 Subject: [PATCH 015/221] Revert "Decorated pot: say why only the outer faces stay" This reverts commit d338bcd070a6c2bf2568c1f57900bf222299929b. --- crates/horizon-client/src/block_entity_render.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 1bbc7a207..3d8c0258b 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -66,10 +66,10 @@ impl ModelPart { children, } } - /// `parse` of the entity model layer `layer`. The pot's `top` and `bottom` are flat - /// boxes (`DecoratedPotRenderer.createBaseLayer`) drawn with a culling render type, so - /// from outside only `top`'s up face and `bottom`'s down face show. Both faces of each - /// plane would fight for the same pixels here: keep the outer one. + /// `parse` of the entity model layer `layer`. Vanilla culls back faces for the pot's + /// `top` and `bottom` planes (`DecoratedPotRenderer.createBaseLayer`), so only the + /// up face of `top` and the down face of `bottom` show; ours draws both faces of each + /// plane, which fight for the same pixels, so the culled face is dropped here. pub fn parse_layer(layer: &str, v: &Value) -> Self { let mut part = Self::parse(v); if layer == "minecraft:decorated_pot_base#main" { From 9841ce7824d8a65fbc66f5a2d2ecef07defd4912 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:27:13 +0100 Subject: [PATCH 016/221] Revert "Decorated pot: draw one face of its top and bottom planes" This reverts commit 408a75aeb32f1f1e34d03f4ff9a42098fcf8514b. --- .../horizon-client/src/block_entity_render.rs | 23 +------------------ .../horizon-client/src/item_render/special.rs | 2 +- 2 files changed, 2 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 3d8c0258b..10c5e2509 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -66,24 +66,6 @@ impl ModelPart { children, } } - /// `parse` of the entity model layer `layer`. Vanilla culls back faces for the pot's - /// `top` and `bottom` planes (`DecoratedPotRenderer.createBaseLayer`), so only the - /// up face of `top` and the down face of `bottom` show; ours draws both faces of each - /// plane, which fight for the same pixels, so the culled face is dropped here. - pub fn parse_layer(layer: &str, v: &Value) -> Self { - let mut part = Self::parse(v); - if layer == "minecraft:decorated_pot_base#main" { - // `ModelPart.Cube` polygon order: down, up, west, north, east, south. - for (name, face) in [("top", 1), ("bottom", 0)] { - if let Some((_, plane)) = part.children.iter_mut().find(|(n, _)| n == name) - && let Some(&polygon) = plane.polygons.get(face) - { - plane.polygons = vec![polygon]; - } - } - } - part - } pub fn child(&self, name: &str) -> Option<&ModelPart> { self.children .iter() @@ -812,10 +794,7 @@ impl BlockEntityRenderer { let all: Value = serde_json::from_slice(&std::fs::read(root.join("entity-models.json"))?)?; let models = MODELS .iter() - .filter_map(|(key, layer)| { - all.get(*layer) - .map(|v| (*key, ModelPart::parse_layer(layer, v))) - }) + .filter_map(|(key, layer)| all.get(*layer).map(|v| (*key, ModelPart::parse(v)))) .collect(); let mut renderer = Self::new(models, registry); renderer.visibility = Some(Mutex::new(crate::models::load_visibility(root, registry)?)); diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index 6f4980169..d42378db1 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -60,7 +60,7 @@ pub(super) fn load_parts(root: &Path) -> HashMap { .chain(COPPER_GOLEM_LAYERS.iter()) .filter_map(|(key, layer)| { all.get(*layer) - .map(|v| ((*key).to_owned(), ModelPart::parse_layer(layer, v))) + .map(|v| ((*key).to_owned(), ModelPart::parse(v))) }) .collect() } From c987778e97f2290abce276333ffc22ba24f6ef78 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 16:34:24 +0100 Subject: [PATCH 017/221] Decorated pot: keep every quad and cull back faces like entitySolid --- crates/horizon-client/src/block_entity_render.rs | 12 +++++++++++- crates/horizon-client/src/entity.wgsl | 9 +++++++-- crates/horizon-client/src/item_render.rs | 7 +++++-- crates/horizon-client/src/item_render/gui.rs | 1 + crates/horizon-client/src/item_render/special.rs | 14 ++++++++++++++ crates/horizon-client/src/mesher.rs | 6 +++++- 6 files changed, 43 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 10c5e2509..f28008d16 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -5,7 +5,11 @@ //! (`entity-models.json`); transforms, animation and textures follow each //! vanilla renderer. Faces are lit like the `entity` shader: the lightmap at //! the block plus `minecraft_mix_light` with the level's two diffuse lights. -use crate::{hud::Rect, mesher::Vertex, world::World}; +use crate::{ + hud::Rect, + mesher::{CULL_BACK, Vertex}, + world::World, +}; use glam::{DVec3, Mat4, Quat, Vec3}; use horizon_core::geometry::{ Direction, @@ -1384,6 +1388,7 @@ impl BlockEntityRenderer { m *= around(Mat4::from_rotation_y(turn * decay), pivot); } } + let first = out.len(); if let Some(paint) = paint("entity/decorated_pot/decorated_pot_base", 0xFFFFFF, packed) { @@ -1401,6 +1406,11 @@ impl BlockEntityRenderer { draw_part(part, side, m, &none, paint, out); } } + // `DecoratedPotRenderer` submits every part with `entitySolid`, which culls + // back faces: the flat `top` and `bottom` planes show one side each. + for vertex in &mut out[first..] { + vertex.normal = CULL_BACK; + } } Kind::EndPortal => { // TheEndPortalRenderer.TRANSFORMATION: y from 6/16 to 12/16; only the diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2e865dfb1..4bd8983d9 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -44,6 +44,8 @@ struct Out { // entity.vsh's lightMapColor, multiplied in after the overlay. @location(9) light_color: vec4, @location(10) @interpolate(flat) weather_rect: vec4, + // 1 drops the quad's back-facing pixels (Vertex::normal w = 1), like a culling render type. + @location(11) @interpolate(flat) cull: u32, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -92,7 +94,10 @@ fn entity_vertex(position: vec3, uv: vec2, // minecraft_mix_light: the vertex colour times the cardinal light only. var c = color; var back = c; - if normal.w != 0.0 { + // Normal w: 0 keeps the baked colour, +-127 shades by the normal, and a small positive 1 + // keeps the baked colour but culls back faces (entitySolid models such as the decorated pot). + out.cull = select(0u, 1u, normal.w > 0.0 && normal.w < 0.5); + if abs(normal.w) >= 0.5 { c = vec4(c.rgb * entity_light(normal.xyz, globals.time.y != 0.0), c.a); back = select(c, vec4(back.rgb * entity_light(-normal.xyz, globals.time.y != 0.0), back.a), normal.w < 0.0); } @@ -187,7 +192,7 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { // clouds.fsh: alpha fades out towards the cloud fog end. return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y))); } - if color.a < 0.1 { discard; } + if color.a < 0.1 || (in.cull != 0u && !front) { discard; } // entity.fsh calculateFinalColor: the overlay (hurt red, TNT white) over the // 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); diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index c2f5c8400..540f7c23c 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -12,7 +12,7 @@ mod special; use crate::{ block_entity_render::{ModelPart, diffuse}, hud::Rect, - mesher::Vertex, + mesher::{CULL_BACK, Vertex}, }; use glam::{Mat3, Mat4, Vec3}; use horizon_assets::{ @@ -46,6 +46,8 @@ pub struct ItemQuad { pub foil: Foil, /// `MaterialInfo.lightEmission` (block light floor). pub light_emission: u8, + /// The render type culls back faces (`entitySolid`): world drawing discards them. + pub cull_back: bool, } /// Which glint render type a quad uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -246,6 +248,7 @@ fn submit_quads( color: argb(color), foil, light_emission: q.light_emission, + cull_back: false, }); } } @@ -692,7 +695,7 @@ impl ItemSink for WorldSink<'_> { let overlay = if q.foil == Foil::None { 0 } else { 7 }; for (p, uv) in q.pos.iter().zip(q.uv) { self.out.push(Vertex { - normal: [0; 4], + normal: if q.cull_back { CULL_BACK } else { [0; 4] }, pos: p.to_array(), uv, layer: overlay, diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index e3d7cc876..93645559a 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -269,6 +269,7 @@ mod tests { color, foil: Foil::None, light_emission: 0, + cull_back: false, } } diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index d42378db1..8a54f49bb 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -65,6 +65,17 @@ pub(super) fn load_parts(root: &Path) -> HashMap { .collect() } +/// Marks every quad passed on as drawn with a back-face-culling render type (`entitySolid`). +struct CullBack<'a>(&'a mut dyn ItemSink); +impl ItemSink for CullBack<'_> { + fn quad(&mut self, quad: ItemQuad) { + self.0.quad(ItemQuad { + cull_back: true, + ..quad + }); + } +} + /// A pose override for a named part (`setupAnim`). type Adjust<'a> = &'a dyn Fn(&str, &mut [f32; 9]); fn none(_: &str, _: &mut [f32; 9]) {} @@ -119,6 +130,7 @@ fn draw( color, foil, light_emission: 0, + cull_back: false, }); } for (child_name, child) in &part.children { @@ -569,6 +581,8 @@ pub(super) fn submit( } SpecialKind::DecoratedPot => { let sides = pot_sides(argument); + // `DecoratedPotRenderer` draws every part with `entitySolid`. + let sink = &mut CullBack(sink); if let Some(base) = renderer.part("decorated_pot_base") && let Some(r) = sprites .get("entity/decorated_pot/decorated_pot_base") diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index fff3c6aa0..788eb316d 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -36,9 +36,13 @@ pub struct Vertex { pub color: u32, /// Smooth light, 16x fixed point: sky in bits 0..8, block in bits 8..16. pub light: u32, - /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour. + /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour, + /// [`CULL_BACK`] to keep it and also drop back-facing pixels. pub normal: [i8; 4], } +/// `Vertex::normal` of a baked-colour quad of an `entitySolid` model: the render type culls +/// back faces, which the entity pipelines here do not, so `entity.wgsl` discards them. +pub const CULL_BACK: [i8; 4] = [0, 0, 0, 1]; /// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour, /// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes /// rather than vanilla's 28: the UV is fixed point, which holds model UVs From d18197a17645d076b4d61e715a2150e72f8b5c97 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:14:24 +0100 Subject: [PATCH 018/221] Shield: hold it up in first person and show the block pose on other players --- crates/horizon-client/src/game/item_draw.rs | 6 +++++- crates/horizon-client/src/game/lan.rs | 12 ++++++++++++ crates/horizon-client/src/game/remote.rs | 14 ++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..b6c42f6e9 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -164,12 +164,16 @@ pub(super) fn owner_at(position: [f64; 3], yaw: f32, entity_type: &str) -> Owner ..Default::default() } } -/// `UseDuration` of a stack: 72000 for drawn items, the consume time for food. +/// `UseDuration` of a stack (`Item.getUseDuration`): 72000 for drawn items +/// and for `blocks_attacks` items (shields), the consume time for food. fn use_duration(components: &Components) -> i32 { if let Some(c) = components.get("minecraft:consumable") { let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6); return (seconds * 20.0) as i32; } + if components.get("minecraft:blocks_attacks").is_some() { + return 72_000; + } let item_model = components .get("minecraft:item_model") .and_then(Value::as_str) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 63aea7e9f..3ad66eaf8 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1400,6 +1400,18 @@ impl Game<'_> { let using = host.play.get(&g.conn).and_then(|p| p.using()); m.extra.using_item = using.map_or(0, |(_, ticks)| ticks as i32 + 1); m.extra.using_off_hand = using.is_some_and(|(slot, _)| slot == OFFHAND_SLOT); + // AvatarRenderer.getArmPose: the used item's BLOCK animation (an + // item with `blocks_attacks`) raises the arm. + m.extra.blocking = using + .and_then(|(slot, _)| { + if slot == OFFHAND_SLOT { + m.extra.off_hand.as_ref() + } else { + m.extra.main_hand.as_ref() + } + }) + .and_then(|i| self.res.items().get(i)) + .is_some_and(|i| i.blocks_attacks.is_some()); } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e9f30e84b..ea0927ead 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3525,6 +3525,20 @@ impl Game<'_> { // LivingEntity.updatingUsingItem: the ticks the item has been // used before this one. Another player's use particles; a mob's // drawn bow only needs the count (its pull follows it). + if player { + // AvatarRenderer.getArmPose: the used item's BLOCK animation + // (an item with `blocks_attacks`) raises the arm. + let used = if m.extra.using_off_hand { + &m.extra.off_hand + } else { + &m.extra.main_hand + }; + m.extra.blocking = m.extra.using_item > 0 + && used + .as_ref() + .and_then(|i| self.res.items().get(i)) + .is_some_and(|i| i.blocks_attacks.is_some()); + } if m.extra.using_item > 0 { if player { let item = if m.extra.using_off_hand { From bf508c2842825c09abb986261342f53e38953af7 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:45:39 +0100 Subject: [PATCH 019/221] Let mobs, dropped items and projectiles trigger pressure plates and tripwires --- crates/horizon-client/src/game.rs | 91 ++++++++++++++++++++++-- crates/horizon-client/src/projectiles.rs | 17 +++++ 2 files changed, 103 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ddb07912a..1cd69e037 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -546,6 +546,11 @@ struct GameLevel<'w> { cart_boxes: Vec<([f64; 3], [f64; 3])>, /// The other entities that keep blocks from being placed into them. blockers: Blockers<'w>, + /// Item entities, experience orbs and projectiles, which trigger plates and + /// tripwires but never keep a block from being placed. + dropped: &'w [ItemEntity], + orbs: &'w [ExperienceOrb], + projectiles: &'w [horizon_client::projectiles::Projectile], biomes: &'w Biomes, seed: i64, behaviours: &'w Behaviours, @@ -615,6 +620,53 @@ impl EntityObstructionWorld for BuildingObstruction { } } impl GameLevel<'_> { + /// The mobs that trigger plates and tripwires: living entities that don't + /// ignore block triggers (`Entity.isIgnoringBlockTriggers`: bats; armor + /// stands are not in `mobs`). + fn mob_trigger_boxes(&self) -> impl Iterator + '_ { + self.blockers + .mobs + .iter() + .filter(|m| !m.removed && m.species() != horizon_client::mobs::Species::Bat) + .map(Mob::bounds) + } + /// The non-living entities that trigger plates and tripwires (boats, + /// crystals, primed TNT, falling blocks, item entities, experience orbs and + /// projectiles). + fn other_trigger_boxes(&self) -> impl Iterator + '_ { + let b = self.blockers; + let square = |p: Vec3, size: f64| { + Aabb::new( + Vec3::new(p.x - size / 2.0, p.y, p.z - size / 2.0), + Vec3::new(p.x + size / 2.0, p.y + size, p.z + size / 2.0), + ) + }; + b.boats + .iter() + .map(boats::Boat::bounds) + .chain(b.crystals.iter().map(|c| { + // EntityType.END_CRYSTAL: 2 x 2. + let p = c.position; + Aabb::new( + Vec3::new(p.x - 1.0, p.y, p.z - 1.0), + Vec3::new(p.x + 1.0, p.y + 2.0, p.z + 1.0), + ) + })) + .chain(b.tnts.iter().map(tnt::PrimedTnt::bounds)) + .chain( + b.falling + .iter() + .map(|f| horizon_client::falling_block::bounds(f.position)), + ) + .chain(self.dropped.iter().map(ItemEntity::bounds)) + // EntityType.EXPERIENCE_ORB: 0.5 x 0.5. + .chain(self.orbs.iter().map(move |o| square(o.position, 0.5))) + .chain( + self.projectiles + .iter() + .map(move |p| square(p.position, p.kind.size())), + ) + } /// 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). @@ -838,7 +890,8 @@ impl LevelAccess for GameLevel<'_> { self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z) } /// Entities that trigger pressure plates, tripwires and detector rails: - /// the players (the host and the LAN guests, mobs) and the minecarts. + /// the players (the host and the LAN guests), the mobs, the minecarts and + /// the other entities that don't ignore block triggers. fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { let hit = |(lo, hi): &([f64; 3], [f64; 3])| { area.intersects(Aabb::new( @@ -847,6 +900,16 @@ impl LevelAccess for GameLevel<'_> { )) }; let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count(); + let mobs = || { + self.mob_trigger_boxes() + .filter(|b| area.intersects(*b)) + .count() + }; + let others = || { + self.other_trigger_boxes() + .filter(|b| area.intersects(*b)) + .count() + }; let players = || { self.player_box .iter() @@ -856,8 +919,8 @@ impl LevelAccess for GameLevel<'_> { }; match query { EntityQuery::Minecart => carts(), - EntityQuery::Mobs => players(), - EntityQuery::Everything => players() + carts(), + EntityQuery::Mobs => players() + mobs(), + EntityQuery::Everything => players() + carts() + mobs() + others(), } } fn emit(&mut self, event: LevelEvent) { @@ -2495,6 +2558,9 @@ impl Game<'_> { let mut level = GameLevel { cart_boxes, blockers, + dropped: &self.dropped, + orbs: &self.orbs, + projectiles: &self.creatures.projectiles, world: &mut self.world, facts: self.res.facts(), collision: self.collision, @@ -2625,7 +2691,8 @@ impl Game<'_> { .filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z)) .collect(); // Entity.checkInsideBlocks for the plates, tripwires and detector rails - // under the players (the host and the LAN guests) and the minecarts. + // under the players (the host and the LAN guests) and the minecarts + // (the mobs and other entities are added in `with_level` below). let mut inside = Vec::new(); let guests = self.lan_block_trigger_boxes(); let boxes = self @@ -2686,7 +2753,21 @@ impl Game<'_> { } } self.with_level(|b, level, ticks| { - for pos in inside { + // The mobs and the other entities (items, orbs, projectiles...) too. + let mut touched: Vec = Vec::new(); + for bounds in level.mob_trigger_boxes().chain(level.other_trigger_boxes()) { + let (lo, hi) = (bounds.min_position(), bounds.max_position()); + for x in (lo.x + 1e-7).floor() as i32..=(hi.x - 1e-7).floor() as i32 { + for y in (lo.y + 1e-7).floor() as i32..=(hi.y - 1e-7).floor() as i32 { + for z in (lo.z + 1e-7).floor() as i32..=(hi.z - 1e-7).floor() as i32 { + touched.push(BlockPos::new(x, y, z)); + } + } + } + } + touched.sort_unstable_by_key(|p| (p.x, p.y, p.z)); + touched.dedup(); + for pos in inside.into_iter().chain(touched) { b.entity_inside(level, ticks, pos); } for (pos, on_ground, feet_y) in standing { diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 219d59b6b..a1d6e5215 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -62,6 +62,23 @@ pub enum ProjectileKind { }, } impl ProjectileKind { + /// The width and height of its entity type's `sized(...)`. + pub fn size(&self) -> f64 { + match self { + Self::Arrow { .. } => 0.5, + Self::Snowball + | Self::Egg + | Self::EnderPearl + | Self::LlamaSpit + | Self::Potion { .. } => 0.25, + Self::SmallFireball + | Self::WindCharge + | Self::BreezeWindCharge + | Self::ShulkerBullet { .. } + | Self::WitherSkull { .. } => 0.3125, + Self::LargeFireball { .. } => 1.0, + } + } /// Its entity type. pub fn id(&self) -> &'static str { match self { From 6dcf4b3e8bbe734a1d906111405875ecee668579 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:45:43 +0100 Subject: [PATCH 020/221] Use the real local difficulty for the phantom spawn check The phantom spawn gate assumed a fixed effective difficulty of 2. Use the local difficulty at the player instead, so easy, hard, a long-played chunk and the moon phase change how often phantoms spawn. --- crates/horizon-client/src/game/stats.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index 7f64c6bb2..c653bf265 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -366,9 +366,10 @@ impl Game<'_> { if pos[1] < 63 || !self.can_see_sky(pos) { return; } - // DifficultyInstance.isHarderThan(random * 3) at normal difficulty. + // `getCurrentDifficultyAt(playerPos).isHarderThan(random * 3)`. + let difficulty = self.local_difficulty([position.x, position.y, position.z]); let r = &mut self.world.random; - if r.next_float() * 3.0 >= 2.0 { + if difficulty.effective <= r.next_float() * 3.0 { return; } if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 { From b283f2ad314243210014263184ebf826eca53f68 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:45:44 +0100 Subject: [PATCH 021/221] Hurt mobs that touch a cactus or a sweet berry bush Mobs ignored both blocks. A mob inside a cactus now takes 1 damage a tick, and a mob inside a sweet berry bush is slowed (0.8, 0.75, 0.8) and, in a grown bush, takes 1 damage when it moved at least 0.003 on X or Z. Foxes and bees are left alone. --- crates/horizon-client/src/mobs.rs | 15 ++++++-- crates/horizon-client/src/mobs/ai.rs | 48 ++++++++++++++++++++++++ crates/horizon-client/src/mobs/living.rs | 9 ++++- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..0edcd3620 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -815,6 +815,8 @@ pub struct Mob { pub previous_swell: i32, pub ambient_timer: i32, pub fall_distance: f64, + /// `Entity.stuckSpeedMultiplier`: the next move is scaled by it. + pub stuck_multiplier: Vec3, pub persistent: bool, /// `CustomName` (plain text) and `CustomNameVisible`. pub custom_name: Option, @@ -1569,6 +1571,7 @@ impl Mob { // Mob.ambientSoundTime starts at 0. ambient_timer: 0, fall_distance: 0.0, + stuck_multiplier: Vec3::ZERO, persistent: false, random, ai: Box::default(), @@ -1640,13 +1643,17 @@ impl Mob { } } pub fn bounds(&self) -> Aabb { + self.bounds_at(self.position) + } + /// `Entity.makeBoundingBox(position)`. + pub fn bounds_at(&self, position: Vec3) -> Aabb { let w = f64::from(self.width()) / 2.0; Aabb::new( - Vec3::new(self.position.x - w, self.position.y, self.position.z - w), + Vec3::new(position.x - w, position.y, position.z - w), Vec3::new( - self.position.x + w, - self.position.y + f64::from(self.height()), - self.position.z + w, + position.x + w, + position.y + f64::from(self.height()), + position.z + w, ), ) } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..ffc74d0b9 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -400,6 +400,7 @@ pub fn tick( if !m.no_ai { ai_step(m, w, level_random, events); } + effects_from_blocks(m, w); if m.species() == Species::Rabbit { super::rabbit::post_tick(m); } @@ -428,6 +429,53 @@ pub fn tick( } true } +/// `LivingEntity.aiStep` -> `Entity.applyEffectsFromBlocks` for the blocks +/// that hurt or hold a mob: the cactus (`CactusBlock.entityInside`, 1) and the +/// sweet berry bush (`SweetBerryBushBlock.entityInside`: stuck at 0.8, 0.75, +/// 0.8, and a grown bush pricks for 1 when the mob moved at least 0.003 on X +/// or Z this tick). The blocks are those the mob's box touches where it +/// started the tick and where it ended. +fn effects_from_blocks(m: &mut Mob, w: &MobWorld) { + let mut visited: Vec<[i32; 3]> = Vec::new(); + for at in [m.previous, m.position] { + if !m.alive() { + return; + } + let b = m.bounds_at(at).deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 { + for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 { + for z in b.min_position().z.floor() as i32..=b.max_position().z.floor() as i32 { + let p = [x, y, z]; + if visited.contains(&p) { + continue; + } + match w.block_name(x, y, z) { + "minecraft:cactus" => { + m.damage(1.0, Damage::of(DamageKind::Cactus)); + } + "minecraft:sweet_berry_bush" + if !matches!(m.species(), Species::Fox | Species::Bee) => + { + m.fall_distance = 0.0; + m.stuck_multiplier = + Vec3::new(f64::from(0.8_f32), 0.75, f64::from(0.8_f32)); + let moved = m.previous.subtract(m.position); + if w.prop(x, y, z, "age") != Some("0") + && moved.horizontal_distance_squared() > 0.0 + && (moved.x.abs() >= f64::from(0.003_f32) + || moved.z.abs() >= f64::from(0.003_f32)) + { + m.damage(1.0, Damage::of(DamageKind::Cactus)); + } + } + _ => continue, + } + visited.push(p); + } + } + } + } +} /// LivingEntity.updateSwingTime (6-tick swing duration). pub fn tick_swing(m: &mut Mob) { if m.ai.swinging { diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..7dfbf7017 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -370,7 +370,14 @@ impl Mob { /// Entity.move with block collisions and step-up; updates collision flags /// and fall distance (Entity.checkFallDamage). pub fn do_move(&mut self, w: &MobWorld, events: &mut Vec) { - let wanted = self.velocity; + let mut wanted = self.velocity; + // Entity.move: a block the mob is stuck in (sweet berry bush) scales + // this move once and stops it. + if self.stuck_multiplier.length_squared() > 1.0e-7 { + wanted = wanted.multiply(self.stuck_multiplier); + self.stuck_multiplier = Vec3::ZERO; + self.velocity = Vec3::ZERO; + } let step = self.kind.step_height as f32; let mut scene = SceneCollisions { world: w.world, From 472da6509dca7ebb9c4084d45ec40f96570e1d63 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:45:57 +0100 Subject: [PATCH 022/221] Projectiles ring bells they hit --- crates/horizon-client/src/game/creatures.rs | 25 +++++++++++++++- crates/horizon-world/src/level/interact.rs | 19 ++---------- crates/horizon-world/src/level/mod.rs | 16 +++++++++++ crates/horizon-world/src/level/redstone.rs | 32 +++++++++++++++++++-- 4 files changed, 73 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..f82962d21 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -20,7 +20,7 @@ use horizon_client::{ projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}, }; use horizon_core::{ - geometry::{Aabb, Vec3, traverse_blocks}, + geometry::{Aabb, Direction, Vec3, traverse_blocks}, position::BlockPos, random::RandomSource, }; @@ -1877,6 +1877,22 @@ impl Game<'_> { None => self.projectile_hit(p, hit), } } + /// `BellBlock.onProjectileHit`: a projectile that strikes the bell proper + /// rings it, and a player's shot counts as the player's ring. + fn bell_projectile_hit(&mut self, p: &Projectile, pos: [i32; 3], at: Vec3, face: [i32; 3]) { + let Some(face) = Direction::ALL.into_iter().find(|d| d.normal() == face) else { + return; + }; + let block = BlockPos::new(pos[0], pos[1], pos[2]); + let rang = self + .with_level(|b, level, ticks| b.bell_projectile_hit(level, ticks, block, face, at.y)); + if rang { + let _ = self.process_level_events(); + if p.owner == Some(Who::Player) { + self.stats.custom("bell_ring", 1); + } + } + } /// What an arrow's tick asked for: its particles and sounds. fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) { use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction}; @@ -2002,6 +2018,13 @@ impl Game<'_> { } } pub(super) fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> { + // Projectile.onHitBlock: BlockState.onProjectileHit, for every + // projectile (a wind charge out of the world's top has no face). + if let Hit::Block { pos, at, face } = hit + && face != [0; 3] + { + self.bell_projectile_hit(p, pos, at, face); + } self.combat.projectile_owner = match p.owner { Some(Who::Mob(id)) => Some(id), _ => None, diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 7b2195c34..18d131740 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -1,11 +1,9 @@ //! `BlockBehaviour.useWithoutItem` (right-click with an empty hand or an item //! that does not handle the block itself). -use super::{ - Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, query::axis_of, update::below, -}; +use super::{Behaviours, LevelAccess, LevelEvent, Sim, Ticks, classes::Class, update::below}; use crate::registry::BlockStateId; use horizon_core::{ - geometry::{Axis, Direction, Vec3}, + geometry::{Direction, Vec3}, position::BlockPos, random::RandomSource, }; @@ -338,18 +336,7 @@ impl Sim<'_, L> { } } Class::Bell => { - let click_y = hit.y - f64::from(pos.y); - let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && { - let facing_axis = axis_of(b.facing(state)); - match table.text(state, p.attachment) { - "floor" => facing_axis == axis_of(face), - "single_wall" | "double_wall" => facing_axis != axis_of(face), - "ceiling" => true, - _ => false, - } - }; - if proper { - self.bell_ring(pos, state, face); + if self.bell_hit(pos, state, face, hit.y - f64::from(pos.y)) { Success } else { Pass diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index a384b38b7..b16315279 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -768,6 +768,22 @@ impl Behaviours { self.sim(level, ticks) .big_dripleaf_entity_inside(pos, on_ground, feet_y); } + /// `BellBlock.onProjectileHit` for a projectile that hit `face` of the + /// block at `pos` at height `hit_y`. False when the block is not a bell + /// or the hit missed the bell proper. + pub fn bell_projectile_hit( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Direction, + hit_y: f64, + ) -> bool { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + self.data(state).is(classes::Class::Bell) + && sim.bell_hit(pos, state, face, hit_y - f64::from(pos.y)) + } /// Redstone signal queries (`SignalGetter`). pub fn has_neighbor_signal( &self, diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 92f9059e5..acbd4aaee 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -5,13 +5,16 @@ use super::{ LevelAccess, LevelEvent, Sim, classes::Class, data::state_flags, - query::{clockwise, counter_clockwise}, + query::{axis_of, clockwise, counter_clockwise}, states::BlockId, update::{HORIZONTAL, above, below, rel}, }; use crate::registry::BlockStateId; use horizon_core::{ - geometry::Direction, position::BlockPos, random::RandomSource, ticks::TickPriority, + geometry::{Axis, Direction}, + position::BlockPos, + random::RandomSource, + ticks::TickPriority, }; const SIGNAL_ORDER: [Direction; 6] = [ @@ -1159,6 +1162,31 @@ impl Sim<'_, L> { self.set_block_and_update(pos, b.table.set_bool(state, b.props.powered, signal)); } } + /// `BellBlock.onHit` with `requireHitFromCorrectSide`: a hit on `face` at + /// height `click_y` in the block rings the bell only when it struck the + /// bell proper. False when the hit missed it. + pub(crate) fn bell_hit( + &mut self, + pos: BlockPos, + state: BlockStateId, + face: Direction, + click_y: f64, + ) -> bool { + let b = self.b; + let facing_axis = axis_of(b.facing(state)); + let proper = axis_of(face) != Axis::Y + && click_y <= f64::from(0.8124f32) + && match b.table.text(state, b.props.attachment) { + "floor" => facing_axis == axis_of(face), + "single_wall" | "double_wall" => facing_axis != axis_of(face), + "ceiling" => true, + _ => false, + }; + if proper { + self.bell_ring(pos, state, face); + } + proper + } /// `BellBlock.attemptToRing`: `BellBlockEntity.onHit` queues block event 1 /// with the struck direction, then the sound and game event. pub(crate) fn bell_ring(&mut self, pos: BlockPos, state: BlockStateId, direction: Direction) { From 45996d8d78222564644f18832b1f31723f76cd3e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:48:10 +0100 Subject: [PATCH 023/221] Match the farmer's requested items to vanilla The farmer's list had food, torchflower seeds and pitcher pods and lacked bone meal. Vanilla requests wheat, wheat seeds, beetroot seeds and bone meal. Food is already picked up and traded through its villager food value. --- crates/horizon-client/src/mobs/villager.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index 148034323..430f2aeee 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -353,18 +353,14 @@ pub fn food_points(item: &str) -> i32 { _ => 0, } } -/// The farmer's `requestedItems`. +/// The farmer's `requestedItems` (`VillagerProfession.FARMER`). Food is picked +/// up and traded separately, through its villager food value. pub fn farmer_items() -> &'static [&'static str] { &[ - "minecraft:bread", - "minecraft:potato", - "minecraft:carrot", "minecraft:wheat", "minecraft:wheat_seeds", - "minecraft:beetroot", "minecraft:beetroot_seeds", - "minecraft:torchflower_seeds", - "minecraft:pitcher_pod", + "minecraft:bone_meal", ] } /// A villager's `requestedItems` by profession. From f2424043f38ccd1f68661456e03c8c1885eb07d2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:49:12 +0100 Subject: [PATCH 024/221] Stop zombie drowning conversion when it leaves the water --- crates/horizon-client/src/mobs/undead.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index e77a37641..a32257b35 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -486,7 +486,12 @@ pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { return zombified_piglin_step(m, cx); } if matches!(m.species(), Species::Zombie | Species::Husk) && m.alive() { - if m.extra.counter2 > 0 { + if m.extra.counter2 > 0 && !m.fluids.eye_in_water { + // ConversionTracker.tick: leaving the water ends a started + // conversion too. + m.extra.counter = -1; + m.extra.counter2 = 0; + } else if m.extra.counter2 > 0 { m.extra.counter2 -= 1; if m.extra.counter2 == 0 { let (kind, sound) = if m.species() == Species::Husk { From e4cd56ed7b44cbe5af3835a4f3ba9730c96ad051 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:49:17 +0100 Subject: [PATCH 025/221] Make Frost Walker freeze water and protect from magma --- crates/horizon-client/src/game.rs | 7 + .../src/game/enchant_effects.rs | 212 +++++++++++++++++- crates/horizon-client/src/game/lan_actions.rs | 5 + crates/horizon-client/src/motion.rs | 3 + .../horizon-client/src/motion/environment.rs | 6 + 5 files changed, 230 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ddb07912a..9b585e611 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1952,6 +1952,7 @@ impl Game<'_> { .as_ref() .is_some_and(|s| &*s.item == "minecraft:leather_boots"); let freeze_immune = self.wears_freeze_immune(); + let burn_immune = self.wears_burn_from_stepping_immunity(); let Some(player) = self.player.as_mut() else { return; }; @@ -1963,6 +1964,7 @@ impl Game<'_> { player.glider = glider; player.leather_boots = leather_boots; player.freeze_immune = freeze_immune; + player.burn_from_stepping_immune = burn_immune; player.fluids.fast_lava = self.dim == Dim::Nether; } fn held_slot(&self) -> usize { @@ -4518,6 +4520,11 @@ impl Game<'_> { } } self.powder_snow_fire()?; + // LivingEntity.baseTick: a new block position runs the worn + // enchantments' location_changed effects (frost walker) on the server. + if self.remote.is_none() { + self.location_changed_effects(before.2, before.0); + } self.tick_totem(); let Some(player) = self.player.as_mut() else { return Ok(()); diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 7cdb3e526..50b10beb1 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -3,10 +3,17 @@ //! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power //! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), //! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and -//! the armor attribute effects (respiration, depth strider, ...). +//! the armor attribute effects (respiration, depth strider, ...) and the +//! `minecraft:location_changed` disk effect (frost walker). use super::Game; -use horizon_client::{enchant::EffectContext, items::ItemStack}; -use horizon_core::random::RandomSource; +use horizon_client::{ + enchant::{EffectContext, level_value}, + items::ItemStack, + mobs::Who, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_world::{fluid::FluidKind, level::LevelAccess, registry::BlockStateId}; +use serde_json::Value; /// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`). #[derive(Clone, Copy)] @@ -456,6 +463,173 @@ impl Game<'_> { } ignite } + /// `EnchantmentHelper.runLocationChangedEffects` for the worn armor of the + /// player, run on the server once the player has moved: `LivingEntity.baseTick` + /// runs it when the block position changed, `checkFallDamage` when it lands. + /// `from` and `was_on_ground` are where and how the tick began. + pub(super) fn location_changed_effects(&mut self, from: [f64; 3], was_on_ground: bool) { + let Some(p) = self.player.as_ref() else { + return; + }; + let at = [p.position.x, p.position.y, p.position.z]; + let on_ground = p.ground.on_ground; + let cell = |v: [f64; 3]| v.map(|c| c.floor() as i32); + if cell(from) == cell(at) && !(on_ground && !was_on_ground) { + return; + } + let riding = self.riding.is_some(); + let mut disks = Vec::new(); + for (stack, slot) in self.armor.iter().zip(["head", "chest", "legs", "feet"]) { + let Some(stack) = stack else { continue }; + for (id, level) in stack.enchantments() { + let Some(def) = self.res.stations().enchantments.get(id) else { + continue; + }; + if !def + .slots + .iter() + .any(|s| s == slot || s == "armor" || s == "any") + { + continue; + } + for effect in def.effects["minecraft:location_changed"] + .as_array() + .into_iter() + .flatten() + { + if effect["effect"]["type"] == "minecraft:replace_disk" + && location_requirements(&effect["requirements"], on_ground, riding) + { + disks.push((effect["effect"].clone(), *level)); + } + } + } + } + for (effect, level) in disks { + self.replace_disk(&effect, level, at); + } + } + /// `ReplaceDisk.apply`: the blocks of the disk around `at` that pass the + /// predicate become the effect's state, and each placement is a game event. + fn replace_disk(&mut self, effect: &Value, level: u32, at: [f64; 3]) { + let registry = self.pack.assets.registry; + let spec = &effect["block_state"]; + let Some(default) = spec["id"].as_str().and_then(|n| registry.default_state(n)) else { + return; + }; + let Some(mut state) = registry.state(default).cloned() else { + return; + }; + for (k, v) in spec["properties"].as_object().into_iter().flatten() { + state + .properties + .insert(k.clone(), v.as_str().unwrap_or("").to_owned()); + } + let new = registry.resolve(&state).unwrap_or(default); + let radius = level_value(&effect["radius"], level) as i32; + let height = level_value(&effect["height"], level) as i32; + let offset = cell_offset(effect); + let center = [0, 1, 2].map(|i| at[i].floor() as i32 + offset[i]); + let event = effect["trigger_game_event"].as_str() == Some("minecraft:block_place"); + for dy in (height - 1).min(0)..=0 { + for dz in -radius..=radius { + for dx in -radius..=radius { + let pos = [center[0] + dx, center[1] + dy, center[2] + dz]; + let (x, z) = ( + f64::from(pos[0]) + 0.5 - at[0], + f64::from(pos[2]) + 0.5 - at[2], + ); + if x * x + z * z >= f64::from(radius * radius) + || !self.disk_predicate(&effect["predicate"], pos, new) + || self.level_set(pos, new).is_err() + { + continue; + } + if event { + self.post_block_game_event( + "minecraft:block_place", + pos, + Some(Who::Player), + Some(new), + ); + } + } + } + } + } + /// The `BlockPredicate` subset the disk effect uses, tested at `pos`; no + /// predicate matches everything. + fn disk_predicate(&mut self, p: &Value, pos: [i32; 3], placed: BlockStateId) -> bool { + if p.is_null() { + return true; + } + let offset = cell_offset(p); + let at = [0, 1, 2].map(|i| pos[i] + offset[i]); + let state = self.world.block(at[0], at[1], at[2]); + let b = self.res.behaviours(); + let names = |v: &Value| -> Vec { + match v { + Value::String(s) => vec![s.clone()], + Value::Array(a) => a + .iter() + .filter_map(|n| n.as_str().map(String::from)) + .collect(), + _ => Vec::new(), + } + }; + match p["type"].as_str().unwrap_or("") { + "minecraft:all_of" => p["predicates"] + .as_array() + .into_iter() + .flatten() + .all(|q| self.disk_predicate(q, pos, placed)), + // `MatchingBlockTagPredicate` + "minecraft:matching_block_tag" => b + .tag(p["tag"].as_str().unwrap_or("").trim_start_matches('#')) + .is_some_and(|t| t.contains(b.block(state))), + // `MatchingBlocksPredicate` + "minecraft:matching_blocks" => { + names(&p["blocks"]).iter().any(|n| n == b.table.name(state)) + } + // `MatchingFluidsPredicate`: Fluids.WATER is the source. + "minecraft:matching_fluids" => { + let fluid = b.fluid(state); + names(&p["fluids"]).iter().any(|n| match n.as_str() { + "minecraft:water" => fluid.kind() == FluidKind::Water && fluid.is_source(), + "minecraft:flowing_water" => { + fluid.kind() == FluidKind::Water && !fluid.is_source() + } + _ => false, + }) + } + // `UnobstructedPredicate`: no building-blocking entity in the block. + "minecraft:unobstructed" => self.with_level(|_, level, _| { + level.is_unobstructed(BlockPos::new(pos[0], pos[1], pos[2]), placed) + }), + _ => false, + } + } + /// Whether a worn enchantment gives immunity to `#burn_from_stepping` + /// damage (frost walker's `minecraft:damage_immunity`). + pub(crate) fn wears_burn_from_stepping_immunity(&self) -> bool { + self.armor + .iter() + .zip(["head", "chest", "legs", "feet"]) + .any(|(stack, slot)| { + stack + .iter() + .flat_map(ItemStack::enchantments) + .any(|(id, _)| { + self.res.stations().enchantments.get(id).is_some_and(|def| { + def.effects.get("minecraft:damage_immunity").is_some() + && def + .slots + .iter() + .any(|s| s == slot || s == "armor" || s == "any") + }) + }) + }) + } /// Enchantment attribute modifiers of worn armor (respiration, depth strider...). /// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`), /// so the same enchantment on two pieces stacks instead of replacing itself. @@ -479,3 +653,35 @@ impl Game<'_> { self.potions.enchant_modifiers = wanted; } } + +/// An effect's or predicate's `offset` vector (zero when absent). +fn cell_offset(v: &Value) -> [i32; 3] { + let at = |i: usize| { + v["offset"] + .get(i) + .and_then(Value::as_i64) + .map_or(0, |n| n as i32) + }; + [at(0), at(1), at(2)] +} +/// The loot-condition subset a `location_changed` effect requires of the +/// wearer: standing on the ground and not riding (frost walker). +fn location_requirements(req: &Value, on_ground: bool, riding: bool) -> bool { + match req["type"].as_str().unwrap_or("") { + "" if req.is_null() => true, + "minecraft:all_of" => req["terms"] + .as_array() + .into_iter() + .flatten() + .all(|t| location_requirements(t, on_ground, riding)), + "minecraft:inverted" => !location_requirements(&req["term"], on_ground, riding), + "minecraft:entity_properties" => { + let p = &req["predicate"]; + p["minecraft:flags"]["is_on_ground"] + .as_bool() + .is_none_or(|v| v == on_ground) + && (p["minecraft:vehicle"].is_null() || riding) + } + _ => false, + } +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..64fda0636 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2187,6 +2187,7 @@ impl Game<'_> { let (rules, motion) = (game.world.health_rules, game.motion); let health = &motion.health; let freeze_immune = game.wears_freeze_immune(); + let burn_immune = game.wears_burn_from_stepping_immunity(); let Some(player) = game.player.as_mut() else { return (Vec::new(), None); }; @@ -2251,6 +2252,7 @@ impl Game<'_> { // lit campfires and grown sweet berry bushes hurt (#1305). w.player.shift_key_down = sneaking; w.player.freeze_immune = freeze_immune; + w.player.burn_from_stepping_immune = burn_immune; let _ = w.server_block_damage(start); let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); @@ -2276,6 +2278,9 @@ impl Game<'_> { for d in travelled { game.movement_stats(Vec3::new(d[0], d[1], d[2])); } + // LivingEntity.baseTick: a new block position runs the worn + // enchantments' location_changed effects (frost walker). + game.location_changed_effects([start.x, start.y, start.z], from_ground); // LivingEntity.baseTick: outside the world border, then tickEffects. game.border_damage(); game.tick_mob_effects(); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0bce8927c..b8f2d981d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -302,6 +302,8 @@ pub struct PlayerMotion { pub leather_boots: bool, /// An armor piece in `#freeze_immune_wearables` (`LivingEntity.canFreeze`). pub freeze_immune: bool, + /// A worn enchantment's `damage_immunity` to `#burn_from_stepping` (frost walker). + pub burn_from_stepping_immune: bool, /// `Entity.oldPosition`: where this tick started. pub old_position: Vec3, /// The server's copy of a player another client moves (a LAN guest), while @@ -475,6 +477,7 @@ impl PlayerMotion { ticks_frozen: 0, leather_boots: false, freeze_immune: false, + burn_from_stepping_immune: false, old_position: position, server_copy: false, client_side: false, diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index fc3c63c77..47033d676 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -10,6 +10,12 @@ impl MotionWorld<'_, '_, '_> { if self.player.invulnerable || self.player.spectator { return Ok(()); } + // Frost walker's `damage_immunity`: #burn_from_stepping (magma, campfire). + if self.player.burn_from_stepping_immune + && matches!(source, "minecraft:hot_floor" | "minecraft:campfire") + { + return Ok(()); + } let id = self .resources .health From 9d4c984e03154fcc86e3cb1593477e921a76ba06 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:49:31 +0100 Subject: [PATCH 026/221] Speed up an enderman while it has a target --- crates/horizon-client/src/mobs.rs | 4 +++- crates/horizon-client/src/mobs/enderman.rs | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..133000ff0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1847,7 +1847,9 @@ impl Mob { /// Movement speed attribute bonus (baby zombies, sprinting modifiers). /// MOVEMENT_SPEED including effects (speed +20%/level, slowness -15%/level). pub fn movement_speed(&self) -> f64 { - let mut v = strider::movement_speed(self, self.attrs.speed) * self.speed_bonus(); + let mut v = + strider::movement_speed(self, self.attrs.speed + enderman::attacking_speed(self)) + * self.speed_bonus(); for (e, _, amp) in &self.extra.effects { match *e { "minecraft:speed" => v *= 1.0 + 0.2 * f64::from(amp + 1), diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index c5ed01680..06f5cd3f3 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -138,6 +138,15 @@ fn teleport_towards( let z = m.position.z + (m.random.next_double() - 0.5) * 8.0 - d[2] * 16.0; teleport_to(m, w, x, y, z, events) } +/// `Enderman.SPEED_MODIFIER_ATTACKING`, an ADD_VALUE modifier `setTarget` +/// adds while the enderman has a target. +pub fn attacking_speed(m: &Mob) -> f64 { + if m.species() == Species::Enderman && m.ai.target.is_some() { + f64::from(0.15f32) + } else { + 0.0 + } +} /// Enderman.customServerAiStep: in daylight, flee by teleporting. The End has a /// fixed time, so `Level.isBrightOutside` is never true there. pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { From 0d02a4c722741e9da538f934d3c8913f64d0ed6a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:50:04 +0100 Subject: [PATCH 027/221] Let a caught fish be picked up right away --- crates/horizon-client/src/game/fishing.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 22cb3774b..2d3d94650 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -219,7 +219,7 @@ impl Game<'_> { item, [hook.position.x, hook.position.y, hook.position.z], v, - 10, + 0, ); let xp = self.world.random.next_int_bound(6).unwrap_or(0) as u32 + 1; self.spawn_orbs([owner.x, owner.y + 0.5, owner.z + 0.5], xp); From fe8565b8740eb6b1282a390a9e6ee4a8d8caf9d4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:50:05 +0100 Subject: [PATCH 028/221] Scale cave spider poison and husk hunger with the difficulty --- crates/horizon-client/src/mobs/ai.rs | 31 ++++++++++++++-------- crates/horizon-client/src/mobs/spawning.rs | 4 +++ 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..2e950079a 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1359,17 +1359,26 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); match m.species() { - // Difficulty NORMAL: cave spiders poison for 7 seconds. - Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:poison", - ticks: 7 * 20, - amplifier: 0, - }), - Species::Husk if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { - effect: "minecraft:hunger", - ticks: 140, - amplifier: 0, - }), + // CaveSpider.doHurtTarget: poison for 7 s on normal, 15 s on hard. + Species::CaveSpider if who == Who::Player && cx.w.difficulty.base >= 2 => { + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:poison", + ticks: if cx.w.difficulty.base == 2 { 7 } else { 15 } * 20, + amplifier: 0, + }) + } + // Husk.doHurtTarget: hunger for 140 ticks per whole point of the + // local difficulty, only with an empty main hand. + Species::Husk if who == Who::Player && m.extra.main_hand.is_none() => { + let ticks = 140 * cx.w.difficulty.effective as i32; + if ticks > 0 { + cx.events.push(MobEvent::EffectPlayer { + effect: "minecraft:hunger", + ticks, + amplifier: 0, + }) + } + } Species::WitherSkeleton if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { effect: "minecraft:wither", ticks: 200, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..46ac6f0ee 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -34,6 +34,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { + /// The world difficulty id, 0 peaceful to 3 hard. + pub base: u8, pub effective: f32, /// The world difficulty is hard. pub hard: bool, @@ -47,6 +49,7 @@ impl LocalDifficulty { let hard = base == 3; if base == 0 { return Self { + base, effective: 0.0, hard, }; @@ -59,6 +62,7 @@ impl LocalDifficulty { local *= 0.5; } Self { + base, effective: f32::from(base) * (0.75 + global + local), hard, } From fe167781c452bee1ee08b74ee58fcd724c87e2ab Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:50:36 +0100 Subject: [PATCH 029/221] Give the fishing rain bonus only where rain falls --- crates/horizon-client/src/game/fishing.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 22cb3774b..e652c92e7 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -14,6 +14,7 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3, trig}, + position::BlockPos, random::RandomSource, }; use horizon_protocol::entity_data::{Value, serializer}; @@ -301,9 +302,12 @@ impl Game<'_> { let mut speed = 1; let above = [b[0], b[1] + 1, b[2]]; let sky = self.world.light(above[0], above[1], above[2]) >> 4 == 15; - let raining = self.world.weather.raining; - let r = &mut self.world.random; - if r.next_float() < 0.25 && raining && sky { + // Level.isRainingAt: rain (not snow) reaches the position. + if self.world.random.next_float() < 0.25 + && self.with_level(|b, level, _| { + b.is_raining_at(level, BlockPos::new(above[0], above[1], above[2])) + }) + { speed += 1; } let r = &mut self.world.random; From 4c8ff0296988236ff4b33e83b082a4892228a794 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:51:03 +0100 Subject: [PATCH 030/221] Make skeleton arrow spread and damage follow the difficulty --- crates/horizon-client/src/mobs/spawning.rs | 4 ++++ crates/horizon-client/src/mobs/undead.rs | 5 +++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..5d8a928f8 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -34,6 +34,8 @@ pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> b /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] pub struct LocalDifficulty { + /// `Difficulty.getId`: 0 peaceful to 3 hard. + pub id: u8, pub effective: f32, /// The world difficulty is hard. pub hard: bool, @@ -47,6 +49,7 @@ impl LocalDifficulty { let hard = base == 3; if base == 0 { return Self { + id: base, effective: 0.0, hard, }; @@ -59,6 +62,7 @@ impl LocalDifficulty { local *= 0.5; } Self { + id: base, effective: f32::from(base) * (0.75 + global + local), hard, } diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index e77a37641..1fcea9c12 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -743,8 +743,9 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { let zd = t.position.z - m.position.z; let dist = (xd * xd + zd * zd).sqrt(); // AbstractArrow.setBaseDamageFromMob: power * 2 + triangle(difficulty * 0.11, 0.57425). + let id = i32::from(cx.w.difficulty.id); let mut arrow_random = crate::projectiles::own_random(m); - let base = f64::from(power) * 2.0 + arrow_random.triangle(2.0 * 0.11, 0.574_25); + let base = f64::from(power) * 2.0 + arrow_random.triangle(f64::from(id) * 0.11, 0.574_25); let effect = match m.species() { Species::Stray => Some(("minecraft:slowness", 600)), Species::Bogged => Some(("minecraft:poison", 100)), @@ -765,7 +766,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) { &mut arrow_random, [xd, yd + dist * 0.2, zd], 1.6, - (14 - 2 * 4) as f32, + (14 - id * 4) as f32, ); cx.events.push(MobEvent::Projectile(p)); let pitch = 1.0 / (m.random.next_float() * 0.4 + 0.8); From 708702917c35ecfab2c3cd35de15cfc71ada76be Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:51:16 +0100 Subject: [PATCH 031/221] Remove an endermite after 2400 ticks --- crates/horizon-client/src/entity_nbt.rs | 6 ++++++ crates/horizon-client/src/mobs/ai.rs | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..3e22145fb 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -458,6 +458,9 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("life_ticks".into(), Tag::Int(m.extra.egg_time)); } } + "minecraft:endermite" => { + map.insert("Lifetime".into(), Tag::Int(m.extra.counter)); + } "minecraft:shulker" => { map.insert("AttachFace".into(), Tag::Byte(m.extra.variant3 as i8)); map.insert("Peek".into(), Tag::Byte(m.extra.counter as i8)); @@ -881,6 +884,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; m.extra.anim_ticks = number(tag.get("RoarTick")).unwrap_or(0) as i32; } + if m.species() == crate::mobs::Species::Endermite { + m.extra.counter = number(tag.get("Lifetime")).unwrap_or(0) as i32; + } if m.species() == crate::mobs::Species::Vex { if let Some(Tag::IntArray(v)) = tag.get("bound_pos") && v.len() == 3 diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..560afe08c 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -961,6 +961,16 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } match m.species() { Species::Enderman => super::enderman::ai_step(m, w, events), + // Endermite.aiStep: `counter` is the life; an endermite not required + // to persist is discarded at 2400. + Species::Endermite => { + if !m.persistent { + m.extra.counter += 1; + } + if m.extra.counter >= 2400 { + m.removed = true; + } + } Species::Wolf => super::tame::ai_step(m, w, events), Species::Cat => super::tame::cat_ai_step(m, events), Species::Blaze => super::nether::blaze_ai_step(m, events), From 5657080884bdbe591797f010571c491fb03d7608 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:51:45 +0100 Subject: [PATCH 032/221] Swell a creeper's fuse when it falls --- crates/horizon-client/src/mobs/living.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..59c2ca9a9 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -625,6 +625,11 @@ impl Mob { let at = [self.position.x, self.position.y, self.position.z]; events.push(MobEvent::Sound("entity.breeze.land", at, 1.0, 1.0)); } + // Creeper.causeFallDamage: the fall swells the fuse, up to five ticks + // short of exploding. + if self.species() == super::Species::Creeper { + self.swell = (self.swell + (self.fall_distance * 1.5) as i32).min(30 - 5); + } if self.kind.flags.fall_immune { return; } From 4084bcdf753c4e1c517ea1667b632016cfc7b110 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:54:11 +0100 Subject: [PATCH 033/221] Let a brush dust suspicious sand and gravel --- crates/horizon-client/src/game.rs | 25 ++ crates/horizon-client/src/game/brush.rs | 246 ++++++++++++++++++++ crates/horizon-client/src/game/item_draw.rs | 5 +- crates/horizon-client/src/game/lan.rs | 5 +- crates/horizon-client/src/game/remote.rs | 33 +++ crates/horizon-world/src/level/mod.rs | 3 +- crates/horizon-world/src/level/tick.rs | 7 + 7 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/game/brush.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 64d5b2766..b20de6ea8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -18,6 +18,7 @@ mod boats; mod books; mod bossbars; mod breezes; +mod brush; mod campfire; mod campfire_douse; mod cartography; @@ -1653,6 +1654,8 @@ struct Game<'a> { boss_overlay: horizon_client::boss_overlay::BossOverlay, exec: commands::execute::ExecState, rand_sequences: horizon_client::random_sequences::RandomSequences, + /// `BrushableBlockEntity`'s brush counts of the blocks being brushed. + brushing: brush::Brushing, border: horizon_client::worldborder::WorldBorder, /// `WorldBorderRenderer` and its render state. border_renderer: horizon_client::border_render::BorderRenderer, @@ -2796,6 +2799,11 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + LevelEvent::LevelEvent { + id: 3008, + pos, + data, + } => self.brush_complete_event([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } @@ -2972,6 +2980,11 @@ impl Game<'_> { kind: "command_block", .. } => self.command_block_tick(pos), + LevelEvent::BlockEvent { + pos, + kind: "brushable", + .. + } => self.brushable_tick([pos.x, pos.y, pos.z]), LevelEvent::BlockEvent { pos, kind: "hatch", .. } => { @@ -3674,6 +3687,13 @@ impl Game<'_> { { return Ok(true); } + // BrushItem.useOn: brushing starts on the block aimed at (CONSUME). + if block_hit.is_some() && &*stack.item == "minecraft:brush" { + if self.using.is_none() { + self.using = Some((self.held_slot(), 0)); + } + return Ok(true); + } if !on_block && (self.raise_shield(self.held_slot()) || self.use_fishing_rod(&stack) @@ -3962,6 +3982,10 @@ impl Game<'_> { } return; } + if &*stack.item == "minecraft:brush" { + self.tick_brush(slot, ticks); + return; + } let Some(consumable) = info.consumable.as_ref() else { self.using = None; return; @@ -12540,6 +12564,7 @@ impl<'a> Game<'a> { boss_overlay: Default::default(), exec: Default::default(), rand_sequences: Default::default(), + brushing: Default::default(), border: Default::default(), border_renderer: Default::default(), border_state: Default::default(), diff --git a/crates/horizon-client/src/game/brush.rs b/crates/horizon-client/src/game/brush.rs new file mode 100644 index 000000000..c064a3153 --- /dev/null +++ b/crates/horizon-client/src/game/brush.rs @@ -0,0 +1,246 @@ +//! Brushing suspicious sand and gravel: `BrushItem.onUseTick` and +//! `BrushableBlockEntity`. The block's loot table stays in its saved block +//! entity (like a decorated pot's) until the first counted stroke rolls it. +use super::{Game, Hit, decorated_pot, spill, view_vector}; +use horizon_client::{ + particles::{ParticleOptions, ParticleType}, + save, +}; +use horizon_core::random::RandomSource; +use std::collections::HashMap; + +/// `BrushItem.USE_DURATION`. +const USE_DURATION: u32 = 200; + +/// A brushable block's counters. Vanilla never saves them: the block's +/// `dusted` state is all that is left after a reload. +#[derive(Default)] +pub(super) struct BrushState { + count: i32, + resets_at: i64, + cooldown_ends_at: i64, + hit_face: Option<[i32; 3]>, +} + +/// `BrushableBlockEntity.getCompletionState`: the `dusted` property. +fn completion_state(count: i32) -> i32 { + match count { + 0 => 0, + 1..=2 => 1, + 3..=5 => 2, + _ => 3, + } +} + +pub(super) type Brushing = HashMap<[i32; 3], BrushState>; + +impl Game<'_> { + /// `BrushItem.onUseTick` for a brush used `ticks` ticks so far, the + /// hand of `slot` acting. + pub(super) fn tick_brush(&mut self, slot: usize, ticks: u32) { + // No block under the crosshair: releaseUsingItem. + let Some(hit) = self.pick() else { + self.using = None; + return; + }; + let elapsed = ticks + 1; + // The last tick before the backswing. + if elapsed % 10 == 5 { + self.brush_stroke(&hit, slot); + } + // The use ends after 200 ticks; the held button starts it again. + self.using = (elapsed < USE_DURATION).then_some((slot, elapsed)); + } + + /// One stroke on the block aimed at: dust (this window only), the brush + /// sound, and the block entity's count. The brush wears when the block + /// changed state. + fn brush_stroke(&mut self, hit: &Hit, slot: usize) { + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let name = self.res.facts().get(state).name.clone(); + let (sound, brushable) = match &*name { + "minecraft:suspicious_sand" => ("minecraft:item.brush.brushing.sand", true), + "minecraft:suspicious_gravel" => ("minecraft:item.brush.brushing.gravel", true), + _ => ("minecraft:item.brush.brushing.generic", false), + }; + if self.lan_acting.is_none() { + self.brush_dust(hit, slot == super::shield::OFFHAND_SLOT); + } + let at = hit.pos.map(|v| f64::from(v) + 0.5); + self.audio.play(sound, Some(at), 1.0, 1.0); + if brushable && self.brush_block(hit.pos, hit.face) { + self.damage_held(1); + } + } + + /// `BrushItem.spawnDustParticles`. + pub(super) fn brush_dust(&mut self, hit: &Hit, off_hand: bool) { + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let Some((sprite, tint)) = self.particle_sprite(state, hit.pos) else { + return; + }; + let options = ParticleOptions::block(ParticleType::Block, sprite, tint); + // The arm that brushes: the main arm, or the other one for the off hand. + let flip = if off_hand == self.settings.main_hand_left { + 1.0 + } else { + -1.0 + }; + let view = view_vector(self.yaw, self.pitch); + // DustParticlesDelta.fromDirection. + let (dx, dz) = match hit.face { + [0, _, 0] => (view[2], -view[0]), + [0, 0, -1] => (1.0, -0.1), + [0, 0, 1] => (-1.0, 0.1), + [-1, 0, 0] => (-0.1, -1.0), + _ => (0.1, 1.0), + }; + let count = 7 + self.particles.level_random().next_int_bound(5).unwrap_or(0); + let x = hit.point[0] - if hit.face == [-1, 0, 0] { 1.0e-6 } else { 0.0 }; + let z = hit.point[2] - if hit.face == [0, 0, -1] { 1.0e-6 } else { 0.0 }; + for _ in 0..count { + let random = self.particles.level_random(); + let v = [ + dx * flip * 3.0 * random.next_double(), + 0.0, + dz * flip * 3.0 * random.next_double(), + ]; + self.particles.add(&options, [x, hit.point[1], z], v); + } + } + + /// `BrushableBlockEntity.brush`: whether the block changed (the brush wears). + fn brush_block(&mut self, pos: [i32; 3], face: [i32; 3]) -> bool { + let time = self.world.game_time; + let mut brush = self.brushing.remove(&pos).unwrap_or_default(); + brush.hit_face.get_or_insert(face); + brush.resets_at = time + 40; + if time < brush.cooldown_ends_at { + self.brushing.insert(pos, brush); + return false; + } + brush.cooldown_ends_at = time + 10; + self.unpack_brush_loot(pos); + let before = completion_state(brush.count); + brush.count += 1; + if brush.count >= 10 { + self.brushing_completed(pos, brush.hit_face); + return true; + } + self.schedule_brushable_tick(pos); + let after = completion_state(brush.count); + self.brushing.insert(pos, brush); + if before != after { + self.set_dusted(pos, after); + } + false + } + + /// `BrushableBlockEntity.unpackLootTable`: the table's roll becomes the + /// block entity's item. + fn unpack_brush_loot(&mut self, pos: [i32; 3]) { + let Some(mut tag) = spill::saved_entity(&self.world, pos) else { + return; + }; + if tag.get("LootTable").is_none() { + return; + } + let loot = horizon_client::structure_blocks::loot_data(&self.options.resources); + decorated_pot::unpack_loot( + &mut tag, + loot.as_deref(), + &mut self.world.random, + &mut self.rand_sequences, + self.level.seed, + ); + spill::put_saved_entity(&mut self.world, pos, tag); + } + + /// `BrushableBlockEntity.brushingCompleted`: the item drops out of the + /// brushed face and the block turns into its sand or gravel. + fn brushing_completed(&mut self, pos: [i32; 3], face: Option<[i32; 3]>) { + let state = self.world.block(pos[0], pos[1], pos[2]); + let turns_into = match &*self.res.facts().get(state).name { + "minecraft:suspicious_sand" => "minecraft:sand", + "minecraft:suspicious_gravel" => "minecraft:gravel", + _ => "minecraft:air", + }; + // dropContent: the item at the middle of the block beside that face. + let item = spill::saved_entity(&self.world, pos) + .and_then(|tag| tag.get("item").and_then(save::item_from_nbt)); + if let Some(mut item) = item { + let face = face.unwrap_or([0, 1, 0]); + let take = 10 + self.world.random.next_int_bound(21).unwrap_or(0); + item.count = item.count.min(take as u32); + let at = [ + f64::from(pos[0] + face[0]) + 0.5, + f64::from(pos[1] + face[1]) + 0.625, + f64::from(pos[2] + face[2]) + 0.5, + ]; + self.spawn_item(item, at, [0.0; 3], 0); + } + // Level event 3008 for every player, then the block change. + self.level_event_at(3008, pos, state.0 as i32); + if let Some(base) = self.pack.assets.registry.default_state(turns_into) { + let _ = self.level_set(pos, base); + } + } + + fn set_dusted(&mut self, pos: [i32; 3], dusted: i32) { + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .cloned() + else { + return; + }; + state.properties.insert("dusted".into(), dusted.to_string()); + if let Ok(state) = registry.resolve(&state) { + let _ = self.level_set(pos, state); + } + } + + fn schedule_brushable_tick(&mut self, pos: [i32; 3]) { + let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.schedule_tick(level, ticks, at, 2)); + } + + /// `BrushableBlockEntity.checkReset`, from `BrushableBlock.tick`: a block + /// left alone loses two counts, again every four ticks. + pub(super) fn brushable_tick(&mut self, pos: [i32; 3]) { + let time = self.world.game_time; + let Some(mut brush) = self.brushing.remove(&pos) else { + return; + }; + let before = completion_state(brush.count); + if brush.count != 0 && time >= brush.resets_at { + brush.count = (brush.count - 2).max(0); + brush.resets_at = time + 4; + } + let after = completion_state(brush.count); + if brush.count != 0 { + self.brushing.insert(pos, brush); + self.schedule_brushable_tick(pos); + } + if before != after { + self.set_dusted(pos, after); + } + } + + /// Level event 3008 (`LevelEventHandler`): the finished block's sound + /// and break particles. + pub(super) fn brush_complete_event(&mut self, pos: [i32; 3], data: i32) { + let state = horizon_world::registry::BlockStateId(data as u32); + let sound = match &*self.res.facts().get(state).name { + "minecraft:suspicious_sand" => "minecraft:item.brush.brushing.sand.complete", + "minecraft:suspicious_gravel" => "minecraft:item.brush.brushing.gravel.complete", + _ => "", + }; + if !sound.is_empty() { + let at = pos.map(|v| f64::from(v) + 0.5); + // Each client plays it from the event itself. + self.audio.play_unshared(sound, Some(at), 1.0, 1.0); + } + self.destroy_particles(pos, state); + } +} diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..8deb483c1 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -179,8 +179,9 @@ fn use_duration(components: &Components) -> i32 { | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" - | "minecraft:goat_horn" - | "minecraft:brush" => 72_000, + | "minecraft:goat_horn" => 72_000, + // BrushItem.USE_DURATION. + "minecraft:brush" => 200, _ => 0, } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..e4c9d19a7 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1187,9 +1187,10 @@ impl Game<'_> { match e { horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { // The acting guest does not predict the egg's teleport - // particles, bone meal's growth, or anvil result sounds + // particles, bone meal's growth, anvil result sounds, or a + // finished brushing // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 3008) { None } else { self.lan_acting diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..5c25fc9b8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4063,6 +4063,15 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + } else if held.as_ref().is_some_and(|s| &*s.item == "minecraft:brush") { + // BrushItem.useOn: brushing starts here (CONSUME, no swing); the + // server brushes and the dust is this client's own. + self.with_hand(hand, |g| { + if g.using.is_none() { + g.using = Some((g.held_slot(), 0)); + } + }); + return true; } else if let Some(stack) = held.as_ref() && self.predict_item_on_block(stack, &hit) { @@ -4383,6 +4392,30 @@ impl Game<'_> { // Another hotbar slot picked: LivingEntity.updatingUsingItem sees a // different stack in the hand. The off hand keeps its item. let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT; + // BrushItem.onUseTick: with no block aimed the use ends (the server + // ends it too); a stroke shows its dust. Its sounds are the server's. + if stack + .as_ref() + .is_some_and(|s| &*s.item == "minecraft:brush") + { + let elapsed = ticks + 1; + let hit = self.pick().filter(|_| in_hand); + if let Some(hit) = &hit + && elapsed % 10 == 5 + { + self.brush_dust(hit, slot == super::shield::OFFHAND_SLOT); + } + if hit.is_none() && in_hand { + self.send(S::PlayerAction(play::PlayerAction { + action: 6, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + } + self.using = hit.and(Some((slot, elapsed))).filter(|_| elapsed < 200); + return; + } // A drawn bow, a charging crossbow, a raised shield...: held until // the button lets go. if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index a384b38b7..d9c63a493 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -252,7 +252,8 @@ pub enum LevelEvent { /// event follow as their own events; the caller removes the block. PrimeTnt { pos: BlockPos, rot: f64 }, /// Block-entity or entity side effects the caller implements: `"dispense"` - /// (dispenser/dropper/crafter scheduled tick), `"hatch"` (frogspawn + /// (dispenser/dropper/crafter scheduled tick), `"brushable"` (a suspicious + /// block's scheduled tick: `checkReset`), `"hatch"` (frogspawn /// hatched into tadpoles; the block is already destroyed), `"portal_spawn"` /// (a nether portal won its zombified piglin roll; the caller checks /// `anyPlayerCloseEnoughForSpawning` and spawns below the portal). diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 29f53e053..186f64bd7 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -127,6 +127,13 @@ impl Sim<'_, L> { } Class::FallingBlock => self.falling_block_tick(pos, state), Class::Brushable => { + // BrushableBlock.tick checks the brush reset first (the + // caller keeps the brush counts). + self.emit(LevelEvent::BlockEvent { + pos, + state, + kind: "brushable", + }); if self.is_free(self.below_state(pos)) && pos.y >= self.level.min_y() { self.falling_block_fall(pos, state); } From b92dd805668a9a6a3ab5deee65054fcad0c54407 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:55:02 +0100 Subject: [PATCH 034/221] Let silverfish hide in stone and wake their friends when hurt --- crates/horizon-client/src/game/creatures.rs | 42 +++++ crates/horizon-client/src/game/spawner.rs | 2 +- crates/horizon-client/src/mobs.rs | 8 + crates/horizon-client/src/mobs/ai.rs | 6 +- crates/horizon-client/src/mobs/hostile.rs | 150 +++++++++++++++++- .../src/mobs/spawn_selection.rs | 2 +- 6 files changed, 206 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..6f5937a81 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1065,8 +1065,50 @@ impl Game<'_> { self.world.set(pos[0], pos[1], pos[2], state)?; } } + MobEvent::Infest { + pos, + infested, + poof, + } => { + let registry = &self.pack.assets.registry; + let old = self.world.block(pos[0], pos[1], pos[2]); + if let Some(mut state) = registry.state(old).cloned() { + let (from, to) = if infested { + ("minecraft:", "minecraft:infested_") + } else { + ("minecraft:infested_", "minecraft:") + }; + state.name = state.name.replacen(from, to, 1); + if let Ok(id) = registry.resolve(&state) { + self.world.set(pos[0], pos[1], pos[2], id)?; + } + } + if let Some(mob) = poof { + self.mob_poof(mob); + } + } MobEvent::BreakBlock { pos, drop } => { let old = self.world.block(pos[0], pos[1], pos[2]); + // InfestedBlock.spawnAfterBreak: its silverfish comes out + // when blocks drop. + if drop + && self + .res + .facts() + .get(old) + .name + .starts_with("minecraft:infested_") + && 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); + } + } // Block.spawnDestroyParticles: fire breaks leave nothing. if !self.res.facts().get(old).has_class("BaseFireBlock") { self.destroy_particles(pos, old); 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; }; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..7bf034632 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1009,6 +1009,14 @@ pub enum MobEvent { pos: [i32; 3], open: bool, }, + /// `InfestedBlock.infestedStateByHost` (`infested`) or `hostStateByInfested` + /// for the block there, keeping its axis; `poof` is the silverfish that + /// hid in it (`spawnAnim`). + Infest { + pos: [i32; 3], + infested: bool, + poof: Option, + }, /// Destroy a block, dropping nothing (sheep eating grass becomes dirt via SetBlock). BreakBlock { pos: [i32; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..fe3cdafb3 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -121,7 +121,7 @@ pub fn family(s: Species) -> Family { | S::Parched | S::WitherSkeleton | S::ZombifiedPiglin => Family::Undead, - S::Creeper | S::Spider | S::CaveSpider => Family::Hostile, + S::Creeper | S::Spider | S::CaveSpider | S::Silverfish => Family::Hostile, S::Squid | S::GlowSquid | S::Cod @@ -1306,6 +1306,10 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { super::bee::hurt(m); true } + Species::Silverfish => { + super::hostile::silverfish_hurt(m, source); + true + } Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider if source.is_fire() => diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index 0d3feaa6c..a58e4a909 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -1,7 +1,7 @@ //! Creepers (swelling, explosions) and spiders (wall climbing, daylight //! neutrality, leaping). use super::{ - Mob, MobEvent, MobWorld, Species, Who, + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, goals::{ Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LeapAtTarget, LookAtPlayer, MOVE, MeleeAttack, NearestTarget, RandomLookAround, Stroll, goal_clone, @@ -54,9 +54,157 @@ pub fn register(m: &mut Mob) { ); m.ai.nav.kind = super::nav::NavKind::WallClimber; } + S::Silverfish => { + let g = &mut m.ai.goals; + g.add(1, Float); + g.add(3, SilverfishWakeUpFriends); + g.add(4, MeleeAttack::new(1.0, false)); + g.add(5, SilverfishMergeWithStone::default()); + m.ai.targets.add(1, HurtByTarget::new().alert()); + m.ai.targets.add(2, NearestTarget::player(true)); + } _ => {} } } +/// `Silverfish.hurtServer`: a hit by an entity (or magic damage) starts the +/// countdown of its wake-up goal, kept in `extra.counter`. +pub fn silverfish_hurt(m: &mut Mob, source: &Damage) { + if (source.attacker.is_some() || source.kind == DamageKind::Magic) && m.extra.counter == 0 { + m.extra.counter = super::goals::reduced(20); + } +} +/// `Silverfish.SilverfishWakeUpFriendsGoal`: 20 ticks after being hurt, the +/// infested blocks within 10 blocks sideways and 5 up or down break (or turn +/// back into stone with mob griefing off), until a coin flip stops it. +#[derive(Clone, Debug)] +struct SilverfishWakeUpFriends; +impl Goal for SilverfishWakeUpFriends { + goal_clone!(); + fn name(&self) -> &'static str { + "SilverfishWakeUpFriendsGoal" + } + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.extra.counter > 0 + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.counter -= 1; + if m.extra.counter > 0 { + return; + } + let base = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + // The loops' offsets go 0, 1, -1, 2, -2 and so on. + let offsets = |limit: i32| std::iter::once(0).chain((1..=limit).flat_map(|i| [i, -i])); + for y in offsets(5) { + for x in offsets(10) { + for z in offsets(10) { + let pos = [base[0] + x, base[1] + y, base[2] + z]; + if !cx + .w + .block_name(pos[0], pos[1], pos[2]) + .starts_with("minecraft:infested_") + { + continue; + } + if cx.w.mob_griefing { + cx.events.push(MobEvent::BreakBlock { pos, drop: true }); + } else { + cx.events.push(MobEvent::Infest { + pos, + infested: false, + poof: None, + }); + } + if m.random.next_boolean() { + return; + } + } + } + } + } +} +/// `Silverfish.SilverfishMergeWithStoneGoal`: a stroll that, now and then +/// with mob griefing on, hides in a stone block next to the silverfish. +#[derive(Clone, Debug)] +struct SilverfishMergeWithStone { + stroll: Stroll, + merge: Option<[i32; 3]>, +} +impl Default for SilverfishMergeWithStone { + fn default() -> Self { + Self { + stroll: Stroll::new(1.0).interval(10), + merge: None, + } + } +} +impl Goal for SilverfishMergeWithStone { + goal_clone!(); + fn name(&self) -> &'static str { + "SilverfishMergeWithStoneGoal" + } + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.ai.target.is_some() || !m.ai.nav.is_done() { + return false; + } + if cx.w.mob_griefing + && m.random + .next_int_bound(super::goals::reduced(10)) + .unwrap_or(1) + == 0 + { + // Direction.getRandom: down, up, north, south, west, east. + const DIRECTIONS: [[i32; 3]; 6] = [ + [0, -1, 0], + [0, 1, 0], + [0, 0, -1], + [0, 0, 1], + [-1, 0, 0], + [1, 0, 0], + ]; + let d = DIRECTIONS[m.random.next_int_bound(6).unwrap_or(0) as usize]; + let pos = [ + m.position.x.floor() as i32 + d[0], + (m.position.y + 0.5).floor() as i32 + d[1], + m.position.z.floor() as i32 + d[2], + ]; + if super::spawn_selection::infested_host(cx.w.block_name(pos[0], pos[1], pos[2])) { + self.merge = Some(pos); + return true; + } + } + self.merge = None; + self.stroll.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.merge.is_none() && self.stroll.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(pos) = self.merge else { + return self.stroll.start(m, cx); + }; + if super::spawn_selection::infested_host(cx.w.block_name(pos[0], pos[1], pos[2])) { + cx.events.push(MobEvent::Infest { + pos, + infested: true, + poof: Some(m.id), + }); + m.removed = true; + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.stroll.stop(m, cx); + } +} /// Entity.getLightLevelDependentMagicValue at the eye. pub fn mob_brightness(m: &Mob, w: &MobWorld) -> f32 { w.brightness( diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index 4e51722f1..dc6a2fc72 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -535,7 +535,7 @@ pub(crate) fn mob_spawn_rules(s: Species, l: &L, x: i32, y: i32 value >= 0.0 } /// `InfestedBlock.isCompatibleHostBlock`. -fn infested_host(block: &str) -> bool { +pub fn infested_host(block: &str) -> bool { matches!( block, "minecraft:stone" From 5b89508fe92abd98e2035e95c08c0be6269dfc87 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 18:58:36 +0100 Subject: [PATCH 035/221] Predict putting out a lit campfire with a shovel on the client In single player and LAN the client never recognized the shovel on a lit campfire, so there was no smoke and a shield in the other hand was raised too. The client now shows the smoke, puts the fire out locally and ends the click after the hand that doused. --- .../horizon-client/src/game/campfire_douse.rs | 70 ++++++++++++++----- crates/horizon-client/src/game/remote.rs | 7 +- 2 files changed, 60 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game/campfire_douse.rs b/crates/horizon-client/src/game/campfire_douse.rs index 04accb2d3..e3a990b27 100644 --- a/crates/horizon-client/src/game/campfire_douse.rs +++ b/crates/horizon-client/src/game/campfire_douse.rs @@ -2,8 +2,60 @@ //! shovels) put on a lit campfire puts it out. use super::Game; use horizon_client::{Result, animate_tick::make_campfire_smoke, items::ItemStack}; +use horizon_core::position::BlockPos; +use horizon_world::chunk::BlockState; +use winit::keyboard::KeyCode; impl Game<'_> { + /// The lit campfire at `pos` that `held` puts out, when the item is in + /// `#minecraft:douses_campfires` (`CampfireBlock.useItemOn`). + fn campfire_to_douse(&self, pos: [i32; 3], held: Option<&ItemStack>) -> Option { + held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:douses_campfires") + .is_some_and(|members| members.contains(&*s.item)) + })?; + self.pack + .assets + .registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire")) + .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true")) + .cloned() + } + + /// `CampfireBlock.useItemOn` as this client runs it before the server's + /// answer (`MultiPlayerGameMode.useItemOn`): the twenty smoke puffs of + /// `CampfireBlock.douse` and the campfire gone out, kept as predicted + /// under `seq`. The level event's sound comes from the server. True when + /// it doused (SUCCESS), which ends the click for both hands. + pub(super) fn predict_campfire_douse( + &mut self, + pos: [i32; 3], + held: Option<&ItemStack>, + seq: i32, + ) -> bool { + // Player.isSecondaryUseActive: a held item means both hands count. + if self.keys.contains(&KeyCode::ShiftLeft) { + return false; + } + let Some(mut state) = self.campfire_to_douse(pos, held) else { + return false; + }; + let signal = state.properties.get("signal_fire").map(String::as_str) == Some("true"); + for _ in 0..20 { + make_campfire_smoke(&mut self.particles, pos, signal, true); + } + state.properties.insert("lit".into(), "false".into()); + if let Ok(unlit) = self.pack.assets.registry.resolve(&state) { + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.predict_blocks(&vec![(at, unlit)], seq); + } + true + } + /// `CampfireBlock.useItemOn` with `held` in the hand that acts, the block /// at `pos` clicked: true when it doused a lit campfire (SUCCESS). pub(super) fn use_campfire_douse( @@ -11,24 +63,11 @@ impl Game<'_> { pos: [i32; 3], held: Option<&ItemStack>, ) -> Result { - let Some(tool) = held.filter(|s| { - self.res - .items() - .item_tags - .get("minecraft:douses_campfires") - .is_some_and(|members| members.contains(&*s.item)) - }) else { - return Ok(false); - }; - let registry = self.pack.assets.registry; - let Some(mut state) = registry - .state(self.world.block(pos[0], pos[1], pos[2])) - .filter(|s| matches!(&*s.name, "minecraft:campfire" | "minecraft:soul_campfire")) - .filter(|s| s.properties.get("lit").map(String::as_str) == Some("true")) - .cloned() + let (Some(used), Some(mut state)) = (held.cloned(), self.campfire_to_douse(pos, held)) else { return Ok(false); }; + let registry = self.pack.assets.registry; // Level event 1009 (SOUND_EXTINGUISH_FIRE) goes to every player. self.level_event_at(1009, pos, 0); // CampfireBlock.douse: the acting client's own smoke (twenty puffs), @@ -44,7 +83,6 @@ impl Game<'_> { if let Ok(unlit) = registry.resolve(&state) { self.level_set(pos, unlit)?; } - let used = tool.clone(); self.damage_held(1); // ServerPlayerGameMode.useItemOn: the action was consumed. self.trigger_block("minecraft:item_used_on_block", pos, &used); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..9a6d19b72 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4063,6 +4063,11 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + } else if self.predict_campfire_douse(hit.pos, held.as_ref(), seq) { + // CampfireBlock.useItemOn succeeded: this hand swings and the + // click ends, so a shield in the other hand is not raised. + self.with_hand(hand, Game::swing_arm); + return true; } else if let Some(stack) = held.as_ref() && self.predict_item_on_block(stack, &hit) { @@ -4230,7 +4235,7 @@ impl Game<'_> { /// predicted under the use's sequence until the server acknowledges it /// (`BlockStatePredictionHandler.retainKnownServerState`): a use the /// server refused goes back. - fn predict_blocks(&mut self, changes: &DryChanges, seq: i32) { + pub(super) fn predict_blocks(&mut self, changes: &DryChanges, seq: i32) { for &(p, state) in changes { let pos = [p.x, p.y, p.z]; let before = self.world.block(p.x, p.y, p.z); From a07c6d57dc5aac19f65730aa5b01579cf54f4e62 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:04:00 +0100 Subject: [PATCH 036/221] horizon-items: item_name reads name_text from horizon-client-core Main's item_name (d983ef89b) called crate::entity_nbt::name_text, which the client re-exports from horizon_client_core::component. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-items/src/item_data.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-items/src/item_data.rs b/crates/horizon-items/src/item_data.rs index 344dab6b7..52c0ccf9b 100644 --- a/crates/horizon-items/src/item_data.rs +++ b/crates/horizon-items/src/item_data.rs @@ -210,7 +210,7 @@ impl ItemStack { /// by `ominous_banner` instead. pub fn item_name(&self) -> Option { let name = self.data()?.other("minecraft:item_name")?; - Some(crate::entity_nbt::name_text(name).plain()) + Some(horizon_client_core::component::name_text(name).plain()) } pub fn potion(&self) -> Option<&str> { self.data().and_then(|d| d.potion.as_deref()) From 81b4c09ee6fd2cb5c83c43e7b8f67e92c12366e7 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:06:53 +0100 Subject: [PATCH 037/221] Count the endermite lifetime with NoAI set --- crates/horizon-client/src/mobs/ai.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 560afe08c..d61f2caa0 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -397,7 +397,13 @@ pub fn tick( } return false; } - if !m.no_ai { + if m.no_ai { + // Mob.aiStep still runs without AI (only serverAiStep is skipped), + // so the endermite's life keeps counting. + if m.species() == Species::Endermite { + endermite_lifetime(m); + } + } else { ai_step(m, w, level_random, events); } if m.species() == Species::Rabbit { @@ -955,6 +961,16 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { _ => {} } } +/// Endermite.aiStep: `counter` is the life; an endermite not required to +/// persist is discarded at 2400. +fn endermite_lifetime(m: &mut Mob) { + if !m.persistent { + m.extra.counter += 1; + } + if m.extra.counter >= 2400 { + m.removed = true; + } +} fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if family(m.species()) == Family::Aquatic { aquatic::ai_step(m, w, events); @@ -963,14 +979,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::Enderman => super::enderman::ai_step(m, w, events), // Endermite.aiStep: `counter` is the life; an endermite not required // to persist is discarded at 2400. - Species::Endermite => { - if !m.persistent { - m.extra.counter += 1; - } - if m.extra.counter >= 2400 { - m.removed = true; - } - } + Species::Endermite => endermite_lifetime(m), Species::Wolf => super::tame::ai_step(m, w, events), Species::Cat => super::tame::cat_ai_step(m, events), Species::Blaze => super::nether::blaze_ai_step(m, events), From e98d939919169ba833f424ab6d03ede68b591bf2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:06:59 +0100 Subject: [PATCH 038/221] Use the mob's own chunk for its local difficulty --- crates/horizon-client/src/game/creatures.rs | 3 +++ crates/horizon-client/src/mobs.rs | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..3a4c9bb4a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -549,6 +549,9 @@ impl Game<'_> { ..base.clone() }; let m = &mut mobs[i]; + // getCurrentDifficultyAt(blockPosition()): the mob's own chunk, + // not the local player's (a server thread has no player). + w.difficulty = self.local_difficulty([m.position.x, m.position.y, m.position.z]); w.nearest_player = super::natural_spawning::nearest_player( &players, m.position.x, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..57257ca75 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1503,7 +1503,8 @@ pub struct MobWorld<'a> { pub biomes: &'a crate::biome::Biomes, /// The `mob_griefing` game rule. pub mob_griefing: bool, - /// `getCurrentDifficultyAt` near the player. + /// `getCurrentDifficultyAt` at the mob being ticked (near the player + /// outside the mob tick). pub difficulty: spawning::LocalDifficulty, /// The End (its dimension type's monster spawn light rules). pub end: bool, From 872409ea57e005cecae3d272a547cc7e5fb15d3f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:08:19 +0100 Subject: [PATCH 039/221] Mined ice melts into water unless the tool has silk touch --- crates/horizon-client/src/game.rs | 14 ++++++++++++++ crates/horizon-world/src/level/hooks.rs | 23 +++++++++++++++++++++++ crates/horizon-world/src/level/mod.rs | 14 ++++++++++++++ 3 files changed, 51 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8448f0837..20c8a282e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3510,6 +3510,20 @@ impl Game<'_> { ); } } + // IceBlock.playerDestroy: the ice melts back into water (the + // #prevents_ice_melting tool tag holds only silk touch). + let prevents_melting = held + .as_ref() + .is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0); + self.with_level(|b, level, ticks| { + b.ice_destroyed_by_player( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + broken, + prevents_melting, + ); + }); } self.pending.clear(pos); self.process_level_events()?; diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index 7f9e8d19a..9b07b8d25 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -433,6 +433,29 @@ impl Sim<'_, L> { self.game_event(pos, "minecraft:block_destroy"); self.remove_block(pos, false) } + /// `IceBlock.playerDestroy` (after the drops): mined ice turns into water + /// when it sits over a solid block or a liquid, unless the tool prevents + /// ice melting (silk touch). In the nether, where water evaporates, the + /// block stays air. + pub(crate) fn ice_destroyed_by_player( + &mut self, + pos: BlockPos, + destroyed: BlockStateId, + prevents_melting: bool, + ) { + let b = self.b; + if !b.data(destroyed).is(Class::Ice) + || prevents_melting + || self.level.dimension() == super::Dimension::Nether + { + return; + } + let below = self.below_state(pos); + if b.in_set(below, &b.tags.blocks_motion) || b.liquid(below) { + let water = b.default_of(b.named.water); + self.set_block_and_update(pos, water); + } + } /// `entityInside` for entity-sensing blocks. pub(crate) fn entity_inside(&mut self, pos: BlockPos) { let b = self.b; diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index c81bdf369..757660ce4 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -646,6 +646,20 @@ impl Behaviours { ) -> bool { self.sim(level, ticks).player_destroy(pos, creative) } + /// `IceBlock.playerDestroy` after the drops: mined ice melts into water + /// unless the tool prevents ice melting (silk touch). `destroyed` is the + /// state that was broken. + pub fn ice_destroyed_by_player( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + destroyed: BlockStateId, + prevents_melting: bool, + ) { + self.sim(level, ticks) + .ice_destroyed_by_player(pos, destroyed, prevents_melting); + } /// `BaseFireBlock.getState(level, pos)`: soul fire on its base blocks, /// otherwise fire shaped by its neighbours. pub fn fire_state_for( From f25fbb6f2ed110ccdd7cb5b48731bbc05f5e159d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:11:24 +0100 Subject: [PATCH 040/221] Give zombified piglins that spawn in a nether portal a portal cooldown --- crates/horizon-client/src/game/creatures.rs | 5 ++++- crates/horizon-client/src/game/nether_portal.rs | 11 +++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..80079d7e3 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3367,6 +3367,9 @@ impl Game<'_> { f64::from(y + 1), f64::from(pos[2]) + 0.5, ]; - let _ = self.spawn_mob("minecraft:zombified_piglin", at, false); + // setPortalCooldown: the new piglin does not travel at once. + if let Some(id) = self.spawn_mob("minecraft:zombified_piglin", at, false) { + self.set_portal_cooldown(id); + } } } diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 87ba81c93..89bf96ae0 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -505,6 +505,17 @@ impl Game<'_> { ); } } + /// `Entity.setPortalCooldown` on an entity that has just spawned in a + /// portal: it stands in the portal for 300 ticks without going through. + pub(super) fn set_portal_cooldown(&mut self, id: u32) { + self.portals.entities.insert( + id, + PortalState { + cooldown: ENTITY_DELAY, + process: None, + }, + ); + } /// `canUsePortal(false)` of a mob: alive, riding nothing, not asleep, /// not carrying the player, and not a boss that never travels. fn mob_can_use_portal(&self, m: &horizon_client::mobs::Mob) -> bool { From 6823e34451a60971cddc1851e68f8ef485a5dcbb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:12:31 +0100 Subject: [PATCH 041/221] Let a piglin let go of the gold it admires when a player hits it --- crates/horizon-client/src/mobs/ai.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..eab3d486f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1328,7 +1328,16 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { // PiglinAi.wasHurtBy: drop what is being admired, no admiring for // a while after a player's hit, and anger. Species::Piglin if source.attacker == Some(Who::Player) => { - m.extra.using_item = 0; + // stopHoldingOffHandItem(.., false): a gold ingot is not bartered + // and is gone; anything else ends its admiring next tick, as if + // the time ran out, and the game side puts it away. + if m.extra.off_hand.as_deref() == Some("minecraft:gold_ingot") { + m.extra.off_hand = None; + m.extra.using_item = 0; + } else { + m.extra.using_item = + i32::from(m.extra.off_hand.is_some() && m.extra.using_item > 0); + } m.extra.egg_time = 400; m.extra.anger = 600; } From 79c3896449584da2309eea8db8aad12d8e949eda Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:13:58 +0100 Subject: [PATCH 042/221] Respawn on a free column within the respawn radius around the world spawn --- crates/horizon-client/src/game.rs | 17 +++-- crates/horizon-client/src/game/end.rs | 10 ++- .../horizon-client/src/game/initial_spawn.rs | 69 +++++++++++++------ crates/horizon-client/src/game/lan_actions.rs | 8 +++ .../horizon-client/src/game/server_travel.rs | 37 +++++++++- 5 files changed, 110 insertions(+), 31 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8448f0837..2d853cbe5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4253,11 +4253,18 @@ impl Game<'_> { if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { return Ok(()); } - // WorldSpawn: the stored column, lifted onto its current surface. - let y = self - .land_column(s.x.floor() as i32, s.z.floor() as i32) - .map_or(s.y, f64::from); - Vec3::new(s.x, y.max(s.y), s.z) + let column = [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32]; + if self.level.world_spawn == Some(column) { + // TeleportTransition.missingRespawnBlock: PlayerSpawnFinder + // around the world spawn, not its exact column. + self.respawn_spawn(column) + } else { + // A spawnpoint: the stored column, lifted onto its current surface. + let y = self + .land_column(column[0], column[2]) + .map_or(s.y, f64::from); + Vec3::new(s.x, y.max(s.y), s.z) + } }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 32d5113b0..f11d4a61c 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -578,9 +578,13 @@ impl Game<'_> { let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]); target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5); } - let y = self - .land_column(target.x.floor() as i32, target.z.floor() as i32) - .map_or(target.y, f64::from); + let (x, z) = (target.x.floor() as i32, target.z.floor() as i32); + // TeleportTransition.missingRespawnBlock: PlayerSpawnFinder around + // the world spawn. + if let Some(world) = self.level.world_spawn.filter(|w| w[0] == x && w[2] == z) { + return Ok((self.respawn_spawn(world), None)); + } + let y = self.land_column(x, z).map_or(target.y, f64::from); Ok((Vec3::new(target.x, y, target.z), None)) } diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 3f7a071bb..bcea90337 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -121,33 +121,58 @@ impl Game<'_> { } Ok(Some([ox * 16 + 8, height, oz * 16 + 8])) } + /// PlayerSpawnFinder.findSpawn: the finder for a suggestion, its radius + /// the respawn radius cut to the world border. + fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder { + if self.level.game_mode == 2 { + // Adventure mode: the suggestion itself. + let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); + finder.next_candidate(); + return finder; + } + let mut radius = self.ui.rules.int("respawn_radius").max(0); + let to_border = self + .border + .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) + .floor() as i32; + if to_border < radius { + radius = to_border; + } + if to_border <= 1 { + radius = 1; + } + PlayerSpawnFinder::new(suggestion, radius, |n| { + entity_random().next_int_bound(n).unwrap_or(0) + }) + } + /// PlayerSpawnFinder.findSpawn around the world spawn for a player placed + /// at once (TeleportTransition.createDefault and missingRespawnBlock): the + /// first free column within the respawn radius, the suggestion's own + /// column when none is. A candidate whose chunk is not loaded counts as + /// not free; the suggestion's chunk must be. + pub(super) fn respawn_spawn(&self, suggestion: [i32; 3]) -> Vec3 { + let mut finder = self.spawn_finder(suggestion); + while let Some(candidate) = finder.next_candidate() { + let SpawnCandidate::Column(x, z) = candidate else { + break; + }; + if !self.streaming.is_lit(x >> 4, z >> 4) { + continue; + } + if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z) + && self.player_fits(pos) + { + return bottom_center(pos); + } + } + self.fixup_spawn_height(suggestion) + } /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a /// player who has no position yet. None while a candidate's chunk loads. pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { let mut finder = match self.player_spawn { Some(finder) => finder, - None if self.level.game_mode == 2 => { - // Adventure mode: the suggestion itself. - let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); - finder.next_candidate(); - finder - } - None => { - let mut radius = self.ui.rules.int("respawn_radius").max(0); - let to_border = self - .border - .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) - .floor() as i32; - if to_border < radius { - radius = to_border; - } - if to_border <= 1 { - radius = 1; - } - PlayerSpawnFinder::new(suggestion, radius, |n| { - entity_random().next_int_bound(n).unwrap_or(0) - }) - } + None => self.spawn_finder(suggestion), }; let found = loop { let Some(candidate) = finder.next_candidate() else { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..dcb3c8919 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1853,6 +1853,10 @@ impl Game<'_> { } if let Some(config) = elsewhere { self.respawn_trip(conn, config); + } else if in_frame_bed.is_none() && host.hub.guests[i].spawn.is_none() { + // TeleportTransition.createDefault: no point of its own, so the + // world spawn's free column once its chunks have loaded. + self.world_spawn_trip(conn); } if let Some(c) = in_frame_bed && self.dim == super::Dim::Overworld @@ -1871,6 +1875,10 @@ impl Game<'_> { host.hub.guests[i].yaw = yaw; [at.x, at.y, at.z] }); + if found.is_none() { + // TeleportTransition.missingRespawnBlock. + self.world_spawn_trip(conn); + } host.hub.teleport(i, Some(at)); } if away && let Err(e) = self.enter_level(Some(host), back) { diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index bcaf37a76..e22cd60e9 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -31,6 +31,9 @@ pub(super) struct Trip { /// A respawn at this point outside the Overworld, resolved through its /// block on arrival. respawn: Option, + /// A respawn at the world spawn, moved onto a free column within the + /// respawn radius once the chunks around it have loaded. + world_spawn: bool, /// Sent by a command: the player is already where it goes. placed: bool, } @@ -66,10 +69,11 @@ impl Game<'_> { /// in it (Nether portals count up their transition time, End portals /// take them at once). pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) { + // Outside a server only the respawns at the world spawn wait for chunks. + self.arrive_server_trips(host); if self.options.dedicated.is_none() { return; } - self.arrive_server_trips(host); let conns: Vec = host .hub .guests @@ -253,6 +257,7 @@ impl Game<'_> { plan, gateway: None, respawn: None, + world_spawn: false, placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { @@ -272,6 +277,7 @@ impl Game<'_> { plan: None, gateway: None, respawn: Some(config), + world_spawn: false, placed: false, }); } @@ -304,6 +310,27 @@ impl Game<'_> { } } + /// TeleportTransition.createDefault and missingRespawnBlock: the player + /// waits at the world spawn for its chunks, then PlayerSpawnFinder puts + /// it on a free column within the respawn radius. + pub(super) fn world_spawn_trip(&mut self, conn: u32) { + let Some([x, y, z]) = self.level.world_spawn else { + return; + }; + self.server_trips.retain(|t| !t.is(conn)); + self.server_trips.push(Trip { + conn, + dim: Dim::Overworld, + target: Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5), + end: false, + plan: None, + gateway: None, + respawn: None, + world_spawn: true, + placed: false, + }); + } + /// TeleportTransition.missingRespawnBlock: the world spawn, in the /// Overworld. fn respawn_at_world_spawn(&mut self, host: &mut LanHost, conn: u32) { @@ -318,6 +345,7 @@ impl Game<'_> { rotation: None, }); self.run_level_teleports(host); + self.world_spawn_trip(conn); } /// `TheEndGatewayBlockEntity.getPortalPosition` and the teleport within @@ -343,6 +371,7 @@ impl Game<'_> { plan: None, gateway: Some(job), respawn: None, + world_spawn: false, placed: false, }); } @@ -383,6 +412,11 @@ impl Game<'_> { continue; } } + } else if trip.world_spawn { + // PlayerSpawnFinder.findSpawn around the world spawn. + let suggestion = + [trip.target.x, trip.target.y, trip.target.z].map(|v| v.floor() as i32); + (self.respawn_spawn(suggestion), yaw) } else if let Some(job) = trip.gateway { match self.resolve_gateway(job, trip.target) { Ok(at) => (at, yaw), @@ -458,6 +492,7 @@ impl Game<'_> { plan: None, gateway: None, respawn: None, + world_spawn: false, placed: true, }); if let Err(e) = self.enter_level(Some(host), source) { From 886a84dea086f4c67674a40a4b72e3b90dd904ac Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:14:04 +0100 Subject: [PATCH 043/221] Fly thrown tridents on by themselves between server updates --- crates/horizon-client/src/game/remote.rs | 13 +++ .../src/game/remote_projectiles.rs | 39 ++++++++- crates/horizon-client/src/game/trident.rs | 83 +++++++++++++++---- 3 files changed, 115 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..6b0d2477d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1406,6 +1406,17 @@ impl Game<'_> { { return; } + // A thrown trident is an arrow: placed at once, flown on by its tick. + if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id as u32) { + if path.is_some() { + t.position = Vec3::new(position[0], position[1], position[2]); + } + if let Some((yaw, pitch)) = rotation { + t.yaw = yaw; + t.pitch = pitch; + } + 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 +3027,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(t) = self.tridents.iter_mut().find(|t| t.id == id as u32) { + t.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 897999c6b..133c2b9fd 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -122,6 +122,8 @@ impl Game<'_> { "minecraft:trident" => { let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch); t.velocity = velocity; + // Projectile.getAddEntityPacket: the owner's id is the data. + t.owner = data as u32; self.tridents.push(t); } "minecraft:firework_rocket" => { @@ -261,6 +263,15 @@ impl Game<'_> { (9, Value::Bool(show)) => c.show_bottom = *show, _ => {} } + } else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) { + // AbstractArrow.ID_FLAGS (no physics) and IN_GROUND, and + // ThrownTrident.ID_LOYALTY. + match (index, value) { + (8, Value::Byte(flags)) => t.no_physics = flags & 2 != 0, + (10, Value::Bool(in_ground)) => t.in_ground = *in_ground, + (11, Value::Byte(loyalty)) => t.loyalty = u32::from(*loyalty as u8), + _ => {} + } } else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { match (&mut p.kind, index, value) { // AbstractArrow.ID_FLAGS (critical) and IN_GROUND. @@ -294,6 +305,25 @@ impl Game<'_> { } } + /// `Entity.getEyePosition` of a projectile's owner: this game's player or + /// another player the server sent. + fn remote_eye(&self, id: u32) -> Option { + let me = self + .remote + .as_ref() + .and_then(|r| u32::try_from(r.entity_id).ok()); + if me == Some(id) { + let eye = self.eye_position()?; + return Some(Vec3::new(eye[0], eye[1], eye[2])); + } + let m = self.mobs.iter().find(|m| m.id == id)?; + Some(Vec3::new( + m.position.x, + m.position.y + m.eye_height(), + m.position.z, + )) + } + /// One tick of interpolation, as `tick_remote_objects`. pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { // PrimedTnt.tick runs on a client too: it falls, bounces and burns its @@ -326,6 +356,7 @@ impl Game<'_> { // updates (10 to 20 ticks apart); a block stops them there, and only // the server decides what they hit. let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + let mut tridents = std::mem::take(&mut self.tridents); { let w = self.mob_world_base(&[]); let world = super::creatures::ProjWorld { @@ -348,12 +379,12 @@ impl Game<'_> { } } } + for t in &mut tridents { + t.remote_tick(&world, self.remote_eye(t.owner)); + } } self.creatures.projectiles = projectiles; - for t in &mut self.tridents { - let id = t.id; - t.remote_step(|at| step(id, at)); - } + self.tridents = tridents; // FireworkRocketEntity.tick: a rocket attached to the gliding local // player boosts it client-side too (attachedToEntity.isFallFlying). let me = self diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index c31094596..75b546804 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -8,6 +8,7 @@ use horizon_client::{ items::ItemStack, mesher::Vertex, mobs::{Damage, DamageKind, Who, anim::Poses}, + projectiles::ProjectileWorld, }; use horizon_core::{ geometry::{Aabb, Vec3}, @@ -30,6 +31,8 @@ pub(super) struct ThrownTrident { pub(super) no_physics: bool, returning: u32, creative_only: bool, + /// The entity id a server sent as its owner (the one Loyalty returns it to). + pub(super) owner: u32, } impl ThrownTrident { /// A trident a server sent (`handleAddEntity`): placed and moved by it. @@ -49,12 +52,71 @@ impl ThrownTrident { no_physics: false, returning: 0, creative_only: false, + owner: 0, } } - /// One tick of a server's client: the previous position, then `step`. - pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + /// `ThrownTrident.tick`'s Loyalty return: pulled up and towards the + /// owner's eye. + fn loyalty_pull(&mut self, owner_eye: Vec3) { + let v = Vec3::new( + owner_eye.x - self.position.x, + owner_eye.y - self.position.y, + owner_eye.z - self.position.z, + ); + self.position.y += v.y * 0.015 * f64::from(self.loyalty); + let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1e-9); + let accel = 0.05 * f64::from(self.loyalty); + self.velocity = Vec3::new( + self.velocity.x * 0.95 + v.x / len * accel, + self.velocity.y * 0.95 + v.y / len * accel, + self.velocity.z * 0.95 + v.z / len * accel, + ); + } + /// `ThrownTrident.tick` on a server's client: it flies on by itself + /// between the server's updates (`AbstractArrow.tick`: gravity and drag, + /// a block holds it), and Loyalty pulls it back to its owner; only the + /// server decides what it hits. + pub(super) fn remote_tick(&mut self, w: &impl ProjectileWorld, owner_eye: Option) { self.previous = self.position; - self.position = step(self.position); + if self.in_ground_time > 4 { + self.dealt_damage = true; + } + if self.loyalty > 0 + && (self.dealt_damage || self.no_physics) + && let Some(eye) = owner_eye + { + self.no_physics = true; + self.in_ground = false; + self.loyalty_pull(eye); + } + if self.in_ground && !self.no_physics { + self.in_ground_time += 1; + return; + } + self.in_ground_time = 0; + let m = self.velocity; + let (x, z) = if self.no_physics { + (-m.x, -m.z) + } else { + (m.x, m.z) + }; + self.yaw = x.atan2(z).to_degrees() as f32; + self.pitch = m.y.atan2(m.x.hypot(m.z)).to_degrees() as f32; + let to = self.position.add_vector(m); + if !self.no_physics + && let Some((at, _, _)) = w.clip(self.position, to) + { + self.position = at; + self.velocity = Vec3::ZERO; + self.in_ground = true; + return; + } + self.position = to; + // A trident's water inertia (0.99) equals the air drag. + self.velocity = self.velocity.scale(0.99); + if !self.no_physics { + self.velocity.y -= 0.05; + } } } const HALF: f64 = 0.25; @@ -240,6 +302,7 @@ impl Game<'_> { no_physics: false, returning: 0, creative_only: self.creative, + owner: 0, }); self.player_projectile_shot(); self.audio @@ -261,19 +324,7 @@ impl Game<'_> { if t.loyalty > 0 && (t.dealt_damage || t.no_physics) { t.no_physics = true; t.in_ground = false; - let v = Vec3::new( - owner_eye.x - t.position.x, - owner_eye.y - t.position.y, - owner_eye.z - t.position.z, - ); - t.position.y += v.y * 0.015 * f64::from(t.loyalty); - let len = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1e-9); - let accel = 0.05 * f64::from(t.loyalty); - t.velocity = Vec3::new( - t.velocity.x * 0.95 + v.x / len * accel, - t.velocity.y * 0.95 + v.y / len * accel, - t.velocity.z * 0.95 + v.z / len * accel, - ); + t.loyalty_pull(owner_eye); if t.returning == 0 { self.audio.play( "minecraft:item.trident.return", From a44581eaf39a1775b79e5ee450f7a0fab1dc9347 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:14:23 +0100 Subject: [PATCH 044/221] Let a shulker bullet's levitation run out on mobs --- crates/horizon-client/src/game/creatures.rs | 2 +- crates/horizon-client/src/mobs.rs | 1 - crates/horizon-client/src/mobs/living.rs | 10 ++++++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..3d16faae9 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2385,7 +2385,7 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) && m.damage(4.0, source) { - m.extra.levitation = 200; + m.add_effect("minecraft:levitation", 200, 0); } } }, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..631ef40eb 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -677,7 +677,6 @@ pub struct Extra { pub anger: i32, pub carried: Option, pub charged: bool, - pub levitation: i32, /// Held item ids (main hand, off hand) and head item. pub main_hand: Option>, pub off_hand: Option>, diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..ddb25d877 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -742,8 +742,14 @@ impl Mob { movement.y = 0.2; } let mut y = movement.y; - if self.extra.levitation > 0 { - y += (0.05 * 1.0 - movement.y) * 0.2; + // LivingEntity.travelInAir: levitation lifts by its amplifier. + if let Some(&(_, _, amp)) = self + .extra + .effects + .iter() + .find(|e| e.0 == "minecraft:levitation") + { + y += (0.05 * f64::from(amp + 1) - movement.y) * 0.2; } else { y -= self.gravity(); } From 0b3e40f9d449923e4bb0d8d4de37211ad2306e07 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:15:28 +0100 Subject: [PATCH 045/221] Give a closed shulker its 20 covered armor --- crates/horizon-client/src/mobs.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..5a13a588c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1730,9 +1730,15 @@ impl Mob { amount *= 0.75; } let (worn, worn_toughness) = self.worn_armor(); - if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { + // Shulker.setRawPeekAmount: a closed shell adds the covered armor modifier. + let covered = if self.species() == Species::Shulker && self.extra.counter == 0 { + 20.0 + } else { + 0.0 + }; + if !source.bypasses_armor() && self.kind.armor + worn + covered > 0.0 { // CombatRules.getDamageAfterAbsorb - let armor = self.kind.armor + worn; + let armor = self.kind.armor + worn + covered; let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0; let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0); let mut fraction = effective / 25.0; From 034af457778bab980cc95ca1c76c8e50471d49fc Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:15:33 +0100 Subject: [PATCH 046/221] Make adult piglins hunt adult hoglins --- crates/horizon-client/src/game/creatures.rs | 8 ++ crates/horizon-client/src/mobs.rs | 10 ++ crates/horizon-client/src/mobs/piglin.rs | 103 ++++++++++++++++++-- 3 files changed, 111 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..a9aa16a1b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1009,6 +1009,14 @@ impl Game<'_> { m.ai.target = Some(target); } } + MobEvent::HuntHoglin { mob, target, ticks } => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.extra.ints[0] = ticks; + if m.ai.target.is_none() { + m.ai.target = Some(Who::Mob(target)); + } + } + } MobEvent::Projectile(mut p) => { self.next_entity += 1; p.id = self.next_entity; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 00c21633e..cd00a12c4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -985,6 +985,13 @@ pub enum MobEvent { mob: u32, target: Who, }, + /// `StartHuntingHoglin` for a nearby adult piglin: it takes the hoglin as + /// its anger target (when it has none) and starts its `HUNTED_RECENTLY` wait. + HuntHoglin { + mob: u32, + target: u32, + ticks: i32, + }, Projectile(crate::projectiles::Projectile), /// Spawn a new mob (breeding, slime splitting, chicken eggs...). Spawn(Box), @@ -1251,6 +1258,8 @@ pub struct Seen { /// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a /// horse's breeding stock). pub stats: [f64; 3], + /// A piglin's `HUNTED_RECENTLY` memory. + pub hunted_recently: bool, } impl Mob { pub fn burning_time(&self) -> f64 { @@ -1323,6 +1332,7 @@ impl Mob { m.extra.vector[0], m.attrs.speed, ], + hunted_recently: m.species() == Species::Piglin && m.extra.ints[0] > 0, } } /// `EntityType.getCategory`'s name. diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index fff536932..5b8c17fb3 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -6,7 +6,8 @@ use super::{ anim::{Poses, State}, goals::{ Avoid, AvoidEntity, Cx, Float, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, MeleeAttack, - NearestTarget, Prey, RandomLookAround, Stroll, goal_clone, + NearestTarget, Prey, RandomLookAround, Stroll, TARGET, TargetState, goal_clone, + target_continue, }, }; use horizon_core::geometry::{Vec3, trig::Mth}; @@ -54,15 +55,94 @@ pub fn register_piglin(m: &mut Mob) { m.ai.targets.add(1, hurt); m.ai.targets .add(2, NearestTarget::player(true).when(hostile_to_player)); - m.ai.targets.add( - 3, - NearestTarget::new( - Prey::Filter(|s| s.species == Species::Hoglin && s.baby), - true, - ) - .interval(10) - .when(|m, _| !m.is_baby()), - ); + m.ai.targets.add(3, HuntHoglin::default()); + // `PiglinAi.initMemories`: the first hunt waits too. + m.extra.ints[0] = time_between_hunts(m); +} +/// `PiglinAi.TIME_BETWEEN_HUNTS`: 30 to 120 seconds. +fn time_between_hunts(m: &mut Mob) -> i32 { + m.random + .next_int_between_inclusive(600, 2400) + .unwrap_or(600) +} +/// `StartHuntingHoglin`: an adult piglin that is not angry, has not hunted +/// recently and sees no adult piglin that has, goes for the nearest adult +/// hoglin it sees; then it and the adult piglins near it wait before the next +/// hunt, and the others join in (`broadcastAngerTarget`). +#[derive(Clone, Debug)] +struct HuntHoglin { + found: Option, + st: TargetState, +} +impl Default for HuntHoglin { + fn default() -> Self { + let mut st = TargetState::default(); + st.unseen_memory = 60; + Self { found: None, st } + } +} +impl Goal for HuntHoglin { + goal_clone!(); + fn flags(&self) -> u8 { + TARGET + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.is_baby() || m.extra.ints[0] > 0 || m.extra.anger > 0 || m.ai.target.is_some() { + return false; + } + let range = m.attrs.follow_range; + let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let id = m.id; + if cx + .w + .nearby(pos, range, |s| { + s.id != id && s.species == Species::Piglin && !s.baby && s.hunted_recently + }) + .next() + .is_some() + { + return false; + } + let hoglins: Vec<(u32, Vec3)> = + cx.w.nearby(pos, range, |s| s.species == Species::Hoglin && !s.baby) + .map(|s| (s.id, s.position)) + .collect(); + self.found = hoglins + .into_iter() + .find(|&(hoglin, at)| { + m.distance_sqr(at) <= range * range && m.sees(cx.w, Who::Mob(hoglin)) + }) + .map(|(hoglin, _)| hoglin); + self.found.is_some() + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + target_continue(&mut self.st, true, m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(hoglin) = self.found else { return }; + m.ai.target = Some(Who::Mob(hoglin)); + m.extra.ints[0] = time_between_hunts(m); + let range = m.attrs.follow_range; + let pos = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let id = m.id; + let others: Vec = + cx.w.nearby(pos, range, |s| { + s.id != id && s.species == Species::Piglin && !s.baby + }) + .map(|s| s.id) + .collect(); + for mob in others { + let ticks = time_between_hunts(m); + cx.events.push(MobEvent::HuntHoglin { + mob, + target: hoglin, + ticks, + }); + } + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.ai.target = None; + } } pub fn register_brute(m: &mut Mob) { let g = &mut m.ai.goals; @@ -251,6 +331,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.species() == Species::Hoglin && m.alive() { hoglin_repellent(m, w); } + if m.species() == Species::Piglin && m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } if m.extra.anger > 0 { m.extra.anger -= 1; if m.extra.anger == 0 && m.ai.target == Some(Who::Player) && !hostile_to_player(m, w) { From dfd06011633f9b0d7f730297cb4e1fb64a4d63f0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:16:52 +0100 Subject: [PATCH 047/221] Teleport a dragon egg when it is left-clicked --- crates/horizon-world/src/level/interact.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 7b2195c34..546da430f 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -513,7 +513,8 @@ impl Behaviours { sim.game_event_state(pos, "minecraft:block_change", next); } - /// The state change of `RedStoneOreBlock.attack` when mining begins. + /// `BlockBehaviour.attack` when mining begins: `RedStoneOreBlock.attack` + /// lights the ore, `DragonEggBlock.attack` teleports the egg. pub fn attack_block( &self, level: &mut L, @@ -522,6 +523,9 @@ impl Behaviours { ) { let mut sim = self.sim(level, ticks); let state = sim.state(pos); + if self.data(state).chain.contains(&Class::DragonEgg) { + sim.dragon_egg_teleport(pos, state); + } if self.data(state).chain.contains(&Class::RedStoneOre) && !self.table.bool(state, self.props.lit) { From 605e8a1488e9beac7a9f0551a212634af49131da Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:18:08 +0100 Subject: [PATCH 048/221] Stop shulkers from targeting and shooting in Peaceful --- crates/horizon-client/src/mobs/shulker.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 11ebdadb4..bbbc07198 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -42,7 +42,7 @@ pub fn register(m: &mut Mob) { // attach axis. m.ai.targets.add( 2, - NearestTarget::player(true).when(|m, w| { + NearestTarget::player(true).gate(peaceful_off).when(|m, w| { let Some(p) = &w.player else { return false }; let d = p.position.subtract(m.position); let axis = match m.extra.variant3 { @@ -196,6 +196,11 @@ impl ProjectileWorld for Probe<'_, '_> { .full_collision } } +/// `level().getDifficulty() != Difficulty.PEACEFUL`, which the shulker's +/// attack goal and target goal check. +fn peaceful_off(_m: &Mob, w: &MobWorld) -> bool { + w.difficulty.effective != 0.0 +} /// `ShulkerAttackGoal`: open up and fire a bullet every one to five and a /// half seconds at a target within 20 blocks. #[derive(Clone, Debug)] @@ -211,7 +216,7 @@ impl Goal for ShulkerAttack { true } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - m.target_info(cx.w).is_some_and(|t| t.alive) + m.target_info(cx.w).is_some_and(|t| t.alive) && peaceful_off(m, cx.w) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { self.attack_time = 20; @@ -221,6 +226,9 @@ impl Goal for ShulkerAttack { set_peek(m, 0, cx.events); } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !peaceful_off(m, cx.w) { + return; + } self.attack_time -= 1; let (Some(who), Some(t)) = (m.ai.target, m.target_info(cx.w)) else { return; From 9aabeb39eee0dfe14a733f150d94703256576a43 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:18:50 +0100 Subject: [PATCH 049/221] Make /tp facing look from the feet, or the eyes under anchored eyes --- crates/horizon-client/src/game/commands.rs | 25 ++++++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 8f934ad8a..d760397f4 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1312,7 +1312,7 @@ impl Game<'_> { { return Err(err("commands.teleport.invalidPosition", &[])); } - let mut rotation = match ctx.get("rotation") { + let rotation = match ctx.get("rotation") { Some(Arg::Coords(c)) => Some(c.rotation(self.source_rotation())), _ => None, }; @@ -1327,21 +1327,31 @@ impl Game<'_> { (Some(f), _) => Some(f), (None, Some(_)) => { let e = self.entities(ctx, "facingEntity", false)?[0]; + // EntityAnchorArgument.Anchor.apply: the feet, or the eyes. let eyes = matches!(ctx.get("facingAnchor"), Some(Arg::Anchor(true))); + let eye_height = if eyes { self.target_eye_height(e) } else { 0.0 }; self.target_position(e) - .map(|p| [p[0], p[1] + if eyes { 1.62 } else { 0.0 }, p[2]]) + .map(|p| [p[0], p[1] + eye_height, p[2]]) } _ => None, }; - if let Some(f) = facing { - let eye = pos[1] + 1.62; + // Entity.lookAt: from the source's anchor (the feet, unless `anchored + // eyes`) on the teleported entity, so the eyes depend on the target. + let anchored_eyes = self.command_source.is_some_and(|s| s.eyes); + let look_at = |this: &Self, t: Target| { + let f = facing?; + let eye = if anchored_eyes { + pos[1] + this.target_eye_height(t) + } else { + pos[1] + }; let (dx, dy, dz) = (f[0] - pos[0], f[1] - eye, f[2] - pos[2]); let horizontal = (dx * dx + dz * dz).sqrt(); - rotation = Some([ + Some([ ((dz.atan2(dx).to_degrees()) - 90.0) as f32, (-(dy.atan2(horizontal).to_degrees())) as f32, - ]); - } + ]) + }; // A server's player in another level than the source's (`execute // in`, the console's Overworld) moves there (ServerPlayer.teleport // into another level), after the command. @@ -1351,6 +1361,7 @@ impl Game<'_> { None => self.dim, }; for &t in &targets { + let rotation = look_at(self, t).or(rotation); if self.teleport_across(t, source_level, pos, rotation) { continue; } From 9dbd0a4bafb0dd09bfc9c9898d6971ca05a2e448 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:19:36 +0100 Subject: [PATCH 050/221] Make the strafing dragon charge its fireball only with a clear line of sight --- crates/horizon-client/src/game/dragon.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index fff03ef1c..43a3124d8 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1374,7 +1374,16 @@ impl Game<'_> { } } let d2 = (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2); - if d2 < 4096.0 { + // Entity.hasLineOfSight: eye to eye (the dragon's eye is 0.85 of + // its 8 block height), blocks only. + let sees = d2 < 4096.0 && { + let eye = Vec3::new(pos.x, pos.y + 6.8, pos.z); + let target_eye = + tracked.map_or(pp.y + 1.62, |p| p.bounds.max_position().y - 0.18); + self.mob_world_base(&[]) + .line_of_sight(eye, Vec3::new(pp.x, target_eye, pp.z)) + }; + if sees { *charge += 1; let d = self.dragon.as_ref().expect("dragon"); let r = d.yaw.to_radians(); From a4ccf205f7872362bb53b9ffd40f038ca8ce5793 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:21:09 +0100 Subject: [PATCH 051/221] Throw what /give cannot fit from the player's eyes, for that player only --- crates/horizon-client/src/entities.rs | 9 ++++++- crates/horizon-client/src/entities/fluids.rs | 1 + crates/horizon-client/src/entity_nbt.rs | 7 +++++ crates/horizon-client/src/game.rs | 5 +++- crates/horizon-client/src/game/commands.rs | 26 +++++++++++++++++-- crates/horizon-client/src/game/lan_actions.rs | 11 ++++++-- crates/horizon-client/src/game/machines.rs | 1 + crates/horizon-client/src/game/remote.rs | 1 + 8 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 69e053411..ce12558c0 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -19,6 +19,8 @@ pub struct ItemEntity { pub id: u32, pub stack: ItemStack, pub thrower: Option<[i32; 4]>, + /// `ItemEntity.target`: the only player who may pick the item up. + pub target: Option<[i32; 4]>, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -346,7 +348,10 @@ pub fn merge_with_neighbours( } // ItemEntity.areMergable: both fit one stack of the same item and components. let (this, other) = (&items[i].stack, &items[j].stack); - if this.count + other.count > max_stack(other) || !this.same_item_same_components(other) { + if items[i].target != items[j].target + || this.count + other.count > max_stack(other) + || !this.same_item_same_components(other) + { continue; } let (to, from) = if other.count < this.count { @@ -874,6 +879,7 @@ mod fire_environment_tests { let make = |id: &str| ItemEntity { id: 1, thrower: None, + target: None, stack: ItemStack { item: std::sync::Arc::from(id), count: 1, @@ -970,6 +976,7 @@ mod merge_tests { ItemEntity { id: 0, thrower: None, + target: None, stack: ItemStack { item: std::sync::Arc::from(id), count, diff --git a/crates/horizon-client/src/entities/fluids.rs b/crates/horizon-client/src/entities/fluids.rs index fffa0ae2b..3b3dffa99 100644 --- a/crates/horizon-client/src/entities/fluids.rs +++ b/crates/horizon-client/src/entities/fluids.rs @@ -189,6 +189,7 @@ mod tests { extra: None, }, thrower: None, + target: None, position: at, previous: at, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..c5115baac 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -967,6 +967,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> } else if let Tag::Compound(map) = &mut tag { map.remove(&"Thrower".into()); } + if let Some(target) = e.target { + put(&mut tag, "Owner", Tag::IntArray(target.to_vec())); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"Owner".into()); + } tag } pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { @@ -978,6 +983,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { health: 5, fire_ticks: 0, thrower: None, + target: None, id: self.next_entity, stack, position: p, @@ -2417,6 +2418,7 @@ impl Game<'_> { ], ); let feet = [p.position.x, p.position.y, p.position.z]; + let own = self.level.ensure_player_uuid(); let mut kept = Vec::with_capacity(items.len()); for mut item in items { let b = item.bounds(); @@ -2426,7 +2428,8 @@ impl Game<'_> { && b.max_position().y > min[1] && b.min_position().z < max[2] && b.max_position().z > min[2]; - if touching && item.pickup_delay == 0 { + // ItemEntity.playerTouch: no pickup delay, and the target (if any) is this player. + if touching && item.pickup_delay == 0 && item.target.is_none_or(|t| t == own) { let before = item.stack.count; let kind = item.stack.item.clone(); match self.give(item.stack.clone()) { diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 8f934ad8a..2988996d1 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1042,6 +1042,17 @@ impl Game<'_> { // An air stack is empty: nothing is given (but the message still is). let empty = id == "minecraft:air"; for &t in targets.iter().filter(|_| !empty) { + // The player's UUID, which an item they could not hold is set to. + let conn = match t { + Target::Guest(conn) => Some(conn), + _ => self.lan_acting, + }; + let uuid = match conn { + Some(conn) => self + .command_guest(conn) + .map(|g| horizon_client::lan::playerdata::uuid_ints(g.uuid)), + None => Some(self.level.ensure_player_uuid()), + }; self.for_player(t, |g| { let mut remaining = count; while remaining > 0 { @@ -1058,8 +1069,19 @@ impl Game<'_> { .target_position(Target::Player) .unwrap_or(g.source_position()); if let Some(rest) = left { - // Inventory full: drop the rest at the player's feet without pickup delay. - g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); + // Inventory full: Player.createItemStackToDrop (thrown from + // the eyes), then setNoPickUpDelay and setTarget(player). + let eye = g.eye_position().unwrap_or([ + p[0], + p[1] + g.target_eye_height(Target::Player), + p[2], + ]); + g.throw_from_eyes(rest, eye); + if let Some(item) = g.dropped.last_mut() { + item.thrower = None; + item.pickup_delay = 0; + item.target = uuid; + } } else { let r = &mut g.world.random; let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..d0bd8e670 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2569,9 +2569,15 @@ impl Game<'_> { /// Dropped items touching a guest go into their inventory. fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) { - let (conn, mode, position, id) = { + let (conn, mode, position, id, uuid) = { let g = &host.hub.guests[gi]; - (g.conn, g.game_mode, g.position, g.entity_id) + ( + g.conn, + g.game_mode, + g.position, + g.entity_id, + horizon_client::lan::playerdata::uuid_ints(g.uuid), + ) }; if mode == SPECTATOR || self.dropped.is_empty() { return; @@ -2582,6 +2588,7 @@ impl Game<'_> { .enumerate() .filter(|(_, d)| { d.pickup_delay == 0 + && d.target.is_none_or(|t| t == uuid) && (d.position.x - position[0]).abs() < 1.5 && (d.position.z - position[2]).abs() < 1.5 && d.position.y > position[1] - 0.6 diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index bb936744b..94d9790d4 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -955,6 +955,7 @@ mod item_column_tests { id, stack: ItemStack::new("minecraft:stone", 1), thrower: None, + target: None, position: at, previous: at, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..5b9bc7ff7 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2980,6 +2980,7 @@ impl Game<'_> { health: 5, fire_ticks: 0, thrower: None, + target: None, id: id as u32, stack, position: at, From 3b24aceb044f9caa07082b224994e931b395bfc9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:21:53 +0100 Subject: [PATCH 052/221] Let /clone move work on overlapping regions --- crates/horizon-client/src/game/commands.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 8f934ad8a..60e8aea59 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2056,7 +2056,8 @@ impl Game<'_> { let dmax = [dest[0] + size[0], dest[1] + size[1], dest[2] + size[2]]; let overlap = (0..3).all(|i| dest[i] <= max[i] && dmax[i] >= min[i]); let moving = ctx.has("move"); - if !ctx.has("force") && overlap { + // Mode.canOverlap: only the normal mode refuses overlapping regions. + if !ctx.has("force") && !moving && overlap { return Err(err("commands.clone.overlap", &[])); } let area = (0..3).map(|i| i64::from(size[i] + 1)).product::(); From 10872bdd64bcb3c96cf02a8d544d0645020111c6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:22:53 +0100 Subject: [PATCH 053/221] Add the tridents field to the remote motion test fixture --- tests/test_remote_motion.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py index b00e5f0a9..3a6e28de5 100644 --- a/tests/test_remote_motion.py +++ b/tests/test_remote_motion.py @@ -35,7 +35,7 @@ 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, tridents: Vec, remote: Option, potions: Potions, end: End, } impl Game { From 8ca15ae2ca47df8857c611cde8c2208568a74101 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:23:47 +0100 Subject: [PATCH 054/221] Apply /xp, /clear and /spawnpoint to each target, not only the host --- crates/horizon-client/src/game/commands.rs | 171 +++++++++++++-------- 1 file changed, 103 insertions(+), 68 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 8f934ad8a..cc3398f90 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2265,26 +2265,54 @@ impl Game<'_> { let levels = ctx.has("levels"); let unit = if levels { "levels" } else { "points" }; if ctx.has("query") { - let _ = self.entities(ctx, "target", true)?; - let e = &self.experience; - let value = if levels { - e.level - } else { - (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32 - }; + let target = self.entities(ctx, "target", true)?[0]; + // ExperienceCommand.queryExperience: the target's own level or points. + let value = self + .for_player(target, |g| { + let e = &g.experience; + if levels { + e.level + } else { + (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) + as i32 + } + }) + .unwrap_or(0); self.system_message(Text::translate( &format!("commands.experience.query.{unit}"), - &[ - Text::literal(self.acting_player_name()), - Text::literal(value.to_string()), - ], + &[self.target_name(target), Text::literal(value.to_string())], )); return Ok(value); } let targets = self.entities(ctx, "target", true)?; let amount = Self::int(ctx, "amount").unwrap_or(0); - let op = if ctx.has("add") { "add" } else { "set" }; - if op == "add" { + let add = ctx.has("add"); + let op = if add { "add" } else { "set" }; + // Every target changes (a set of points can be refused for some). + let changed: Vec = targets + .iter() + .copied() + .filter(|&t| { + self.for_player(t, |g| g.change_experience(add, levels, amount)) == Some(true) + }) + .collect(); + if changed.is_empty() { + return Err(err("commands.experience.set.points.invalid", &[])); + } + let (key, who) = match changed[..] { + [only] => ("single", self.target_name(only)), + _ => ("multiple", Text::literal(changed.len().to_string())), + }; + self.feedback(Text::translate( + &format!("commands.experience.{op}.{unit}.success.{key}"), + &[Text::literal(amount.to_string()), who], + )); + Ok(changed.len() as i32) + } + /// ExperienceCommand's add and set on the player in place: false when + /// the points to set do not fit the level. + fn change_experience(&mut self, add: bool, levels: bool, amount: i32) -> bool { + if add { if levels { self.experience.level = (self.experience.level + amount).max(0); if self.experience.level == 0 && amount < 0 { @@ -2298,26 +2326,11 @@ impl Game<'_> { } else { let needed = horizon_client::entities::Experience::needed(self.experience.level); if amount > needed - 1 { - return Err(err("commands.experience.set.points.invalid", &[])); + return false; } self.experience.progress = amount as f32 / needed as f32; } - let key = format!( - "commands.experience.{op}.{unit}.success.{}", - if targets.len() == 1 { - "single" - } else { - "multiple" - } - ); - self.feedback(Text::translate( - &key, - &[ - Text::literal(amount.to_string()), - Text::literal(self.acting_player_name()), - ], - )); - Ok(targets.len() as i32) + true } fn cmd_gamerule(&mut self, ctx: &Context) -> R { let Some(name) = ctx.literals.get(1).cloned() else { @@ -2402,21 +2415,26 @@ impl Game<'_> { }; let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; let pitch = rot[1].clamp(-90.0, 90.0); - // SetSpawnCommand: a forced point in the source's level. - if self.dim == Dim::Overworld { - self.spawn = Some(Vec3::new( - f64::from(pos[0]) + 0.5, - f64::from(pos[1]), - f64::from(pos[2]) + 0.5, - )); - self.respawn_config = None; - } else { - self.spawn = None; - self.respawn_config = Some(super::respawn_anchor::RespawnConfig { - dim: self.dim, - pos, - yaw, - forced: true, + // SetSpawnCommand: a forced point in the source's level, for each target. + let level = self.dim; + for &t in &targets { + self.for_player(t, |g| { + if level == Dim::Overworld { + g.spawn = Some(Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + )); + g.respawn_config = None; + } else { + g.spawn = None; + g.respawn_config = Some(super::respawn_anchor::RespawnConfig { + dim: level, + pos, + yaw, + forced: true, + }); + } }); } let dim = Text::literal(self.dim.id()); @@ -2596,6 +2614,44 @@ impl Game<'_> { }, }; let max = Self::int(ctx, "maxCount").unwrap_or(-1); + let counting = max == 0; + // ClearInventoryCommands.clearInventory: each player on their own. + let mut removed = 0i32; + let mut found = Vec::new(); + for &t in &targets { + let n = self + .for_player(t, |g| g.clear_matching(&predicate, max)) + .unwrap_or(0); + removed += n; + if n != 0 { + found.push(t); + } + } + if removed == 0 { + return Err(if targets.len() == 1 { + CommandError::new(Text::translate( + "clear.failed.single", + &[self.target_name(targets[0])], + )) + } else { + err("clear.failed.multiple", &[&targets.len()]) + }); + } + let kind = if counting { "test" } else { "success" }; + let (key, who) = match found[..] { + [only] => ("single", self.target_name(only)), + _ => ("multiple", Text::literal(found.len().to_string())), + }; + self.feedback(Text::translate( + &format!("commands.clear.{kind}.{key}"), + &[Text::literal(removed.to_string()), who], + )); + Ok(removed) + } + /// Inventory.clearOrCountMatchingItems for the player in place: `max` + /// of the matching items go (all when negative, none and only counted + /// when 0). Returns how many matched. + fn clear_matching(&mut self, predicate: &ItemInput, max: i32) -> i32 { let counting = max == 0; // Inventory slots 0..40: main, armor feet to head, off hand; // then clearOrCountMatchingItems visits the crafting grid and carried stack. @@ -2611,10 +2667,7 @@ impl Game<'_> { }; let matching: Vec = all(self) .iter() - .map(|s| { - s.as_ref() - .is_some_and(|s| self.stack_matches(&predicate, s)) - }) + .map(|s| s.as_ref().is_some_and(|s| self.stack_matches(predicate, s))) .collect(); let mut slots: Vec<&mut Option> = Vec::new(); slots.extend(self.inventory.iter_mut()); @@ -2644,25 +2697,7 @@ impl Game<'_> { } } } - if removed == 0 { - return Err(if targets.len() == 1 { - CommandError::new(Text::translate( - "clear.failed.single", - &[Text::literal(self.acting_player_name())], - )) - } else { - err("clear.failed.multiple", &[&targets.len()]) - }); - } - let kind = if counting { "test" } else { "success" }; - self.feedback(Text::translate( - &format!("commands.clear.{kind}.single"), - &[ - Text::literal(removed.to_string()), - Text::literal(self.acting_player_name()), - ], - )); - Ok(removed) + removed } /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { From cb97c5496e127edc5287914d0ad63f974a0158b2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:30:07 +0100 Subject: [PATCH 055/221] Raiders in a raid no longer count idle time twice as fast A raider's idle counter grew by 4 per tick while in a raid, so it dropped out of the raid after about 700 ticks instead of 1400 and could no longer be recruited sooner than in vanilla. Remove the extra tick added by the raid bookkeeping; the counter now grows by 3 like vanilla. --- crates/horizon-client/src/game/raids.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bedca5708..ce74e4e80 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -819,14 +819,11 @@ impl Game<'_> { if !alive { continue; } - // Raider.updateNoActionTime adds two per tick, and a raider - // fighting a player or golem in a raid is never idle. - if s.raid_id.is_some() { - m.ai.no_action_time = if target_player || target_golem { - 0 - } else { - m.ai.no_action_time + 1 - }; + // Raider.aiStep: a raider fighting a player or golem in a raid is + // never idle. The per-tick growth (+1 serverAiStep, +2 + // Raider.updateNoActionTime) is added by the mob's own step. + if s.raid_id.is_some() && (target_player || target_golem) { + m.ai.no_action_time = 0; } // Raider.aiStep: join the raid the raider stands in. if s.raid_id.is_none() From 0cc3f567fc6acdffbfa80c7de1a535f3c75c2564 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:30:29 +0100 Subject: [PATCH 056/221] Play the bubble pop sound when an air bubble bursts --- .../horizon-client/examples/probe/hud_fixture.rs | 1 + crates/horizon-client/src/game.rs | 13 +++++++++++++ crates/horizon-client/src/hud_layout.rs | 15 +++++++++++++++ 3 files changed, 29 insertions(+) diff --git a/crates/horizon-client/examples/probe/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs index a6f27fcda..5fc77309b 100644 --- a/crates/horizon-client/examples/probe/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -223,6 +223,7 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec { display_health: int("displayHealth", 0), last_health_time: millis - i64::from(int("lastHealthAgo", 0)), health_blink_time: i64::from(int("healthBlinkTime", 0)), + ..HealthHud::default() }; let kind = if has("minecraft:poison") { HeartKind::Poisoned diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..834befa5e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5275,6 +5275,19 @@ impl Game<'_> { }; let draws = self.health_hud.layout(&inputs, wi, hi); hud_layout::paint(&mut batch, atlas, &draws); + // Hud.playAirBubblePoppedSound: Player.playSound (PLAYERS), heard + // by this client only. + if let Some((volume, pitch)) = self.health_hud.bubble_pop_sound.take() { + let at = [p.position.x, p.position.y, p.position.z]; + let players = horizon_client::settings::SOUND_SOURCES + .iter() + .position(|s| *s == "player") + .unwrap_or(0); + let capture = self.audio.capture.take(); + self.audio + .play_on(players, "ui.hud.bubble_pop", Some(at), volume, pitch); + self.audio.capture = capture; + } } if contextual == ContextualBar::Locator { let draws = self.locator_bar_draws(wi, hi); diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs index 4b0f2fa82..ac8cd514e 100644 --- a/crates/horizon-client/src/hud_layout.rs +++ b/crates/horizon-client/src/hud_layout.rs @@ -485,6 +485,11 @@ pub struct HealthHud { /// `Util.getMillis()` of the last health change. pub last_health_time: i64, pub health_blink_time: i64, + /// `Hud.lastBubblePopSoundPlayed`. + pub last_bubble_pop_sound: i32, + /// The `ui.hud.bubble_pop` volume and pitch `playAirBubblePoppedSound` + /// asked for this frame; the caller plays it and clears it. + pub bubble_pop_sound: Option<(f32, f32)>, } pub struct HealthInputs { @@ -751,12 +756,22 @@ impl HealthHud { let popping = bubble(0); let delay = i32::from(air != 0 && i.under_water); let empty = 10 - bubble(delay); + if !i.under_water { + self.last_bubble_pop_sound = 0; + } for b in 1..=10 { let x = x_right - (b - 1) * 8 - 9; if b <= full { out.push(sprite("hud/air", x, y, 9, 9)); } else if full != popping && b == popping && i.under_water { out.push(sprite("hud/air_bursting", x, y, 9, 9)); + // Hud.playAirBubblePoppedSound. + if self.last_bubble_pop_sound != b { + let volume = 0.5 + 0.1 * (empty - 3 + 1).max(0) as f32; + let pitch = 1.0 + 0.1 * (empty - 5 + 1).max(0) as f32; + self.bubble_pop_sound = Some((volume, pitch)); + self.last_bubble_pop_sound = b; + } } else if b > 10 - empty { let wobble = if empty == 10 && i.tick % 2 == 0 { next(2) From 575cef1d26a290eec7536f4a7fe081771d44a732 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:30:38 +0100 Subject: [PATCH 057/221] Let a vindicator named Johnny attack other raiders too Vanilla's Johnny goal targets any living entity that can be attacked. Horizon skipped pillagers, vindicators, witches, evokers, illusioners and ravagers, so Johnny left them alone. Remove that filter. --- crates/horizon-client/src/mobs/illager.rs | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/mobs/illager.rs b/crates/horizon-client/src/mobs/illager.rs index 45ef076d3..c4693c182 100644 --- a/crates/horizon-client/src/mobs/illager.rs +++ b/crates/horizon-client/src/mobs/illager.rs @@ -13,18 +13,6 @@ use horizon_core::geometry::trig::Mth; use horizon_core::{geometry::Vec3, random::RandomSource}; use std::f32::consts::PI; -/// The species raiders do not fight (`Raider`'s allies). -fn raider(s: Species) -> bool { - matches!( - s, - Species::Pillager - | Species::Vindicator - | Species::Witch - | Species::Evoker - | Species::Illusioner - | Species::Ravager - ) -} fn targets(m: &mut Mob, villagers_seen: bool) { let mut hurt = HurtByTarget::new().alert(); hurt.ignore = vec![ @@ -78,10 +66,11 @@ pub fn register_vindicator(m: &mut Mob) { g.add(9, LookAtPlayer::new(3.0).probability(1.0)); g.add(10, LookAtPlayer::mobs(8.0)); targets(m, true); - // VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks anything. + // VindicatorJohnnyAttackGoal: a vindicator named Johnny attacks any + // living entity, other raiders included. m.ai.targets.add( 4, - NearestTarget::new(Prey::Filter(|s| !raider(s.species)), true) + NearestTarget::new(Prey::Filter(|_| true), true) .interval(0) .when(|m, _| m.custom_name.as_deref() == Some("Johnny")), ); From 9bc05faf53c169c8ae19ac2ee8f118c576927a62 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:30:54 +0100 Subject: [PATCH 058/221] Tamed wolves heal twice the food's nutrition --- crates/horizon-client/src/game/creatures.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d192a2b02..6f81189f6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2645,8 +2645,9 @@ impl Game<'_> { .items() .get(&item) .and_then(|i| i.food.as_ref()) - .map_or(2.0, |f| f.0 as f32); - // TamableAnimal.feed: playEatingSound, which wolves leave empty. + .map_or(2.0, |f| f.0 as f32 * 2.0); + // TamableAnimal.feed(.., 2.0F, 2.0F): heals twice the nutrition, + // then playEatingSound, which wolves leave empty. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; } From de1e5f729226070d11aaca39c2a6d248797fc029 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:31:10 +0100 Subject: [PATCH 059/221] Spin the player arrow on a Nether map Vanilla's MapItemSavedData.calculateRotation gives the arrow a changing rotation in the Nether. The player marker used the yaw there too, so it never spun. --- crates/horizon-client/src/game/maps.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 6da65c592..e87ba9cdd 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -774,9 +774,8 @@ impl Game<'_> { (d * 2.0 + 0.5) as i8 } }; - let y = f64::from(yaw); - let adjusted = if y < 0.0 { y - 8.0 } else { y + 8.0 }; - let rot = ((adjusted * 16.0 / 360.0) as i32 & 15) as u8; + // calculateRotation: the arrow spins in the Nether. + let rot = decoration_rotation(nether, game_time, f64::from(yaw)); let sprite = if inside { Some("map/decorations/player") } else if dx.abs() < 320.0 && dz.abs() < 320.0 { From 7d7a85d1845d0ef2f7ff8a2866f92054f68a732e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:31:28 +0100 Subject: [PATCH 060/221] Recruit nearby raiders only while the raid pathfinding goal runs Raiders recruited other raiders every 20 ticks whether or not they were heading for the raid. In vanilla the recruiting is part of PathfindToRaidGoal.tick, so a raider that has a target or carries a rider does not recruit. Do the recruiting from the goal's tick. --- crates/horizon-client/src/game/raids.rs | 10 ++++------ crates/horizon-client/src/mobs/raider.rs | 19 +++++++++++++++---- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index bedca5708..4c5eff980 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -791,7 +791,7 @@ impl Game<'_> { let has_rider = ridden.contains(&m.id); let target_golem = matches!(m.ai.target, Some(horizon_client::mobs::Who::Mob(t)) if golems.contains(&t)); let target_player = m.ai.target == Some(horizon_client::mobs::Who::Player); - let (health, age, range) = (m.health, m.age, m.attrs.follow_range); + let (health, range) = (m.health, m.attrs.follow_range); let raids = &mut self.raiding.raids; let s = m.extra.raider.get_or_insert_with(Box::default); s.rider = has_rider; @@ -837,11 +837,9 @@ impl Game<'_> { { joins.push((m.id, id, health)); } - // PathfindToRaidGoal.recruitNearby. - if s.active_raid - && !s.raid_over - && !s.in_village - && age % 20 == 0 + // PathfindToRaidGoal.tick: recruitNearby, only while the goal runs. + if std::mem::take(&mut s.recruit_due) + && s.active_raid && let Some(id) = s.raid_id { recruit.push((id, position)); diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index 6c3ab9b64..6096d04ad 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -38,6 +38,9 @@ pub struct State { pub in_village: bool, /// A dropped ominous banner this raider may fetch. pub banner_at: Option<[f64; 3]>, + /// `PathfindToRaidGoal.tick` ran its 20 tick recruitment: the game + /// recruits the raiders around this one. + pub recruit_due: bool, /// Beds around the raid's centre. pub homes: Option>>, /// A ravager carrying a raider, set every tick from `Extra::rider`. @@ -114,7 +117,7 @@ pub fn register(m: &mut Mob) { m.extra.raider = Some(Box::default()); m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595)); m.ai.goals.add(1, ObtainBanner); - m.ai.goals.add(3, PathfindToRaid); + m.ai.goals.add(3, PathfindToRaid::default()); m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0)); m.ai.goals.add(5, Celebration); } @@ -357,9 +360,11 @@ impl Goal for ObtainBanner { } /// `PathfindToRaidGoal`: outside the village, head for the raid's centre in -/// hops of up to 15 blocks. -#[derive(Clone, Debug)] -pub struct PathfindToRaid; +/// hops of up to 15 blocks, recruiting nearby raiders every 20 ticks. +#[derive(Clone, Debug, Default)] +pub struct PathfindToRaid { + recruitment_tick: i32, +} impl PathfindToRaid { fn valid(s: &State) -> bool { s.active_raid && !s.raid_over && !s.in_village @@ -380,6 +385,12 @@ impl Goal for PathfindToRaid { let Some(c) = state(m).map(|s| s.raid_center) else { return; }; + if m.age as i32 > self.recruitment_tick { + self.recruitment_tick = m.age as i32 + 20; + if let Some(s) = m.extra.raider.as_deref_mut() { + s.recruit_due = true; + } + } if m.ai.nav.is_done() { let to = [ f64::from(c[0]) + 0.5, From 74dc389321d923a047e245c2e91cbbb999a2b59d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:31:55 +0100 Subject: [PATCH 061/221] Keep the effect icons on screen over the pause menu, chat and other screens --- crates/horizon-client/src/game/potions.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 13eae7d3e..cdf084377 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -780,9 +780,28 @@ impl Game<'_> { } } } - /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row. + /// `Screen.showsActiveEffects`: the survival and creative inventories + /// draw their own effect list when `EffectsInInventory.canSeeEffects` + /// (32 or more pixels right of the screen). + fn screen_shows_active_effects(&self, batch: &HudBatch) -> bool { + let (ox, image_width) = match self.screen { + Screen::Inventory + if self.container.is_none() && self.craft_size == 2 && !self.mount_active() => + { + (self.inventory_origin(batch).0, 176) + } + Screen::Creative => ( + Self::creative_origin(batch).0, + horizon_client::creative::Creative::WIDTH as i32, + ), + _ => return false, + }; + batch.width as i32 - (ox as i32 + image_width + 2) >= 32 + } + /// `Hud.extractEffects`: icons top-right, beneficial row then harmful row; + /// every screen but the inventories keeps them. pub(super) fn draw_effect_icons(&self, batch: &mut HudBatch) { - if self.screen != Screen::Playing || self.potions.effects.list.is_empty() { + if self.potions.effects.list.is_empty() || self.screen_shows_active_effects(batch) { return; } let icons: Vec = self From c5a37c02de3101da524236010243244d278c5bd4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:32:01 +0100 Subject: [PATCH 062/221] Push sonic boom targets only when hit, by their knockback resistance --- .../examples/probe/mob_ai_probe.rs | 8 ++ crates/horizon-client/src/game/creatures.rs | 115 ++++++++++++------ crates/horizon-client/src/game/lan_mobs.rs | 4 + crates/horizon-client/src/mobs.rs | 9 ++ crates/horizon-client/src/mobs/warden.rs | 31 +---- 5 files changed, 104 insertions(+), 63 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..290d45371 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -568,6 +568,10 @@ fn print_heart( fn player_damage(e: &MobEvent) -> f32 { match e { MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount, + MobEvent::SonicBoom { + target: Who::Player, + .. + } => 10.0, _ => 0.0, } } @@ -579,6 +583,10 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { }; match e { MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, + MobEvent::SonicBoom { + target: Who::Player, + .. + } => true, // ServerExplosion.hurtEntities: within twice the radius every hit does damage. MobEvent::Explode(at, radius) => { let d = Vec3::new(at[0], at[1], at[2]) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 1f560af0d..c7b033c03 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -838,6 +838,44 @@ impl Game<'_> { } } } + /// Melee or ranged damage to another mob; whether the hit landed. + fn mob_hits_mob(&mut self, target: u32, amount: f32, source: Damage) -> bool { + let mut killed = false; + let mut hurt = false; + if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { + let hit = t.damage(amount, source); + hurt = hit; + if hit { + killed = !t.alive(); + // The hurt or death sound the mob raised. + let center = t.center(); + for event in std::mem::take(&mut t.outbox) { + if let MobEvent::Sound(s, _, volume, pitch) = event { + self.audio + .play(&format!("minecraft:{s}"), Some(center), volume, pitch); + } + } + } + } + if hurt + && let Some(Who::Mob(attacker)) = source.attacker + && let Some(m) = self + .mobs + .iter() + .find(|m| m.id == attacker && m.species() == Species::Axolotl) + { + self.audio.play( + "minecraft:entity.axolotl.attack", + Some([m.position.x, m.position.y, m.position.z]), + 1.0, + 1.0, + ); + } + if killed && let Some(Who::Mob(killer)) = source.attacker { + self.zombie_killed(killer, target); + } + hurt + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { @@ -926,43 +964,48 @@ impl Game<'_> { amount, source, } => { - let mut killed = false; - let mut hurt = false; - if let Some(t) = self.mobs.iter_mut().find(|m| m.id == target) { - let hit = t.damage(amount, source); - hurt = hit; - if hit { - killed = !t.alive(); - // The hurt or death sound the mob raised. - let center = t.center(); - for event in std::mem::take(&mut t.outbox) { - if let MobEvent::Sound(s, _, volume, pitch) = event { - self.audio.play( - &format!("minecraft:{s}"), - Some(center), - volume, - pitch, - ); - } - } + self.mob_hits_mob(target, amount, source); + } + MobEvent::SonicBoom { + target, + attacker, + from, + direction, + } => { + // SonicBoom: the push only follows a hit that landed, scaled + // by the target's KNOCKBACK_RESISTANCE. + let (hurt, resistance) = match target { + Who::Player => { + let hurt = self.mob_hits_player(10.0, from, "minecraft:sonic_boom"); + let resistance = self.player.as_mut().map_or(0.0, |p| { + p.attribute("minecraft:knockback_resistance").unwrap_or(0.0) + }); + (hurt, resistance) } - } - if hurt - && let Some(Who::Mob(attacker)) = source.attacker - && let Some(m) = self - .mobs - .iter() - .find(|m| m.id == attacker && m.species() == Species::Axolotl) - { - self.audio.play( - "minecraft:entity.axolotl.attack", - Some([m.position.x, m.position.y, m.position.z]), - 1.0, - 1.0, - ); - } - if killed && let Some(Who::Mob(killer)) = source.attacker { - self.zombie_killed(killer, target); + Who::Mob(id) => { + let source = Damage { + kind: DamageKind::SonicBoom, + attacker: Some(Who::Mob(attacker)), + from: Some(from), + }; + let hurt = self.mob_hits_mob(id, 10.0, source); + let resistance = self + .mobs + .iter() + .find(|m| m.id == id) + .map_or(0.0, |m| m.attrs.knockback_resistance); + (hurt, resistance) + } + }; + if hurt { + let horizontal = 2.5 * (1.0 - resistance); + let vertical = 0.5 * (1.0 - resistance); + let velocity = [ + direction[0] * horizontal, + direction[1] * vertical, + direction[2] * horizontal, + ]; + self.handle_mob_events(vec![MobEvent::Push { target, velocity }])?; } } MobEvent::FinishAdmiring { mob } => self.finish_admiring(mob), diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..88f98e3f6 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -66,6 +66,10 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { e, MobEvent::AttackPlayer(..) | MobEvent::DamagePlayer { .. } + | MobEvent::SonicBoom { + target: Who::Player, + .. + } | MobEvent::Push { target: Who::Player, .. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4b67f738f..49a11e75a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -961,6 +961,15 @@ pub enum MobEvent { target: Who, velocity: [f64; 3], }, + /// `SonicBoom`: 10 damage to the target, then a push along `direction` + /// (the unit vector from the warden's chest to the target's eyes) only + /// if the hit landed, less the target's knockback resistance. + SonicBoom { + target: Who, + attacker: u32, + from: [f64; 3], + direction: [f64; 3], + }, /// `EvokerWololoSpellGoal`: a blue sheep turns red. Wololo { mob: u32, diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11161ef7c..f6acb3d50 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -697,34 +697,11 @@ pub(super) fn tick_sonic_boom(m: &mut Mob, w: &MobWorld, events: &mut Vec events.push(MobEvent::DamagePlayer { - amount: 10.0, - from, - kind: "minecraft:sonic_boom", - }), - Who::Mob(id) => events.push(MobEvent::AttackMob { - target: id, - amount: 10.0, - source: Damage { - kind: DamageKind::SonicBoom, - attacker: Some(Who::Mob(m.id)), - from: Some(from), - }, - }), - } - let horizontal = 2.5 * (1.0 - resistance); - let vertical = 0.5 * (1.0 - resistance); - events.push(MobEvent::Push { + events.push(MobEvent::SonicBoom { target, - velocity: [ - normal[0] * horizontal, - normal[1] * vertical, - normal[2] * horizontal, - ], + attacker: m.id, + from: at(m), + direction: normal, }); } /// `Warden.tick` on the client: the heartbeat (pitched by the client's copy From f1181d4a250b8d1a76dadfbadbbf714642492e17 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:32:16 +0100 Subject: [PATCH 063/221] Trial chamber mobs spawn with the gear their spawner's equipment table gives --- crates/horizon-client/src/game/mob_gear.rs | 56 +++++++++++++++++++ crates/horizon-client/src/game/spawner.rs | 27 +++++---- .../horizon-client/src/game/trial_spawner.rs | 2 +- crates/horizon-client/src/mobs/finalize.rs | 22 ++++++++ crates/horizon-client/src/mobs/spawner.rs | 28 ++++++++++ 5 files changed, 124 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game/mob_gear.rs b/crates/horizon-client/src/game/mob_gear.rs index 809b250dc..7dc529f17 100644 --- a/crates/horizon-client/src/game/mob_gear.rs +++ b/crates/horizon-client/src/game/mob_gear.rs @@ -5,11 +5,15 @@ use super::Game; use horizon_client::{ mobs::{ Species, + drops::{self, SLOTS}, + finalize::equip_stack, gear::{self, ARMOR, MAIN}, + spawner::equipment_table, }, raid::{self, RaiderType}, }; use horizon_core::random::RandomSource; +use horizon_world::{loot::EntityLootParams, nbt::Tag}; /// `EnchantmentsByCostWithDifficulty` of `mob_spawn_equipment`. const MIN_COST: i32 = 5; @@ -47,6 +51,58 @@ fn slot_item(m: &horizon_client::mobs::Mob, slot: usize) -> Option { + /// `Mob.equip(EquipmentTable)` for a spawner's `equipment`: the loot table + /// (the mob as `this`, its random sequence) is rolled and each stack goes + /// in the slot `EquipmentUser.resolveSlot` picks, with the table's drop + /// chance for that slot. + pub(super) fn equip_from_table(&mut self, id: u32, table: &Tag) { + let Some((name, chances)) = equipment_table(table) else { + return; + }; + let Some(loot) = horizon_client::structure_blocks::loot_data(&self.options.resources) + else { + return; + }; + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + if !loot.has_table(&name) { + return; + } + let params = EntityLootParams { + this: drops::loot_entity(m, None), + ..EntityLootParams::default() + }; + let seed = self.level.seed; + let stacks = match loot.random_sequence(&name) { + Some(sequence) => { + let random = self.rand_sequences.get(sequence, seed); + loot.roll_entity(&name, random, ¶ms) + } + None => loot.roll_entity(&name, &mut self.world.random, ¶ms), + }; + let mut inserted: Vec = Vec::new(); + for stack in stacks.iter().filter(|s| !s.is_empty()) { + // `resolveSlot`: an `equippable` item goes in its own slot, any + // other in the main hand, each slot once. + let slot = match self + .res + .items() + .get(&stack.item) + .and_then(|i| i.equip_slot.as_deref()) + { + Some(name) => SLOTS.iter().position(|s| *s == name), + None => Some(0), + }; + let Some(slot) = slot.filter(|s| !inserted.contains(s)) else { + continue; + }; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + equip_stack(m, slot, stack, chances[slot]); + } + inserted.push(slot); + } + } /// `Mob.populateDefaultEquipmentEnchantments`: the weapon one time in /// four and each piece of armour one time in two, scaled by the local /// difficulty, enchanted as if at an enchanting table of cost 5 to 22. diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 538cb39e7..de367a37c 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -21,10 +21,11 @@ type Pos = (i32, i32, i32); /// What a spawner tick decided to add, created once the level is free. pub(super) enum Planned { - /// `finalizeSpawn` ran on a fresh mob. - Finalized(Mob), - /// A mob loaded from the spawn data (with its passengers). - Loaded(Tag), + /// `finalizeSpawn` ran on a fresh mob; the spawn data's `equipment`. + Finalized(Mob, Option), + /// A mob loaded from the spawn data (with its passengers) and its + /// `equipment`. + Loaded(Tag, Option), } /// What the spawner code keeps between ticks. @@ -120,18 +121,24 @@ impl Game<'_> { for (i, plan) in planned.into_iter().enumerate() { let provisional = u32::MAX - i as u32; let id = match plan { - Planned::Finalized(mut mob) => { + Planned::Finalized(mut mob, equipment) => { self.next_entity += 1; mob.id = self.next_entity; let id = mob.id; self.mobs.push(mob); self.enchant_spawn_equipment(id); self.spawn_jockeys(id, true); - Some(id) + Some((id, equipment)) + } + Planned::Loaded(tag, equipment) => { + self.load_mob(tag, None).map(|id| (id, equipment)) } - Planned::Loaded(tag) => self.load_mob(tag, None), }; - if let Some(id) = id { + if let Some((id, equipment)) = id { + // `nextSpawnData.getEquipment().ifPresent(mob::equip)`. + if let Some(table) = equipment { + self.equip_from_table(id, &table); + } ids.insert(provisional, id); } } @@ -169,7 +176,7 @@ impl Game<'_> { mob.previous_head_yaw = 0.0; } let bounds = mob.bounds(); - planned.push(Planned::Finalized(mob)); + planned.push(Planned::Finalized(mob, r.equipment.cloned())); bounds } else { // A UUID already in the level is refused. @@ -197,7 +204,7 @@ impl Game<'_> { let tag = Tag::Compound(tag); let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), 0)?; let bounds = mob.bounds(); - planned.push(Planned::Loaded(tag)); + planned.push(Planned::Loaded(tag, r.equipment.cloned())); bounds }; l.pending.borrow_mut().push(bounds); diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs index 42a26c6e4..d076671ea 100644 --- a/crates/horizon-client/src/game/trial_spawner.rs +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -163,7 +163,7 @@ impl Game<'_> { let mut spawn = |l: &GameLevel, r: &SpawnerSpawn| { let added = l.game.plan_spawner_mob(l, r, &mut planned)?; let uuid = match planned.last_mut() { - Some(Planned::Loaded(Tag::Compound(tag))) => { + Some(Planned::Loaded(Tag::Compound(tag), _)) => { let tag_uuid = horizon_client::entity_nbt::uuid(&Tag::Compound(tag.clone())); tag_uuid.unwrap_or_else(|| { diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 4eeed885b..7cd8926c0 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -829,6 +829,28 @@ pub fn set_item(m: &mut Mob, slot: usize, id: &str) { } gear::set(m, gear_slot(slot), Vec::new()); } +/// `EquipmentUser.equip` for one rolled stack: `setItemSlot` puts the item in +/// `slot` with its own enchantments, then the slot's drop chance is stored +/// when the table names one. +pub fn equip_stack( + m: &mut Mob, + slot: usize, + stack: &horizon_world::loot::LootStack, + drop_chance: Option, +) { + set_item(m, slot, &stack.item); + if slot <= HEAD { + let levels = stack + .enchantments + .iter() + .map(|(id, level)| (Arc::from(id.as_str()), (*level).max(0) as u32)) + .collect(); + gear::set(m, gear_slot(slot), levels); + } + if let Some(chance) = drop_chance { + set_drop_chance(m, slot, chance); + } +} /// `Mob.setDropChance`. pub fn set_drop_chance(m: &mut Mob, slot: usize, chance: f32) { let c = m diff --git a/crates/horizon-client/src/mobs/spawner.rs b/crates/horizon-client/src/mobs/spawner.rs index 78b091b7b..f5e633226 100644 --- a/crates/horizon-client/src/mobs/spawner.rs +++ b/crates/horizon-client/src/mobs/spawner.rs @@ -152,6 +152,34 @@ pub(crate) fn cube_scale(id: &str, entity: &Compound) -> f32 { .map_or(1, |size| (size as i32).saturating_add(1).clamp(1, 127)) as f32 } +/// `EquipmentTable.CODEC`: the loot table and the drop chance of each +/// `EquipmentSlot` (`drops::SLOTS` order) the table names, `slot_drop_chances` +/// being one number for every slot or a map by slot name. +pub fn equipment_table(tag: &Tag) -> Option<(String, [Option; 8])> { + let chance = |t: &Tag| match t { + Tag::Float(v) => Some(f32::from_bits(*v)), + Tag::Double(v) => Some(f64::from_bits(*v) as f32), + Tag::Byte(v) => Some(f32::from(*v)), + Tag::Short(v) => Some(f32::from(*v)), + Tag::Int(v) => Some(*v as f32), + Tag::Long(v) => Some(*v as f32), + _ => None, + }; + let Some(Tag::String(table)) = tag.get("loot_table") else { + return None; + }; + let mut chances = [None; 8]; + match tag.get("slot_drop_chances") { + Some(Tag::Compound(map)) => { + for (i, slot) in super::drops::SLOTS.iter().enumerate() { + chances[i] = map.get(&JavaString::from(*slot)).and_then(chance); + } + } + Some(all) => chances = [Some(chance(all)?); 8], + None => {} + } + Some((table.to_string_lossy(), chances)) +} /// A whole number from any numeric tag (`NumericTag.intValue`: floats floor). pub(crate) fn number(tag: Option<&Tag>) -> Option { Some(match tag? { From b65b0a6a7d7b481b35c1a844e641908c3ea68a95 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:32:59 +0100 Subject: [PATCH 064/221] Dim the sun and moon in rain and turn the moon texture the right way up --- crates/horizon-client/src/game.rs | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..5d58a3ade 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7921,24 +7921,34 @@ impl Game<'_> { } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. /// Returns the sun and moon quads, and the stars' frame and brightness - /// (the renderer keeps their geometry, built once). + /// (the renderer keeps their geometry, built once). The bodies fade with + /// the rain (`rainBrightness = 1 - rainLevel`, their colour's alpha). fn celestial_geometry( &self, sky: &horizon_client::environment::Sky, + rain: f32, ) -> (Vec, Option<(glam::Mat4, f32)>) { + let body_color = + 0x00FF_FFFF | (((1.0 - rain).clamp(0.0, 1.0) * 255.0).round() as u32) << 24; let mut out = Vec::new(); let atlas = &self.gui.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) }; - let mut body = |name: &str, angle: f32, size: f32, color: u32| { + let mut body = |name: &str, angle: f32, size: f32, moon: bool| { let Some(r) = atlas.sprites.get(name).copied() else { return; }; let m = frame(angle); let corners = [(-size, -size), (size, -size), (size, size), (-size, size)]; - let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; + // buildCelestialQuad (sun) vs buildMoonPhases: the moon's UVs run + // the other way round. + let uv = if moon { + [[r.u1, r.v1], [r.u0, r.v1], [r.u0, r.v0], [r.u1, r.v0]] + } else { + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]] + }; for ((x, z), uv) in corners.iter().zip(uv) { let p = m.transform_point3(glam::Vec3::new(*x, 100.0, *z)); out.push(Vertex { @@ -7946,17 +7956,12 @@ impl Game<'_> { pos: p.to_array(), uv, layer: 2, - color, + color: body_color, light: 0, }); } }; - body( - "environment/celestial/sun", - sky.sun_angle, - 30.0, - 0xFFFF_FFFF, - ); + body("environment/celestial/sun", sky.sun_angle, 30.0, false); let phases = [ "full_moon", "waning_gibbous", @@ -7972,7 +7977,7 @@ impl Game<'_> { &format!("environment/celestial/moon/{phase}"), sky.moon_angle, 20.0, - 0xFFFF_FFFF, + true, ); // SkyRenderer.renderStars: the static star buffer on the same frame. let stars = @@ -10641,7 +10646,7 @@ impl Game<'_> { && self.potions.effects.get("blindness").is_none() { // Camera.doesMobEffectBlockSky: no sun, moon or stars. - self.celestial_geometry(&sky) + self.celestial_geometry(&sky, rain) } else if self.dim == Dim::End && self.settings.horizon.sky { (self.end_flash_geometry(), None) } else { From 849b5b663bbeb3cf04326b5726df1e2e57be38cf Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:33:09 +0100 Subject: [PATCH 065/221] Let a sculk catalyst take the experience of mobs killed without a player --- crates/horizon-client/src/game/creatures.rs | 5 +++-- crates/horizon-client/src/mobs/drops.rs | 18 +++++++++++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d192a2b02..36bd1150a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -685,11 +685,12 @@ impl Game<'_> { let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby - // takes the experience (before the loot is dropped). + // takes the experience (before the loot is dropped). It takes what + // would drop, whoever killed the mob. self.sculk_mob_died(m); let consumed = self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| { - if by_player { + if horizon_client::mobs::drops::drops_experience(&dying) { horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32 } else { 0 diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index c7b1c77e1..d1b0e8b9a 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -471,13 +471,7 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec false, - Species::Hoglin => true, - s if is_monster(s) => true, - _ => !m.is_baby(), - }; - if killed_by_player && drops_experience && d.mob_drops { + if killed_by_player && drops_experience(m) && d.mob_drops { let mut amount = base_experience(m); while amount > 0 { let value = orb_value(amount); @@ -501,6 +495,16 @@ fn roll( None => Vec::new(), } } +/// `LivingEntity.shouldDropExperience`: babies drop none, except monsters and +/// hoglins; tadpoles never do. +pub fn drops_experience(m: &Mob) -> bool { + match m.species() { + Species::Tadpole => false, + Species::Hoglin => true, + s if is_monster(s) => true, + _ => !m.is_baby(), + } +} /// `getBaseExperienceReward` (no vanilla enchantment changes mob experience). pub fn base_experience(m: &mut Mob) -> i32 { use Species as S; From 8c0ed0e591d7abe2d5a971ad8e6929c37283666b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:33:24 +0100 Subject: [PATCH 066/221] Let a comparator read an item frame through a block A comparator behind a solid block now reads the item frame on its far side (rotation + 1, or 0 when empty), and updates when the frame's item or rotation changes. --- crates/horizon-client/src/game.rs | 17 +++++++++++++++++ crates/horizon-client/src/game/frames.rs | 14 ++++++++++++++ crates/horizon-world/src/level/mod.rs | 6 ++++++ crates/horizon-world/src/level/redstone.rs | 10 ++++++++-- 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..083c9c85e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -545,6 +545,8 @@ struct GameLevel<'w> { player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, + /// The item frames a comparator reads through a conductor. + item_frames: &'w [horizon_client::entities::ItemFrame], /// The other entities that keep blocks from being placed into them. blockers: Blockers<'w>, biomes: &'w Biomes, @@ -706,6 +708,20 @@ impl LevelAccess for GameLevel<'_> { } machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } + fn item_frame_analog_output(&self, pos: BlockPos, facing: Direction) -> Option { + let mut frames = self + .item_frames + .iter() + .filter(|f| f.pos == [pos.x, pos.y, pos.z] && f.facing == facing as u8); + let frame = frames.next().filter(|_| frames.next().is_none())?; + // ItemFrame.getAnalogOutput. + Some( + frame + .item + .as_ref() + .map_or(0, |_| i32::from(frame.rotation % 8) + 1), + ) + } fn block_entity_signal( &self, pos: BlockPos, @@ -2541,6 +2557,7 @@ impl Game<'_> { }; let mut level = GameLevel { cart_boxes, + item_frames: &self.item_frames, blockers, world: &mut self.world, facts: self.res.facts(), diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index d08c5f283..9e18b2cb3 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -7,6 +7,7 @@ use horizon_assets::{bake::bake_model, model::CuboidModel, resolve::ModelLibrary use horizon_client::{entities::ItemFrame, items::ItemStack, mesher::Vertex}; use horizon_core::{ geometry::{Aabb, Vec3}, + position::BlockPos, random::RandomSource, }; use std::sync::Arc; @@ -223,6 +224,7 @@ impl Game<'_> { } let p = self.item_frames[i].pos; self.world.modified.insert((p[0] >> 4, p[2] >> 4)); + self.frame_output_changed(p); self.swing_arm(); true } @@ -255,8 +257,17 @@ impl Game<'_> { } self.drop_frame_items(&f, with_frame, true); self.world.modified.insert((f.pos[0] >> 4, f.pos[2] >> 4)); + if f.item.is_some() { + self.frame_output_changed(f.pos); + } true } + /// `ItemFrame.setItem` / `setRotation`: `updateNeighbourForOutputSignal`, so + /// the comparators reading the frame take its new signal. + fn frame_output_changed(&mut self, pos: [i32; 3]) { + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.update_neighbour_for_output_signal(level, ticks, at)); + } /// `ItemFrame.dropItem`: the frame (when breaking) and the held item. fn drop_frame_items(&mut self, f: &ItemFrame, with_frame: bool, by_player: bool) { if !self.ui.rules.bool("entity_drops") || (by_player && self.creative) { @@ -300,6 +311,9 @@ impl Game<'_> { self.audio .play(&sound(&f, "break"), Some(center(&f)), 1.0, 1.0); self.drop_frame_items(&f, true, false); + if f.item.is_some() { + self.frame_output_changed(f.pos); + } continue; } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index c81bdf369..f06771a06 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -372,6 +372,12 @@ pub trait LevelAccess { ) -> i32 { 0 } + /// `ItemFrame.getAnalogOutput` of the one item frame in the block at + /// `pos` that faces `facing` (`ComparatorBlock.getItemFrame`), or None when + /// there is not exactly one. + fn item_frame_analog_output(&self, _pos: BlockPos, _facing: Direction) -> Option { + None + } /// `ContainerOpenersCounter.recheckOpenCount` for the chest or ender chest /// block entity at `pos`: recounts its openers and returns the previous /// and new counts (the caller plays open/close effects when they change), diff --git a/crates/horizon-world/src/level/redstone.rs b/crates/horizon-world/src/level/redstone.rs index 92f9059e5..bebf5d826 100644 --- a/crates/horizon-world/src/level/redstone.rs +++ b/crates/horizon-world/src/level/redstone.rs @@ -490,8 +490,14 @@ impl Sim<'_, L> { } else if result < 15 && self.is_redstone_conductor(target_state, target) { let further = rel(target, facing); let further_state = self.state(further); - if b.has_flag(further_state, state_flags::ANALOG_OUTPUT) { - result = self.analog_output(further_state, further, facing.opposite()); + let block = b + .has_flag(further_state, state_flags::ANALOG_OUTPUT) + .then(|| self.analog_output(further_state, further, facing.opposite())); + // ComparatorBlock.getInputSignal: an item frame behind the + // conductor counts too, the larger signal winning. + let frame = self.level.item_frame_analog_output(further, facing); + if let Some(signal) = frame.into_iter().chain(block).max() { + result = signal; } } } From b5a735c8d176f0ea15535c450bf4d548c1d69ffe Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:33:51 +0100 Subject: [PATCH 067/221] Let tame parrots follow their owner and sit when told to A tamed parrot ignored its owner: it never followed, and right-clicking it did nothing. Give the parrot the goals of Parrot.registerGoals (SitWhenOrderedToGoal, FollowOwnerGoal 1.0, 5.0, 1.0), let the owner toggle sitting with a click while it stands on the ground, and keep the owner and sitting state in the save file and in the data a guest gets. --- crates/horizon-client/src/entity_nbt.rs | 13 +++++++++++++ crates/horizon-client/src/game/creatures.rs | 15 +++++++++++++++ crates/horizon-client/src/game/lan.rs | 7 +++++++ crates/horizon-client/src/mobs/ai.rs | 1 + crates/horizon-client/src/mobs/tame.rs | 11 +++++++++++ 5 files changed, 47 insertions(+) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..6c7fd1d5a 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -246,6 +246,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.entry("sound_variant".into()) .or_insert_with(|| string("minecraft:classic")); } + "minecraft:parrot" => { + if let Some(owner) = m.extra.owner { + map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); + } else { + map.remove(&"Owner".into()); + } + map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); + } "minecraft:wolf" => { if let Some(owner) = m.extra.owner { map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); @@ -773,6 +781,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - .unwrap_or(0) as u8; } } + if m.species() == crate::mobs::Species::Parrot { + m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); + m.extra.tame = m.extra.owner.is_some(); + m.extra.sitting = flag(tag, "Sitting"); + } if m.species() == crate::mobs::Species::Wolf { let health = m.health; m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d192a2b02..8eb4cc911 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2559,6 +2559,12 @@ impl Game<'_> { .items() .get(&item) .is_some_and(|i| i.max_damage > 0); + let parrot_poisonous = self + .res + .items() + .item_tags + .get("minecraft:parrot_poisonous_food") + .is_some_and(|t| t.contains(&*item)); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2764,6 +2770,15 @@ impl Game<'_> { m.position.z.floor() as i32 >> 4, )); } + // Parrot.mobInteract: the owner makes a tame parrot on the ground + // sit or stand (poisonous food is handled apart). + Species::Parrot if m.extra.tame && m.on_ground && !parrot_poisonous => { + m.extra.sitting = !m.extra.sitting; + self.world.modified.insert(( + m.position.x.floor() as i32 >> 4, + m.position.z.floor() as i32 >> 4, + )); + } Species::Cat if !m.extra.tame && is_food => { consume = true; m.persistent = true; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..72345970b 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -231,6 +231,13 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(0))); } + "minecraft:parrot" => { + // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. + let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 }; + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags))); + } + } "minecraft:cat" | "minecraft:wolf" => { // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 }; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..d30cc56ad 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -178,6 +178,7 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + Family::Generic if m.species() == Species::Parrot => super::tame::register_parrot(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1e725df80..0043ff9ef 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -100,6 +100,17 @@ pub fn register(m: &mut Mob) { ), ); } +/// `Parrot.registerGoals`: a tamed parrot sits when told to and follows its +/// owner from five blocks away (the wander and the shoulder come as they are). +pub fn register_parrot(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, TamePanic(Panic::new(1.25))); + g.add(0, Float); + g.add(1, LookAtPlayer::new(8.0)); + g.add(2, SitWhenOrdered); + g.add(2, FollowOwner::new(1.0, 5.0, 1.0)); + g.add(2, Stroll::avoiding_water(1.0)); +} /// `Wolf.PREY_SELECTOR`: sheep, rabbits and foxes. fn wolf_prey(s: &super::Seen) -> bool { matches!(s.species, Species::Sheep | Species::Rabbit | Species::Fox) From bc2dd35cc34c84b4048fcbdc704897bc266c3ecb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:33:57 +0100 Subject: [PATCH 068/221] Raise the held item name and action bar above extra heart, armor and mount rows --- .../horizon-client/examples/probe/hud_fixture.rs | 1 + .../examples/probe/hud_fixture/kinds.rs | 4 ++-- crates/horizon-client/src/game.rs | 13 +++++++++++-- crates/horizon-client/src/game/titles.rs | 9 ++++++--- crates/horizon-client/src/hud_layout.rs | 10 ++++++++++ crates/horizon-client/src/hud_overlays.rs | 15 +++++++++++---- 6 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/examples/probe/hud_fixture.rs b/crates/horizon-client/examples/probe/hud_fixture.rs index a6f27fcda..5fc77309b 100644 --- a/crates/horizon-client/examples/probe/hud_fixture.rs +++ b/crates/horizon-client/examples/probe/hud_fixture.rs @@ -223,6 +223,7 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec { display_health: int("displayHealth", 0), last_health_time: millis - i64::from(int("lastHealthAgo", 0)), health_blink_time: i64::from(int("healthBlinkTime", 0)), + ..HealthHud::default() }; let kind = if has("minecraft:poison") { HeartKind::Poisoned diff --git a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs index 9ba66abe1..f45c122fa 100644 --- a/crates/horizon-client/examples/probe/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/probe/hud_fixture/kinds.rs @@ -101,7 +101,7 @@ fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { } let partial = float(c, "partial", 0.0); let bg = background(c); - let mut out = t.overlay_message(w, h, partial, &atlas.font, bg); + let mut out = t.overlay_message(w, h, 39, partial, &atlas.font, bg); out.extend(t.title(w, h, partial, &atlas.font, bg)); out } @@ -129,7 +129,7 @@ fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { } let mode = c["gameMode"].as_str().unwrap_or("survival"); let can_hurt = mode == "survival" || mode == "adventure"; - highlight.draw(w, h, can_hurt, &atlas.font, background(c)) + highlight.draw(w, h, 39, can_hurt, &atlas.font, background(c)) } fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..c3cfa51ee 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5133,6 +5133,9 @@ impl Game<'_> { let spectator = self.spectator(); let (wi, hi) = (w as i32, h as i32); let show_hud = !self.ui.hide_gui; + // max(Hud.leftHeight, Hud.rightHeight) after the bars: the item name and + // the action bar sit above it. + let mut bar_height = 39; if show_hud { self.draw_spyglass(&mut batch); // Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth / @@ -5202,6 +5205,8 @@ impl Game<'_> { contextual == ContextualBar::JumpableVehicle, ) }; + // Without the survival bars only the mount's hearts raise it. + bar_height = 39 + 10 * ((vehicle_hearts + 9) / 10); if contextual == ContextualBar::Locator { let (sprite, [x, y, w, h]) = horizon_client::locator_bar::background(wi, hi); horizon_client::ui::nine_slice( @@ -5275,20 +5280,24 @@ impl Game<'_> { }; let draws = self.health_hud.layout(&inputs, wi, hi); hud_layout::paint(&mut batch, atlas, &draws); + bar_height = self + .health_hud + .left_height + .max(self.health_hud.right_height); } if contextual == ContextualBar::Locator { let draws = self.locator_bar_draws(wi, hi); hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { - self.draw_selected_name(&mut batch, !self.creative); + self.draw_selected_name(&mut batch, bar_height, !self.creative); } } // Hud.extractSleepOverlay: over all health/food bars, under titles and chat. let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32); hud_layout::paint(&mut batch, &self.gui.atlas, &draws); if show_hud { - self.draw_titles(&mut batch); + self.draw_titles(&mut batch, bar_height); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); } diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index cbae1f6b4..e7964165b 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -12,12 +12,14 @@ use horizon_client::{ impl Game<'_> { /// `Hud.extractOverlayMessage` and `extractTitle`. - pub(super) fn draw_titles(&self, batch: &mut HudBatch) { + pub(super) fn draw_titles(&self, batch: &mut HudBatch, bar_height: i32) { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); let font = &self.gui.atlas.font; - let mut draws = self.titles.overlay_message(w, h, partial, font, background); + let mut draws = self + .titles + .overlay_message(w, h, bar_height, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); hud_layout::paint(batch, &self.gui.atlas, &draws); } @@ -49,10 +51,11 @@ impl Game<'_> { .tick(held, f64::from(self.settings.notification_display_time)); } /// `Hud.extractSelectedItemName`. - pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, can_hurt: bool) { + pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, bar_height: i32, can_hurt: bool) { let draws = self.tool_highlight.draw( batch.width as i32, batch.height as i32, + bar_height, can_hurt, &self.gui.atlas.font, self.settings.text_background(0.0), diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs index 4b0f2fa82..42347d877 100644 --- a/crates/horizon-client/src/hud_layout.rs +++ b/crates/horizon-client/src/hud_layout.rs @@ -485,6 +485,11 @@ pub struct HealthHud { /// `Util.getMillis()` of the last health change. pub last_health_time: i64, pub health_blink_time: i64, + /// `Hud.leftHeight` and `rightHeight` once the health, armor, food, mount + /// and air layers have run; the selected item name and the action bar sit + /// above them. + pub left_height: i32, + pub right_height: i32, } pub struct HealthInputs { @@ -645,6 +650,9 @@ impl HealthHud { let rows = ceil((max_health + absorption as f32) / 2.0 / 10.0); let row_height = (10 - (rows - 2)).max(3); let mut y_air = y_base - 10; + self.left_height = 39 + (rows - 1) * row_height + 10 + if i.armor > 0 { 10 } else { 0 }; + // The mount's heart rows (`extractVehicleHealth`); food adds its row below. + self.right_height = 39 + 10 * ((i.vehicle_hearts + 9) / 10); let offset_index = if i.regeneration { i.tick % ceil(max_health + 5.0) } else { @@ -739,11 +747,13 @@ impl HealthHud { } } y_air -= 10; + self.right_height += 10; } // Hud.extractAirBubbles. let max_air = i.max_air.max(1); let air = i.air.clamp(0, max_air); if i.under_water || air < max_air { + self.right_height += 10; let rows = (f64::from(i.vehicle_hearts) / 10.0).ceil() as i32; let y = y_air - (rows - 1) * 10; let bubble = |offset: i32| ceil(((air + offset) * 10) as f32 / max_air as f32); diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index ebd860e08..d28e07324 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -275,11 +275,13 @@ impl Titles { } } } - /// `Hud.extractOverlayMessage`. + /// `Hud.extractOverlayMessage`; `bar_height` is + /// `max(leftHeight, rightHeight)`. pub fn overlay_message( &self, w: i32, h: i32, + bar_height: i32, partial: f32, font: &Font, background: u32, @@ -295,9 +297,12 @@ impl Titles { let alpha = ((t * 255.0 / 20.0) as i32).min(255); if alpha > 0 { let message = message.resolve_legacy(); + // The bars' height plus the gap between the item name (59) and the + // overlay (68), at least the default level. + let y_shift = bar_height + (68 - 59); out.push(GuiDraw::Push(vec![PoseOp::Translate( (w / 2) as f32, - (h - 68) as f32, + (h - y_shift.max(68)) as f32, )])); let color = if self.overlay_animated { hsv_to_argb(t / 50.0, 0.7, 0.6, alpha as u32) @@ -415,11 +420,13 @@ impl ToolHighlight { self.last = selected; } /// `Hud.extractSelectedItemName`; `can_hurt` is - /// `gameMode.canHurtPlayer()` (survival and adventure). + /// `gameMode.canHurtPlayer()` (survival and adventure) and `bar_height` + /// is `max(leftHeight, rightHeight)`. pub fn draw( &self, w: i32, h: i32, + bar_height: i32, can_hurt: bool, font: &Font, background: u32, @@ -440,7 +447,7 @@ impl ToolHighlight { } let str_width = width(font, &name); let x = (w - str_width) / 2; - let mut y = h - 59; + let mut y = h - bar_height.max(59); if !can_hurt { y += 14; } From b8d0590d6d56d3ea14d54255d865d17c212bb880 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:34:47 +0100 Subject: [PATCH 069/221] Lightning flash: mix the sky colour toward the flash tint instead of replacing it --- crates/horizon-client/src/game.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..5e4b36ebc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10517,8 +10517,11 @@ impl Game<'_> { horizon_client::environment::apply_weather(&mut sky, rain, thunder); self.end_flash_sky(&mut sky, alpha); if self.flash > 0 && !self.settings.file.bool("hideLightningFlashes") { - // Lightning flash brightens the sky (LevelRenderer skyFlashTime). - sky.sky_color = [0.9, 0.9, 1.0]; + // ClientLevel's flash layer while skyFlashTime > 0: the sky colour + // moves 22% of the way to (0.8, 0.8, 1.0). + let flash = [0.8, 0.8, 1.0]; + sky.sky_color = + std::array::from_fn(|i| sky.sky_color[i] + (flash[i] - sky.sky_color[i]) * 0.22); sky.sky_light_factor = 1.0; } // FishingHookRenderer's line, then DebugRenderer: chunk borders and From 4d9ead721e547a3a4983ebf738c316674be1c55b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:36:35 +0100 Subject: [PATCH 070/221] Point the recovery compass at the player's last death The local player's last death location is now recorded, saved as LastDeathLocation, taken from the Login and Respawn packets on the server thread, and given to the item owner. --- crates/horizon-client/src/game.rs | 3 ++ crates/horizon-client/src/game/item_draw.rs | 5 ++++ crates/horizon-client/src/game/lan_actions.rs | 2 +- crates/horizon-client/src/game/remote.rs | 6 ++++ crates/horizon-client/src/lan/guest.rs | 2 +- crates/horizon-client/src/lan/hub.rs | 28 +++++++++---------- crates/horizon-client/src/lan/playerdata.rs | 2 ++ crates/horizon-client/src/save.rs | 21 ++++++++++++++ 8 files changed, 53 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..8788c8f2b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4587,6 +4587,9 @@ impl Game<'_> { let feet = [player.position.x, player.position.y, player.position.z]; let at = [feet[0], feet[1] + 1.32, feet[2]]; let killer = self.combat_killer_kind(); + // Player.die: the dimension and block of the death. + self.level.last_death = + Some((self.dim.id().to_owned(), feet.map(|v| v.floor() as i32))); self.death_message(); // ServerPlayer.die: deaths, and the time-since counters restart. self.stats.custom("deaths", 1); diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..ce3757305 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -247,6 +247,11 @@ impl Game<'_> { owner.main_arm_left = self.settings.main_hand_left; owner.is_local_player = true; owner.is_view_entity = true; + owner.last_death_location = self + .level + .last_death + .clone() + .map(|(dimension, pos)| GlobalPos { dimension, pos }); if let (Some((slot, ticks)), Some(stack)) = (self.using, stack) && self.stack_in(slot) == Some(stack) { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..20fbdf9af 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2009,7 +2009,7 @@ impl Game<'_> { let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; - g.last_death = Some(g.position.map(|v| v.floor() as i32)); + g.last_death = Some((g.dimension.clone(), g.position.map(|v| v.floor() as i32))); let (id, at) = (g.entity_id, g.position); let reward = Experience { level: g.xp_level, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..03f5cc554 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -995,6 +995,12 @@ impl Game<'_> { r.predictions.clear(); self.set_mode_id(spawn.game_type); self.dim = Dim::from_id(&spawn.dimension); + // ClientPacketListener.handleLogin / handleRespawn: the server's + // Player.getLastDeathLocation, for the recovery compass. + self.level.last_death = spawn + .last_death + .as_ref() + .map(|d| (d.dimension.clone(), d.pos)); if !same { let mut streaming = Streaming::new( Arc::new(NoTerrain), diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 7e43cf04e..23e1efbe2 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -210,7 +210,7 @@ pub struct Guest { /// last sent about itself. pub sent_shared: i8, /// Where the player last died (Player.lastDeathLocation), sent with the respawn. - pub last_death: Option<[i32; 3]>, + pub last_death: Option<(String, [i32; 3])>, /// The last action sequence to acknowledge at the next tick (-1: none). pub ack_up_to: std::cell::Cell, pub sent_selected: usize, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..7bcea3e79 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -557,16 +557,24 @@ impl Hub { // ---- joining ------------------------------------------------------- - fn spawn_info(&self, game_mode: i32) -> play::SpawnInfo { + fn spawn_info(&self, i: usize) -> play::SpawnInfo { + let g = &self.guests[i]; play::SpawnInfo { dimension_type: self.dimension_type, dimension: self.config.dimension.clone(), seed: horizon_core::biome::obfuscate_seed(self.config.seed), - game_type: game_mode, + game_type: g.game_mode, previous_game_type: None, debug: false, flat: false, - last_death: None, + // Player.getLastDeathLocation. + last_death: g + .last_death + .as_ref() + .map(|(dimension, pos)| play::GlobalPos { + dimension: dimension.clone(), + pos: *pos, + }), portal_cooldown: 0, sea_level: 63, } @@ -635,7 +643,7 @@ impl Hub { reduced_debug_info: false, show_death_screen: true, limited_crafting: false, - spawn: self.spawn_info(mode), + spawn: self.spawn_info(i), // MinecraftServer.usesAuthentication, enforceSecureProfile. online_mode: self.lan.shared.config.online.is_some(), enforces_secure_chat: self.enforces_secure_chat(), @@ -2361,14 +2369,7 @@ impl Hub { /// level loading screen from the Respawn packet until the level info's "level chunks load /// start" event and the chunk under the player, so the packets follow vanilla's order. pub fn respawn(&mut self, i: usize, at: [f64; 3], ctx: &TickCtx) { - let mode = self.guests[i].game_mode; - let mut info = self.spawn_info(mode); - // Player.getLastDeathLocation, set where the player died. - // The level they died in: theirs until now. - info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos { - dimension: self.guests[i].dimension.clone(), - pos, - }); + let info = self.spawn_info(i); self.close_container_for(i); let g = &mut self.guests[i]; // PlayerList.respawn: into the level in place (the respawn level). @@ -2481,8 +2482,7 @@ impl Hub { portal_sound: bool, ctx: &TickCtx, ) { - let mode = self.guests[i].game_mode; - let info = self.spawn_info(mode); + let info = self.spawn_info(i); self.close_container_for(i); let g = &mut self.guests[i]; g.dimension = self.config.dimension.clone(); diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index f5eb935c9..af8f15bb4 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -86,6 +86,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); guest.seen_credits = level.seen_credits; + guest.last_death = level.last_death.clone(); let extra = level.player_extra.as_ref(); let short = |key: &str, default: i64| { extra @@ -168,6 +169,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; level.seen_credits = guest.seen_credits; + level.last_death = guest.last_death.clone(); level.player_extra = guest.saved.clone(); // The live body's fire, air and fall distance (Entity.saveWithoutId), // or what the file had while the player has no body yet. diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 5926e0a1d..c965d36c1 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2761,6 +2761,8 @@ pub struct Level { pub xp_seed: i32, /// ServerPlayer.seenCredits: the end poem has been shown. pub seen_credits: bool, + /// Player.lastDeathLocation: the dimension and block of the last death. + pub last_death: Option<(String, [i32; 3])>, /// Player.active_effects: (id, duration, amplifier, ambient, show_icon). pub active_effects: Vec<(String, i32, i32, bool, bool)>, /// Player.EnderItems: the ender chest inventory (27 slots). @@ -2961,6 +2963,15 @@ impl Level { self.fall_distance = f("fall_distance").unwrap_or(0.0); self.on_ground = n("OnGround").unwrap_or(0) != 0; self.seen_credits = n("seenCredits").unwrap_or(0) != 0; + self.last_death = p.get("LastDeathLocation").and_then(|d| { + let Some(Tag::IntArray(pos)) = d.get("pos") else { + return None; + }; + Some(( + text(d.get("dimension"))?, + [*pos.first()?, *pos.get(1)?, *pos.get(2)?], + )) + }); if let Some(mode) = n("playerGameType") { self.creative = mode == 1; self.game_mode = mode as i32; @@ -3061,6 +3072,7 @@ impl Level { "Pos", "respawn", "recipeBook", + "LastDeathLocation", ] { map.remove(&JavaString::from(key)); } @@ -3187,6 +3199,15 @@ impl Level { entries.push(("Pos", doubles(&pos))); } entries.push(("seenCredits", Tag::Byte(i8::from(self.seen_credits)))); + if let Some((dimension, pos)) = &self.last_death { + entries.push(( + "LastDeathLocation", + Tag::compound([ + ("dimension", string(dimension)), + ("pos", Tag::IntArray(pos.to_vec())), + ]), + )); + } // A respawn point other than the world spawn: an anchor elsewhere, or a bed. if let Some((dimension, block, yaw, forced)) = &self.respawn_elsewhere { let mut respawn = vec![ From f1949c3bdacece089ba1dfa2bcfe31eb9698e2ce Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:36:39 +0100 Subject: [PATCH 071/221] Ask before the death screen's Title Screen button leaves the world --- crates/horizon-client/src/confirm_screen.rs | 15 ++++- crates/horizon-client/src/game.rs | 15 +++++ crates/horizon-client/src/game/chat.rs | 4 ++ crates/horizon-client/src/game/remote.rs | 2 + crates/horizon-client/src/game/screens.rs | 61 +++++++++++++++++++++ 5 files changed, 95 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/confirm_screen.rs b/crates/horizon-client/src/confirm_screen.rs index 3b4f7e7aa..c6fda8236 100644 --- a/crates/horizon-client/src/confirm_screen.rs +++ b/crates/horizon-client/src/confirm_screen.rs @@ -63,13 +63,24 @@ impl Confirm { atlas: &HudAtlas, cursor: (f32, f32), labels: [&Text; 2], + ) { + self.draw_active(batch, atlas, cursor, labels, true); + } + /// `draw` with the buttons greyed out while `setDelay` runs (`active` false). + pub fn draw_active( + &self, + batch: &mut HudBatch, + atlas: &HudAtlas, + cursor: (f32, f32), + labels: [&Text; 2], + active: bool, ) { for (line, x, y) in &self.lines { batch.text_styled(atlas, line, *x, *y, u32::MAX, true); } for ((bx, by), label) in self.buttons.into_iter().zip(labels) { - let hover = ui::hovered(cursor, bx, by, 150.0, 20.0); - ui::button(batch, atlas, bx, by, 150.0, 20.0, label, true, hover); + let hover = active && ui::hovered(cursor, bx, by, 150.0, 20.0); + ui::button(batch, atlas, bx, by, 150.0, 20.0, label, active, hover); } } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..9747559f0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4281,6 +4281,7 @@ impl Game<'_> { self.screen = Screen::Dead; self.ui.died_at = Some(Instant::now()); self.ui.death_text = None; + self.ui.death_confirm = None; self.capture(false); } self.previous_position = feet; @@ -11860,6 +11861,20 @@ impl ApplicationHandler for Game<'_> { _ => {} } } + // ConfirmScreen.keyPressed: Escape answers no, once its delay is over. + WindowEvent::KeyboardInput { event, .. } + if self.screen == Screen::Dead && self.ui.death_confirm.is_some() => + { + if event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape) + && self + .ui + .death_confirm + .is_some_and(|t| t.elapsed().as_millis() >= 1000) + { + self.death_confirm_answer(false)?; + } + } // ConfirmScreen.keyPressed: Escape answers no. WindowEvent::KeyboardInput { event, .. } if self.server_packs.prompt.is_some() => { if event.state == ElementState::Pressed diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..bb4c26adc 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -102,6 +102,9 @@ pub struct UiState { /// Death screen cause and when the player died (buttons wait 20 ticks). pub death_text: Option, pub died_at: Option, + /// `DeathScreen.TitleConfirmScreen` and when it opened (its buttons wait + /// 20 ticks, `setDelay`). + pub death_confirm: Option, /// `LivingEntity.deathTime` of the window's player: ticks since it died. pub death_time: u32, } @@ -886,6 +889,7 @@ impl Game<'_> { let cause = self.ui.death_cause.take(); self.ui.died_at = Some(std::time::Instant::now()); self.ui.death_text = None; + self.ui.death_confirm = None; if !self.ui.rules.bool("show_death_messages") { return; } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..fae77175c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2185,6 +2185,7 @@ impl Game<'_> { if p.health <= 0.0 && self.screen != Screen::Dead && self.player.is_some() { self.screen = Screen::Dead; self.ui.death_time = 0; + self.ui.death_confirm = None; self.capture(false); } } @@ -2202,6 +2203,7 @@ impl Game<'_> { if me && self.screen != Screen::Dead && self.player.is_some() { self.screen = Screen::Dead; self.ui.death_time = 0; + self.ui.death_confirm = None; self.capture(false); } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index f8885f83a..4f5c72694 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -3,6 +3,7 @@ use super::{Game, Screen}; use horizon_client::{ Result, command::args::GameMode, + confirm_screen::Confirm, hud::{HudBatch, rgba}, text::{self, Text}, ui, @@ -84,6 +85,14 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { ] } /// DeathScreen.init: a hardcore player can only spectate. +/// `DeathScreen.TitleConfirmScreen`: its title and the yes and no labels. +fn death_confirm_texts() -> (Text, [Text; 2]) { + let t = |key: &str| Text::translate(key, &[]); + ( + t("deathScreen.quit.confirm"), + [t("deathScreen.titleScreen"), t("deathScreen.respawn")], + ) +} fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8); 2] { let respawn = if hardcore { "deathScreen.spectate" @@ -231,6 +240,20 @@ impl Game<'_> { ), ); } + // DeathScreen.handleExitToTitleScreen: the TitleConfirmScreen takes the + // screen over, on the same background. + if let Some(opened) = self.ui.death_confirm { + let (title, labels) = death_confirm_texts(); + let size = self.gui_size(); + Confirm::new(&atlas.font, size, &title, &Text::literal("")).draw_active( + batch, + atlas, + self.cursor, + [&labels[0], &labels[1]], + opened.elapsed().as_millis() >= 1000, + ); + return; + } let title = if self.level.hardcore { "deathScreen.title.hardcore" } else { @@ -294,6 +317,23 @@ impl Game<'_> { { return Ok(()); } + if let Some(opened) = self.ui.death_confirm { + // ConfirmScreen.setDelay: both buttons wait 20 ticks. + if opened.elapsed().as_millis() < 1000 { + return Ok(()); + } + let (title, _) = death_confirm_texts(); + let confirm = Confirm::new( + &self.gui.atlas.font, + self.gui_size(), + &title, + &Text::literal(""), + ); + if let Some(yes) = confirm.answer_at(self.cursor) { + self.death_confirm_answer(yes)?; + } + return Ok(()); + } let size = self .renderer .as_ref() @@ -303,6 +343,27 @@ impl Game<'_> { .into_iter() .find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)) .map(|d| d.3); + // handleExitToTitleScreen: outside hardcore, Title Screen asks first. + if hit == Some(1) && !self.level.hardcore { + self.ui.death_confirm = Some(std::time::Instant::now()); + self.audio.play_button_click(); + return Ok(()); + } + self.death_action(hit) + } + /// The confirm screen's answer: yes leaves the world, no respawns + /// (`DeathScreen.handleExitToTitleScreen`'s callback). + pub(super) fn death_confirm_answer(&mut self, yes: bool) -> Result<()> { + self.ui.death_confirm = None; + if yes { + self.audio.play_button_click(); + self.close_world() + } else { + self.death_action(Some(0)) + } + } + /// A death screen button: 0 respawns (or spectates in hardcore), 1 leaves. + fn death_action(&mut self, hit: Option) -> Result<()> { if hit == Some(0) && self.remote.is_none() { let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); self.experience.respawn(keep); From 796dc320d9b3ccef8c2bc949bbb0db0072ecc05d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:36:45 +0100 Subject: [PATCH 072/221] Use the height adjusted biome temperature for the rain and snow line on the client --- crates/horizon-client/src/biome.rs | 26 ++++++++++++++++++- crates/horizon-client/src/game.rs | 16 ++++-------- crates/horizon-client/src/game/render_tick.rs | 11 +------- 3 files changed, 31 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index c8c15e44e..7aa95e623 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -1,7 +1,8 @@ //! Biome colours from the pinned biome definitions and colormaps //! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`). use crate::Result; -use horizon_core::{noise::SimplexNoise, random::LegacyRandom}; +use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom}; +use horizon_world::worldgen::biome_temperature::{BiomeTemperatureSettings, TemperatureModifier}; use serde_json::Value; use std::{collections::HashMap, fs, path::Path}; @@ -33,6 +34,8 @@ pub struct BiomeInfo { pub increased_fire_burnout: bool, pub name: String, pub temperature: f32, + /// `climateSettings.temperatureModifier` (frozen oceans). + pub temperature_modifier: TemperatureModifier, pub downfall: f32, pub precipitation: bool, pub grass: u32, @@ -45,6 +48,22 @@ pub struct BiomeInfo { pub fog: Option, pub water_fog: u32, } +impl BiomeInfo { + /// `Biome.getPrecipitationAt` in the Overworld (sea level 63): None + /// without precipitation, else whether it falls as snow + /// (`getHeightAdjustedTemperature` below 0.15). + pub fn snows_at(&self, x: i32, y: i32, z: i32) -> Option { + let settings = BiomeTemperatureSettings { + base_temperature: self.temperature, + modifier: self.temperature_modifier, + has_precipitation: self.precipitation, + downfall: self.downfall, + }; + settings + .has_precipitation + .then(|| settings.height_adjusted(BlockPos::new(x, y, z), 63) < 0.15) + } +} pub struct Biomes { pub list: Vec, pub index: HashMap, @@ -105,6 +124,10 @@ impl Biomes { let attributes = &v["attributes"]; let temperature = v["temperature"].as_f64().unwrap_or(0.5) as f32; let downfall = v["downfall"].as_f64().unwrap_or(0.5) as f32; + let temperature_modifier = match v["temperature_modifier"].as_str() { + Some("frozen") => TemperatureModifier::Frozen, + _ => TemperatureModifier::None, + }; let modifier = match effects["grass_color_modifier"].as_str() { Some("dark_forest") => GrassModifier::DarkForest, Some("swamp") => GrassModifier::Swamp, @@ -135,6 +158,7 @@ impl Biomes { .as_bool() .unwrap_or(false), temperature, + temperature_modifier, downfall, precipitation: v["has_precipitation"].as_bool().unwrap_or(true), grass: color(&effects["grass_color"]) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..e5667f6de 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9670,19 +9670,13 @@ impl Game<'_> { } } /// Whether precipitation at a column is snow (Biome.coldEnoughToSnow: - /// base temperature lowered above y 80) or none (no precipitation). + /// height adjusted temperature) or none (no precipitation). fn precipitation(&self, x: i32, y: i32, z: i32) -> Option { let chunk = self.world.chunks.get(&(x >> 4, z >> 4))?; - let b = self.res.biomes().get(chunk.biome(x, y, z)); - if !b.precipitation { - return None; - } - let t = if y > 80 { - b.temperature - (y - 80) as f32 * 0.05 / 40.0 - } else { - b.temperature - }; - Some(t < 0.15) + self.res + .biomes() + .get(chunk.biome(x, y, z)) + .snows_at(x, y, z) } /// `getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)`: one above the /// highest block in `blocks_motion_in_heightmap` or holding a fluid. diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..f5efa392b 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -33,16 +33,7 @@ fn rains_at(world: &World, biomes: &Biomes, x: i32, y: i32, z: i32) -> bool { let Some(chunk) = world.chunks.get(&(x >> 4, z >> 4)) else { return false; }; - let b = biomes.get(chunk.biome(x, y, z)); - if !b.precipitation { - return false; - } - let t = if y > 80 { - b.temperature - (y - 80) as f32 * 0.05 / 40.0 - } else { - b.temperature - }; - t >= 0.15 + biomes.get(chunk.biome(x, y, z)).snows_at(x, y, z) == Some(false) } impl Game<'_> { From 08c959807d291ef94bf9baf58fb4b9e3179c551d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:37:01 +0100 Subject: [PATCH 073/221] Broken heads keep their skin and silk-touched hives keep their bees and honey --- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/block_items.rs | 44 +++++++++++++++++- crates/horizon-client/src/game/dispenser.rs | 1 + crates/horizon-client/src/game/spill.rs | 46 ++++++++++++++++++- crates/horizon-client/src/items.rs | 26 +++++++++++ 5 files changed, 115 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..f7db61dd8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3812,6 +3812,7 @@ impl Game<'_> { return Ok(true); }; let target = [pos.x, pos.y, pos.z]; + let state = self.apply_item_block_state(target, state, &stack)?; self.mod_block_event(target, state, true); if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { let key = (target[0], target[1], target[2]); diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index 199c39a78..d18715041 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -4,9 +4,13 @@ //! placed item gives its block entity. use super::Game; use horizon_client::{ - block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save, + Result, block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, + items::ItemStack, save, +}; +use horizon_world::{ + nbt::{Compound, Tag}, + registry::BlockStateId, }; -use horizon_world::nbt::{Compound, Tag}; /// The component patch of `stack`. fn components(stack: &ItemStack) -> Compound { @@ -77,6 +81,42 @@ impl Game<'_> { Some(stack) } + /// `BlockItem.updateBlockStateFromTag`: the properties of the item's + /// `block_state` component (a hive's honey level, a statue's pose) set on + /// the block just placed at `pos`. Returns the state it has now. + pub(super) fn apply_item_block_state( + &mut self, + pos: [i32; 3], + state: BlockStateId, + stack: &ItemStack, + ) -> Result { + let Some(Tag::Compound(saved)) = + stack.data().and_then(|d| d.other("minecraft:block_state")) + else { + return Ok(state); + }; + let Some(current) = self.pack.assets.registry.state(state) else { + return Ok(state); + }; + // Only the properties the block has. + let props: Vec<(String, String)> = saved + .iter() + .filter_map(|(k, v)| match v { + Tag::String(v) => Some((k.to_string_lossy(), v.to_string_lossy())), + _ => None, + }) + .filter(|(k, v)| current.properties.get(k).is_some_and(|old| old != v)) + .collect(); + let props: Vec<(&str, &str)> = props.iter().map(|(k, v)| (&**k, &**v)).collect(); + match self.with_props(state, &props) { + Some(new) if !props.is_empty() && new != state => { + self.level_set(pos, new)?; + Ok(new) + } + _ => Ok(state), + } + } + /// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents` /// for the block entity just placed at `pos` from `stack`; `game_master`: /// the placer can use game master blocks (a dispenser can't). diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 61725c6ab..913e193bd 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1548,6 +1548,7 @@ impl Game<'_> { return Ok((Some(stack), FAIL)); }; let target = (placed.x, placed.y, placed.z); + let state = self.apply_item_block_state([target.0, target.1, target.2], state, &stack)?; if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(target, entity); self.apply_placed_item([target.0, target.1, target.2], &stack, false); diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index 7f370507f..a84a2f04f 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -5,9 +5,11 @@ //! world as soon as the behaviour returns, within the same tick. use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box}; use horizon_client::{ + block_entity_item, block_entity_nbt, containers::{Banner, BlockEntity}, item_data, items::ItemStack, + save, }; use horizon_core::position::BlockPos; use horizon_core::random::RandomSource; @@ -16,7 +18,7 @@ use horizon_world::{ LevelEvent, removal::{self, PreRemove}, }, - nbt::{JavaString, Tag}, + nbt::{Compound, JavaString, Tag}, registry::BlockStateId, }; use std::collections::HashMap; @@ -32,6 +34,9 @@ pub(super) struct Pending { pub(super) names: HashMap<[i32; 3], (String, String)>, /// A decorated pot's sherds (back, left, right, front). pub(super) pot: HashMap<[i32; 3], [Option; 4]>, + /// A head's profile, note block sound and name, or a hive's bees: the + /// dropped item and the component patch it takes. + pub(super) copied: HashMap<[i32; 3], (String, Compound)>, } impl Pending { /// Remember what the block entity at `pos` copies into the drops of `block`. @@ -49,6 +54,31 @@ impl Pending { if let Some(name) = name { self.names.insert(pos, (block.to_owned(), name)); } + // `copy_components` from the block entity: the head tables copy the + // profile (player heads), note block sound and name, the hive tables + // the bees. + let include: &[&str] = match entity { + BlockEntity::Skull(_) if block.starts_with("minecraft:player_") => &[ + "minecraft:profile", + "minecraft:note_block_sound", + "minecraft:custom_name", + ], + BlockEntity::Skull(_) => &["minecraft:custom_name"], + BlockEntity::Beehive(_) => &["minecraft:bees"], + _ => &[], + }; + if !include.is_empty() { + let saved = save::encode_block_entity((pos[0], pos[1], pos[2]), entity, block); + let mut patch = block_entity_nbt::canonical(&saved) + .map(|saved| block_entity_item::pick(&saved)) + .unwrap_or_default(); + patch.retain(|k, _| include.contains(&k.to_string_lossy().as_str())); + if !patch.is_empty() { + // `Blocks.wallVariant`: a wall head drops the standing item. + let item = block.replacen("_wall_", "_", 1); + self.copied.insert(pos, (item, patch)); + } + } if is_shulker_box(block) && let BlockEntity::Chest(items) = entity { @@ -76,6 +106,19 @@ impl Pending { { stack.data_mut().custom_name = Some(name); } + if self + .copied + .get(&pos) + .is_some_and(|(item, _)| **item == *stack.item) + && let Some((_, copied)) = self.copied.remove(&pos) + { + let mut patch = match item_data::encode_components(stack) { + Some(Tag::Compound(c)) => c, + _ => Default::default(), + }; + patch.extend(copied); + (stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(patch))); + } if &*stack.item == "minecraft:decorated_pot" { // The pot's block entity always copies its decorations, empty or not. let sides = self.pot.remove(&pos).unwrap_or_default(); @@ -155,6 +198,7 @@ impl Pending { self.shulker.remove(&pos); self.banner.remove(&pos); self.names.remove(&pos); + self.copied.remove(&pos); } } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index b4092a201..391fa793f 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1085,6 +1085,8 @@ impl Items { ctx.evaluate(table, random) } } +/// `DataComponents.BLOCK_STATE`. +const BLOCK_STATE: &str = "minecraft:block_state"; impl LootContext<'_> { fn evaluate(&self, table: &Value, random: &mut R) -> Vec { let ctx = self; @@ -1481,6 +1483,30 @@ impl LootContext<'_> { } } } + // CopyBlockState: the listed properties of the broken block + // become the item's `block_state` component. + "minecraft:copy_state" => { + use horizon_world::nbt::Tag; + let mut copied = match stack.data().and_then(|d| d.other(BLOCK_STATE)) { + Some(Tag::Compound(c)) => c.clone(), + _ => Default::default(), + }; + for name in f["properties"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if let Some(value) = self.properties.get(name) { + copied.insert(name.into(), Tag::String(value.as_str().into())); + } + } + if !copied.is_empty() { + stack + .data_mut() + .set_other(BLOCK_STATE, Some(Tag::Compound(copied))); + } + } // ApplyExplosionDecay: each item survives with 1 / radius. "minecraft:explosion_decay" => { if let Some(radius) = self.explosion_radius { From d248ab26057306cdca68f68541a5af915e1edf11 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:37:15 +0100 Subject: [PATCH 074/221] Give foxes their own goals: flee, hunt, nap in the shade and eat berries Foxes used the generic animal goals: they panicked at 1.25, never avoided players or wolves, never hunted, slept, bred or ate berries. Add mobs/fox.rs with the goals Fox.registerGoals sets up that Horizon can run today, send the fox variant and flags to clients so the sleeping pose shows, and let a baby fox take either parent's variant. --- crates/horizon-client/src/game/creatures.rs | 4 + crates/horizon-client/src/game/lan.rs | 12 + .../src/game/remote_mob_data.rs | 5 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/ai.rs | 2 + crates/horizon-client/src/mobs/body_anim.rs | 2 +- crates/horizon-client/src/mobs/fox.rs | 369 ++++++++++++++++++ crates/horizon-client/src/mobs/goals.rs | 17 + 8 files changed, 411 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/mobs/fox.rs diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d192a2b02..38cb3a2e4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1426,6 +1426,10 @@ impl Game<'_> { } // Offspring inherit a parent's variant (pigs/cows/chickens) or mixed wool. child.extra.variant = p.extra.variant; + // Fox.getBreedOffspring: either parent's variant. + if p.species() == Species::Fox && !coin { + child.extra.variant = q.as_ref().map_or(p.extra.variant, |q| q.extra.variant); + } if p.species() == Species::Sheep { child.extra.color = p.extra.color; } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..cef1a5b68 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -231,6 +231,18 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(0))); } + // Fox.DATA_TYPE_ID and DATA_FLAGS_ID (sleeping 32, ...). + "minecraft:fox" => { + if e.variant != 0 { + meta.push((17, serializer::INT, Value::Int(i32::from(e.variant)))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + let flags = (e.ints[0] & 0xff) as u8 as i8; + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags))); + } + defaults.push((18, serializer::BYTE, Value::Byte(0))); + } "minecraft:cat" | "minecraft:wolf" => { // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 }; diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..50afac107 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -61,6 +61,11 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), + // Fox.DATA_TYPE_ID and DATA_FLAGS_ID. + (Species::Fox, 17, Value::Int(variant)) => { + m.extra.variant = (*variant).clamp(0, 1) as u8 + } + (Species::Fox, 18, Value::Byte(flags)) => m.extra.ints[0] = i32::from(*flags as u8), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. (Species::Sheep, 18, Value::Byte(wool)) => { m.extra.color = (*wool & 15) as u8; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4b67f738f..847177657 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -29,6 +29,7 @@ pub mod drops; pub mod enderman; pub mod equine; pub mod farm; +pub mod fox; pub mod finalize; pub mod gear; pub mod goals; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..7bb165020 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -178,6 +178,7 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + Family::Generic if m.species() == Species::Fox => super::fox::register(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { @@ -999,6 +1000,7 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Fox => super::fox::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; } diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..b872cbd98 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -1028,7 +1028,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { a, ), Species::Rabbit => rabbit(p, s, &st[0], &st[1], a), - Species::Fox => fox(p, s, &Fox::default(), a), + Species::Fox => fox(p, s, &super::fox::pose(m), a), _ => return false, } true diff --git a/crates/horizon-client/src/mobs/fox.rs b/crates/horizon-client/src/mobs/fox.rs new file mode 100644 index 000000000..c683eeb86 --- /dev/null +++ b/crates/horizon-client/src/mobs/fox.rs @@ -0,0 +1,369 @@ +//! Foxes (`net.minecraft.world.entity.animal.fox.Fox`): the goal list, the +//! flags byte (sleeping, ...), napping in the shade by day, eating berries +//! and the food held in the mouth. Faceplanting, stalking and pouncing, +//! picking up items, sheltering and trusting players are not ported yet. +use super::{ + Mob, MobEvent, MobWorld, Seen, Species, + goals::{ + Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, JUMP, LOOK, LeapAtTarget, + LookAtPlayer, MOVE, MeleeAttack, MoveToBlock, NearestTarget, Panic, Prey, Stroll, + goal_clone, reduced, + }, +}; +use horizon_core::{geometry::Axis, random::RandomSource}; +use horizon_world::registry::BlockStateId; + +// Fox.DATA_FLAGS_ID, kept in `extra.ints[0]` (and sent to clients as is). +pub const SITTING: i32 = 1; +pub const CROUCHING: i32 = 4; +pub const INTERESTED: i32 = 8; +pub const POUNCING: i32 = 16; +pub const SLEEPING: i32 = 32; +pub const FACEPLANTED: i32 = 64; +pub const DEFENDING: i32 = 128; +/// `Fox.ticksSinceEaten`. +const TICKS_SINCE_EATEN: usize = 1; + +pub fn flag(m: &Mob, f: i32) -> bool { + m.extra.ints[0] & f != 0 +} +fn set_flag(m: &mut Mob, f: i32, on: bool) { + if on { + m.extra.ints[0] |= f; + } else { + m.extra.ints[0] &= !f; + } +} +/// `Fox.clearStates`. +fn clear_states(m: &mut Mob) { + m.extra.ints[0] = 0; +} + +/// `Fox.registerGoals` and `setTargetGoals` (the targets wait for the variant: +/// red foxes prefer chickens and rabbits, snow foxes fish). +pub fn register(m: &mut Mob) { + let countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0); + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(2, Panic::new(2.2)); + g.add(3, Breed::new(1.0)); + // AVOID_PLAYERS: not a sneaking player. + g.add( + 4, + AvoidEntity::new(Avoid::Player, 16.0, 1.6, 1.4) + .player_when(|p| !p.sneaking && !p.spectator), + ); + g.add( + 4, + AvoidEntity::new(Avoid::Species(vec![Species::Wolf]), 8.0, 1.6, 1.4).seen_when(|s| !s.tame), + ); + g.add( + 4, + AvoidEntity::new(Avoid::Species(vec![Species::PolarBear]), 8.0, 1.6, 1.4), + ); + g.add(7, MeleeAttack::new(1.2, true)); + g.add(7, Sleep { countdown }); + g.add(8, FollowParent::new(1.25)); + g.add(10, EatBerries::new()); + g.add(10, LeapAtTarget::new(0.4)); + g.add(11, Stroll::avoiding_water(1.0)); + g.add(12, LookAtPlayer::new(24.0)); + let red = |m: &Mob, _: &MobWorld| m.extra.variant == 0; + let snow = |m: &Mob, _: &MobWorld| m.extra.variant != 0; + let land = || NearestTarget::new(Prey::Filter(chicken_or_rabbit), false).interval(10); + let turtle = || NearestTarget::new(Prey::Filter(baby_turtle_on_land), false).interval(10); + let fish = || NearestTarget::new(Prey::Filter(schooling_fish), false).interval(20); + let t = &mut m.ai.targets; + t.add(4, land().gate(red)); + t.add(4, turtle().gate(red)); + t.add(6, fish().gate(red)); + t.add(4, fish().gate(snow)); + t.add(6, land().gate(snow)); + t.add(6, turtle().gate(snow)); +} + +fn chicken_or_rabbit(s: &Seen) -> bool { + matches!(s.species, Species::Chicken | Species::Rabbit) +} +fn baby_turtle_on_land(s: &Seen) -> bool { + s.species == Species::Turtle && s.baby && !s.in_water +} +fn schooling_fish(s: &Seen) -> bool { + matches!( + s.species, + Species::Cod | Species::Salmon | Species::TropicalFish + ) +} + +/// `Fox.tick` and the eating part of `Fox.aiStep`. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if !m.alive() { + return; + } + m.extra.ints[TICKS_SINCE_EATEN] += 1; + if let Some(item) = m.extra.main_hand.clone() + && eats(w, &item) + && m.ai.target.is_none() + && m.on_ground + && !flag(m, SLEEPING) + { + let eaten = m.extra.ints[TICKS_SINCE_EATEN]; + if eaten > 600 { + // ItemStack.finishUsingItem: the food is gone, a use remainder stays. + m.extra.main_hand = w + .items + .and_then(|i| i.items.get(&item)) + .and_then(|i| i.use_remainder.as_deref()) + .map(Into::into); + m.extra.ints[TICKS_SINCE_EATEN] = 0; + } else if eaten > 560 && m.random.next_float() < 0.1 { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound("entity.fox.eat", at, 1.0, 1.0)); + } + } + if m.ai.target.is_none() { + set_flag(m, CROUCHING | INTERESTED, false); + } + let in_water = m.fluids.in_water; + if in_water || m.ai.target.is_some() || w.thundering { + set_flag(m, SLEEPING, false); + } + if in_water || flag(m, SLEEPING) { + set_flag(m, SITTING, false); + } +} +/// `Fox.isConsumableFood`: the item has food and consumable components. +fn eats(w: &MobWorld, item: &str) -> bool { + w.items + .and_then(|i| i.items.get(item)) + .is_some_and(|i| i.food.is_some() && i.consumable.is_some()) +} + +/// `Fox.FoxBehaviorGoal.hasShelter`: out of the sky's sight and not a bad spot. +fn has_shelter(m: &Mob, w: &MobWorld) -> bool { + let at = [ + m.position.x.floor() as i32, + m.bounds().max(Axis::Y).floor() as i32, + m.position.z.floor() as i32, + ]; + !w.can_see_sky(at[0], at[1], at[2]) && m.walk_target_value(w, at) >= 0.0 +} +/// `Fox.FoxBehaviorGoal.alertable`: someone within 12 blocks the fox would +/// keep watch over (`FoxAlertableEntitiesSelector`). +fn alertable(m: &Mob, w: &MobWorld) -> bool { + let (from, id, y) = (m.position, m.id, m.position.y); + let mob = w + .nearby(from, 12.0, |s: &Seen| { + s.id != id + && (s.position.y - y).abs() <= 6.0 + && m.distance_sqr(s.position) <= 144.0 + && match s.species { + Species::Fox => false, + Species::Chicken | Species::Rabbit => true, + Species::Wolf | Species::Cat | Species::Parrot | Species::Nautilus => !s.tame, + _ => true, + } + }) + .next() + .is_some(); + mob || w.player.as_ref().is_some_and(|p| { + p.alive + && !p.creative + && !p.spectator + && !p.sneaking + && (p.position.y - y).abs() <= 6.0 + && m.distance_sqr(p.position) <= 144.0 + }) +} + +/// `Fox.SleepGoal`: nap in the shade by day when nothing is around. +#[derive(Clone, Debug)] +struct Sleep { + countdown: i32, +} +impl Sleep { + fn can_sleep(&mut self, m: &Mob, w: &MobWorld) -> bool { + if self.countdown > 0 { + self.countdown -= 1; + return false; + } + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + w.daylight + && has_shelter(m, w) + && !alertable(m, w) + && w.block_name(x, y, z) != "minecraft:powder_snow" + } +} +impl Goal for Sleep { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.nav.is_done() && (self.can_sleep(m, cx.w) || flag(m, SLEEPING)) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.can_sleep(m, cx.w) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING | CROUCHING | INTERESTED, false); + m.ai.jumping = false; + set_flag(m, SLEEPING, true); + m.nav_stop(); + let p = m.position; + m.ai.mov.set_wanted(p.x, p.y, p.z, 0.0); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + self.countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0); + clear_states(m); + } +} + +/// `BlockState` with one property changed. +fn with_prop(w: &MobWorld, p: [i32; 3], key: &str, value: &str) -> Option { + let mut s = w.registry.state(w.world.block(p[0], p[1], p[2]))?.clone(); + s.properties.insert(key.into(), value.into()); + w.registry.id(&s) +} +/// `FoxEatBerriesGoal.isValidTarget`: a ripe sweet berry bush or glow berries. +fn has_berries(w: &MobWorld, p: [i32; 3]) -> bool { + match w.block_name(p[0], p[1], p[2]) { + "minecraft:sweet_berry_bush" => w + .prop(p[0], p[1], p[2], "age") + .and_then(|a| a.parse::().ok()) + .is_some_and(|a| a >= 2), + "minecraft:cave_vines" | "minecraft:cave_vines_plant" => { + w.prop(p[0], p[1], p[2], "berries") == Some("true") + } + _ => false, + } +} + +/// `Fox.FoxEatBerriesGoal`: walk to a ripe berry bush and pick it after 40 ticks. +#[derive(Clone, Debug)] +struct EatBerries { + block: MoveToBlock, + waited: i32, +} +impl EatBerries { + fn new() -> Self { + Self { + block: MoveToBlock::new(1.2, 12, 1), + waited: 0, + } + } + fn pick(&mut self, m: &mut Mob, cx: &mut Cx) { + let p = self.block.block; + let at = [ + f64::from(p[0]) + 0.5, + f64::from(p[1]) + 0.5, + f64::from(p[2]) + 0.5, + ]; + if cx.w.block_name(p[0], p[1], p[2]) == "minecraft:sweet_berry_bush" { + let age: i32 = + cx.w.prop(p[0], p[1], p[2], "age") + .and_then(|a| a.parse().ok()) + .unwrap_or(0); + let mut count = 1 + m.random.next_int_bound(2).unwrap_or(0) + i32::from(age == 3); + if m.extra.main_hand.is_none() { + m.extra.main_hand = Some("minecraft:sweet_berries".into()); + count -= 1; + } + if count > 0 { + cx.events.push(MobEvent::DropItem { + item: "minecraft:sweet_berries".into(), + count: count as u32, + at, + }); + } + if let Some(state) = with_prop(cx.w, p, "age", "1") { + cx.events.push(MobEvent::SetBlock { pos: p, state }); + } + cx.events.push(MobEvent::Sound( + "block.sweet_berry_bush.pick_berries", + at, + 1.0, + 1.0, + )); + } else { + // CaveVines.use: one glow berry, the vine goes back to bare. + cx.events.push(MobEvent::DropItem { + item: "minecraft:glow_berries".into(), + count: 1, + at, + }); + if let Some(state) = with_prop(cx.w, p, "berries", "false") { + cx.events.push(MobEvent::SetBlock { pos: p, state }); + } + let pitch = 0.8 + m.random.next_float() * 0.4; + cx.events.push(MobEvent::Sound( + "block.cave_vines.pick_berries", + at, + 1.0, + pitch, + )); + } + } +} +impl Goal for EatBerries { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) { + return false; + } + // MoveToBlockGoal.canUse draws the next delay only once the last one + // has run out. + if self.block.next_start > 0 { + self.block.next_start -= 1; + return false; + } + let next = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.block.can_use(m, cx.w, next, has_berries) + } + fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool { + self.block.can_continue(cx.w, has_berries) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.waited = 0; + set_flag(m, SITTING, false); + self.block.start(m, cx.w); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if self.block.reached { + if self.waited >= 40 { + if cx.w.mob_griefing { + self.pick(m, cx); + } + } else { + self.waited += 1; + } + } else if m.random.next_float() < 0.05 { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.fox.sniff", at, 1.0, 1.0)); + } + self.block.tick_within(m, cx.w, 2.0); + } +} + +/// `FoxModel`'s flags as the renderer reads them. +pub fn pose(m: &Mob) -> super::body_anim::Fox { + super::body_anim::Fox { + crouching: flag(m, CROUCHING), + sleeping: flag(m, SLEEPING), + sitting: flag(m, SITTING), + pouncing: flag(m, POUNCING), + faceplanted: flag(m, FACEPLANTED), + ..Default::default() + } +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index a784464d8..1124414b8 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1525,6 +1525,10 @@ pub struct AvoidEntity { pub sprint: f64, /// Extra condition on the avoider (e.g. untamed cats only). pub when: Option bool>, + /// Extra condition on the player or mob avoided (`AvoidEntityGoal`'s + /// predicate: a sneaking player, a tame wolf). + pub player_when: Option bool>, + pub seen_when: Option bool>, from: Vec3, /// The mob being avoided (`toAvoid`), when it is one. pub found: Option, @@ -1537,6 +1541,8 @@ impl AvoidEntity { walk, sprint, when: None, + player_when: None, + seen_when: None, from: Vec3::ZERO, found: None, } @@ -1545,6 +1551,14 @@ impl AvoidEntity { self.when = Some(f); self } + pub fn player_when(mut self, f: fn(&super::PlayerView) -> bool) -> Self { + self.player_when = Some(f); + self + } + pub fn seen_when(mut self, f: fn(&Seen) -> bool) -> Self { + self.seen_when = Some(f); + self + } } impl Goal for AvoidEntity { goal_clone!(); @@ -1565,6 +1579,7 @@ impl Goal for AvoidEntity { .filter(|p| { p.alive && !p.creative + && self.player_when.is_none_or(|f| f(p)) && m.distance_sqr(p.position) <= max * max && (p.position.y - m.position.y).abs() <= max + 3.0 }) @@ -1573,10 +1588,12 @@ impl Goal for AvoidEntity { Avoid::Species(list) => { let id = m.id; let y = m.position.y; + let seen_when = self.seen_when; let hit = cx.w.nearby(m.position, max, move |s| { s.id != id && list.contains(&s.species) + && seen_when.is_none_or(|f| f(s)) && (s.position.y - y).abs() <= 3.0 + max }) .map(|s| (s.id, s.position)) From dc36089156d9af32cd00be9dc4f966faea90cd3a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:37:51 +0100 Subject: [PATCH 075/221] Apply the set_name loot function to generated items --- .../examples/probe/entity_death_loot_fixture.rs | 1 + crates/horizon-client/src/game/creatures.rs | 4 ++++ crates/horizon-client/src/item_data.rs | 10 ++++++++++ crates/horizon-client/src/mobs/drops.rs | 1 + crates/horizon-client/src/structure_blocks.rs | 5 +++++ crates/horizon-world/src/loot.rs | 14 +++++++++++++- 6 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs index 3f47ba787..f05bd8b83 100644 --- a/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_death_loot_fixture.rs @@ -24,6 +24,7 @@ fn stack(spec: &str) -> LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; for e in parts { let (name, level) = e.rsplit_once(':').unwrap_or((e, "1")); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 845d2aee6..50fd5ddf5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3342,6 +3342,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), } } /// A generated loot stack as a Horizon item stack. @@ -3361,6 +3362,9 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) { item.data_mut().ominous_amplifier = Some(amplifier as u8); } + for (id, text) in &stack.names { + item.data_mut().set_loot_name(id, text); + } item } impl Game<'_> { diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index ac624e85b..0c4adbd55 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -90,6 +90,16 @@ impl StackData { pub fn other(&self, id: &str) -> Option<&Tag> { self.other.iter().find(|(k, _)| k == id).map(|(_, v)| v) } + /// `SetNameFunction.run`: a loot text component stored as `custom_name` + /// (plain text, as modelled) or as the unmodelled `item_name`. + pub fn set_loot_name(&mut self, id: &str, text: &serde_json::Value) { + let tag = crate::scoreboard::json_to_tag(text); + if id == "minecraft:custom_name" { + self.custom_name = read_text(&tag); + } else { + self.set_other(id, Some(tag)); + } + } /// Set (or with None remove) an unmodelled component. pub fn set_other(&mut self, id: &str, value: Option) { self.other.retain(|(k, _)| k != id); diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index c7b1c77e1..4d4166e53 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -305,6 +305,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), } } /// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 604cf7925..909d69926 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -69,6 +69,9 @@ pub fn loot_item_with_components(s: &horizon_world::loot::LootStack) -> ItemStac .stew_effects .push((Arc::from(effect.as_str()), *duration)); } + for (id, text) in &s.names { + item.data_mut().set_loot_name(id, text); + } item } @@ -255,6 +258,7 @@ mod tests { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; // An End city chest's enchant_with_levels roll. let boots = loot_item_with_components(&stack( @@ -317,6 +321,7 @@ mod tests { })))), ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), }; let mut item = loot_item(&stack); assert!(has_pending_map(&item)); diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index f98afa21f..19651ee99 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -34,6 +34,8 @@ pub struct LootStack { /// Added by set_stew_effect (the `suspicious_stew_effects` component): /// (effect id, duration in ticks). pub stew_effects: Vec<(String, i32)>, + /// Set by set_name: (`custom_name` or `item_name`, the text component). + pub names: Vec<(String, Value)>, } /// `ExplorationMapFunction`'s settings. #[derive(Clone, Debug, PartialEq, Eq)] @@ -78,6 +80,7 @@ impl LootStack { exploration: None, ominous_amplifier: None, stew_effects: Vec::new(), + names: Vec::new(), } } pub fn is_empty(&self) -> bool { @@ -1219,7 +1222,16 @@ impl Context<'_, R> { stack = smelted; } } - // Names, lore, components and other data without random draws. + // SetNameFunction: the component the target names (custom_name by + // default). The entity-resolved selectors and scores are not + // modelled; no table uses `entity`. + "minecraft:set_name" if !f["name"].is_null() => { + let target = f["target"].as_str().unwrap_or("custom_name"); + let id = format!("minecraft:{target}"); + stack.names.retain(|(k, _)| *k != id); + stack.names.push((id, f["name"].clone())); + } + // Lore, components and other data without random draws. _ => {} } stack From de2df51193171de808cbd3e6a79add64aa012e39 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:38:43 +0100 Subject: [PATCH 076/221] Wolf armor: put it on, repair it, shear it off, and let it take the damage --- crates/horizon-client/src/entity_nbt.rs | 15 +++++ crates/horizon-client/src/game/creatures.rs | 54 +++++++++++++++++ crates/horizon-client/src/game/lan.rs | 7 ++- crates/horizon-client/src/game/remote.rs | 17 ++++-- crates/horizon-client/src/mobs.rs | 65 ++++++++++++++++++++- crates/horizon-client/src/mobs/drops.rs | 4 ++ crates/horizon-client/src/mobs/render.rs | 26 ++++++++- crates/horizon-client/src/mobs/species.rs | 9 ++- 8 files changed, 186 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..18f89d884 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -544,6 +544,16 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { equipment.insert(slot.into(), crate::save::item_to_nbt(&stack)); continue; } + // A wolf's armor keeps the durability it lost. + if slot == "body" + && m.species() == crate::mobs::Species::Wolf + && let Some(id) = item + { + let mut stack = crate::items::ItemStack::new(id, 1); + stack.damage = m.extra.body_damage.max(0) as u32; + equipment.insert(slot.into(), crate::save::item_to_nbt(&stack)); + continue; + } match item { Some(id) => { let keep = matches!( @@ -780,6 +790,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - crate::mobs::tame::set_tame(&mut m, tame); m.health = health; m.extra.sitting = flag(tag, "Sitting"); + m.extra.body_damage = tag + .get("equipment") + .and_then(|e| e.get("body")) + .and_then(crate::save::item_from_nbt) + .map_or(0, |s| s.damage as i32); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); if let Some(Tag::String(v)) = tag.get("variant") { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index d192a2b02..a72d53c6b 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2559,12 +2559,18 @@ impl Game<'_> { .items() .get(&item) .is_some_and(|i| i.max_damage > 0); + let me = self.level.player_uuid.or(Some([0, 0, 0, 1])); + let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) + || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight); + let held_damage = held.as_ref().map_or(0, |h| h.damage as i32); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); } let species = m.species(); let center = m.center(); + // Wolf armor the owner takes off with shears or leaves a dropped stack of. + let mut armor_drop: Option = None; let mut consume = false; let mut give: Option<&str> = None; let mut sound: Option<&str> = None; @@ -2637,6 +2643,22 @@ impl Game<'_> { handled = false; } } + // Entity.interact: shears take a tamed wolf's armor off for its owner. + Species::Wolf + if item == "minecraft:shears" + && m.extra.tame + && m.extra.owner == me + && m.extra.head.is_some() + && !sneaking => + { + let mut stack = ItemStack::new("minecraft:wolf_armor", 1); + stack.damage = m.extra.body_damage.max(0) as u32; + armor_drop = Some(stack); + m.extra.head = None; + m.extra.body_damage = 0; + eat = Some(("item.armor.unequip_wolf", 1.0, 1.0)); + self.damage_held_tool(); + } // Wolf.mobInteract: heal, dye the collar or sit/stand when tame; // a bone tames a wild one a third of the time. Species::Wolf if m.extra.tame && is_food && m.health < m.attrs.max_health => { @@ -2650,6 +2672,35 @@ impl Game<'_> { m.health = (m.health + heal).min(m.attrs.max_health); consume = true; } + // Wolf.mobInteract: the owner puts wolf armor on a tamed adult. + Species::Wolf + if item == "minecraft:wolf_armor" + && m.extra.tame + && m.extra.owner == me + && m.extra.head.is_none() + && !m.is_baby() => + { + m.extra.head = Some(item.as_str().into()); + m.extra.body_damage = held_damage; + consume = true; + eat = Some(("item.armor.equip_wolf", 1.0, 1.0)); + } + // Wolf.mobInteract: an armadillo scute repairs a sitting wolf's + // armor by an eighth of its durability. + Species::Wolf + if item == "minecraft:armadillo_scute" + && m.extra.tame + && m.extra.owner == me + && m.extra.sitting + && m.extra.head.is_some() + && m.extra.body_damage > 0 => + { + m.extra.body_damage = (m.extra.body_damage + - (horizon_client::mobs::WOLF_ARMOR_DURABILITY as f32 * 0.125) as i32) + .max(0); + consume = true; + eat = Some(("item.wolf_armor.repair", 1.0, 1.0)); + } Species::Wolf if m.extra.tame && item.ends_with("_dye") @@ -2897,6 +2948,9 @@ impl Game<'_> { self.spawn_item(rest, at, [0.0, 0.0, 0.0], 40); } } + if let Some(stack) = armor_drop { + self.spawn_item(stack, [center[0], center[1] + 0.5, center[2]], [0.0; 3], 10); + } for (item, count) in drops { for _ in 0..count { let v = [ diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..7897b5c57 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -379,7 +379,12 @@ fn mob_equipment( let stack = ItemStack { item: item.clone(), count: 1, - damage: 0, + // A wolf's armor shows its cracks. + damage: if slot == 5 && m.species() == horizon_client::mobs::Species::Wolf { + e.body_damage.max(0) as u32 + } else { + 0 + }, extra: None, }; out.push((slot, hub.stack(&Some(stack)))); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..7077023b8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2011,13 +2011,19 @@ impl Game<'_> { // player holds and wears (EquipmentSlot ordinals). C::SetEquipment(p) => { self.remote_object_equipment(p.id, &p.slots); - let items: Vec<(u8, Option>)> = p + let items: Vec<(u8, Option>, i32)> = p .slots .iter() - .map(|(slot, stack)| (*slot, stack.as_ref().map(|s| self.item_name(s.item)))) + .map(|(slot, stack)| { + ( + *slot, + stack.as_ref().map(|s| self.item_name(s.item)), + self.to_stack(stack).map_or(0, |s| s.damage as i32), + ) + }) .collect(); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - for (slot, item) in items { + for (slot, item, damage) in items { let e = &mut m.extra; match slot { 0 => e.main_hand = item, @@ -2025,7 +2031,10 @@ impl Game<'_> { 2 => e.feet = item, 3 => e.legs = item, 4 => e.chest = item, - 5 => e.head = item, + 5 => { + e.head = item; + e.body_damage = damage; + } _ => {} } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4b67f738f..f9a53f0f2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -631,6 +631,8 @@ pub struct Attrs { pub spawn_reinforcements: f64, pub jump_strength: f64, } +/// `minecraft:wolf_armor`'s maximum damage. +pub const WOLF_ARMOR_DURABILITY: i32 = 64; /// Species-specific persistent state (variants, colours, taming, ageing...). #[derive(Clone, Debug, Default)] pub struct Extra { @@ -659,6 +661,8 @@ pub struct Extra { /// `Mob.canPickUpLoot` (also lets dispensers equip it). pub pick_up_loot: bool, pub saddled: bool, + /// The durability a wolf's body armor (`extra.head`) has lost. + pub body_damage: i32, /// The saddle's components (name, enchantments...) when it is not a bare /// one; `saddled` stays the gameplay flag. pub saddle_stack: Option, @@ -1752,18 +1756,29 @@ impl Mob { if epf > 0.0 { amount *= 1.0 - epf / 25.0; } + // Wolf.actuallyHurt: wolf armor takes the damage instead of the wolf. + let absorbed = self.wolf_armor_absorbs(&source); let mut knock = true; if self.invulnerable as f32 > 10.0 { if amount <= self.last_hurt { return false; } - self.health -= amount - self.last_hurt; + let dealt = amount - self.last_hurt; + if absorbed { + self.hurt_wolf_armor(dealt); + } else { + self.health -= dealt; + } self.last_hurt = amount; knock = false; } else { self.last_hurt = amount; self.invulnerable = 20; - self.health -= amount; + if absorbed { + self.hurt_wolf_armor(amount); + } else { + self.health -= amount; + } self.hurt_time = 10; } // Animal.actuallyHurt: damage taken ends love mode (`resetLove`). @@ -1794,7 +1809,12 @@ impl Mob { // playHurtSound (Mob: also resets the ambient sound clock) or the // death sound: makeSound draws the voice pitch whenever there is a sound. let dead = !self.alive(); - let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }]; + // Wolf.getHurtSound: the armor's own sound when it takes the hit. + let sound = if absorbed { + "item.wolf_armor.damage" + } else { + ai::voice_sounds(self)[if dead { 2 } else { 1 }] + }; if !dead { self.ambient_timer = -self.kind.ambient_interval; } @@ -1809,6 +1829,45 @@ impl Mob { } true } + /// `Wolf.canArmorAbsorb`: it wears wolf armor and the damage type is not + /// in `#bypasses_wolf_armor` (drowning, magic, thorns, in a wall, out of + /// the world and the untyped kills). + fn wolf_armor_absorbs(&self, source: &Damage) -> bool { + self.species() == Species::Wolf + && self.extra.head.as_deref() == Some("minecraft:wolf_armor") + && !matches!( + source.kind, + DamageKind::Drown + | DamageKind::Magic + | DamageKind::InWall + | DamageKind::Thorns + | DamageKind::OutOfWorld + | DamageKind::Generic + ) + } + /// `Wolf.actuallyHurt`: the armor loses `ceil(damage)` durability, cracks + /// at `Crackiness.WOLF_ARMOR` steps and breaks at its maximum. + fn hurt_wolf_armor(&mut self, damage: f32) { + let crack = |lost: i32| { + let left = (WOLF_ARMOR_DURABILITY - lost) as f32 / WOLF_ARMOR_DURABILITY as f32; + [0.95_f32, 0.69, 0.32].iter().filter(|t| left < **t).count() + }; + let before = self.extra.body_damage; + let after = before + damage.ceil() as i32; + let at = [self.position.x, self.position.y, self.position.z]; + if after >= WOLF_ARMOR_DURABILITY { + self.extra.head = None; + self.extra.body_damage = 0; + self.outbox + .push(MobEvent::Sound("item.wolf_armor.break", at, 1.0, 1.0)); + } else { + self.extra.body_damage = after; + if crack(before) != crack(after) { + self.outbox + .push(MobEvent::Sound("item.wolf_armor.crack", at, 1.0, 1.0)); + } + } + } /// LivingEntity.knockback(power, xd, zd) towards the negative direction. pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) { let power = power * (1.0 - self.attrs.knockback_resistance); diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index c7b1c77e1..28ba2a0cd 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -245,6 +245,9 @@ pub fn slot_item(m: &Mob, slot: &str) -> Option { _ => (None, None), }; let mut stack = loot_stack(item?, 1); + if slot == "body" && m.species() == Species::Wolf { + stack.damage = m.extra.body_damage; + } if let (Some(index), Some(g)) = (index, gear::gear(m)) { for (e, l) in &g.slots[index] { stack.enchantments.push((e.to_string(), *l as i32)); @@ -282,6 +285,7 @@ pub fn clear_slot(m: &mut Mob, slot: &str) { } "body" if body => { m.extra.head = None; + m.extra.body_damage = 0; return; } "saddle" => { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..1e7286598 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -352,13 +352,37 @@ pub fn layers(m: &Mob) -> Vec { }) }; match m.species() { - // WolfCollarLayer. + // WolfArmorLayer, then WolfCollarLayer. S::Wolf if m.extra.tame => { let (model, texture) = if m.is_baby() { ("wolf_baby#main", "entity/wolf/wolf_collar_baby") } else { ("wolf#main", "entity/wolf/wolf_collar") }; + // The armor, then the cracks of its damage (`Crackiness.WOLF_ARMOR`). + if !m.is_baby() && m.extra.head.as_deref() == Some("minecraft:wolf_armor") { + let left = (super::WOLF_ARMOR_DURABILITY - m.extra.body_damage) as f32 + / super::WOLF_ARMOR_DURABILITY as f32; + push( + &mut v, + "wolf_armor#main", + "entity/equipment/wolf_body/armadillo_scute", + white, + false, + ); + let crack = [(0.32, "high"), (0.69, "medium"), (0.95, "low")] + .iter() + .find(|(t, _)| left < *t); + if let Some((_, level)) = crack { + push( + &mut v, + "wolf_armor#main", + &format!("entity/wolf/wolf_armor_crackiness_{level}"), + white, + false, + ); + } + } push( &mut v, model, diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index f48a21fe9..95a342ca3 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1690,10 +1690,15 @@ impl Def { } } /// Mobs whose `body` equipment slot Horizon keeps in `Extra::head` (a -/// happy ghast's harness, nautilus armour, a sulfur cube's swallowed block). +/// happy ghast's harness, nautilus armour, a sulfur cube's swallowed block, +/// a wolf's armor). pub fn body_slot(s: Species) -> bool { matches!( s, - Species::HappyGhast | Species::Nautilus | Species::ZombieNautilus | Species::SulfurCube + Species::HappyGhast + | Species::Nautilus + | Species::ZombieNautilus + | Species::SulfurCube + | Species::Wolf ) } From 9ca7162169b8db523223534eaa4874ea937e1be8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:39:14 +0100 Subject: [PATCH 077/221] Let a tame parrot sit on its owner's shoulder A tame parrot never landed on its owner. Add LandOnOwnersShoulderGoal: when the parrot touches its owner, it is stored in the player's ShoulderEntityLeft or ShoulderEntityRight and removed from the world. It comes back, still tame, when the player falls, swims, flies, sleeps, is hurt, dies, turns spectator or spins with a riptide. The shoulder data is the player's own save data, so it also works for players on the integrated server and for LAN guests. --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/creatures.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 4 + crates/horizon-client/src/game/lan_mobs.rs | 1 + crates/horizon-client/src/game/shoulders.rs | 120 ++++++++++++++++++ crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/tame.rs | 29 +++++ 7 files changed, 164 insertions(+) create mode 100644 crates/horizon-client/src/game/shoulders.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..2acbfb4f9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -156,6 +156,7 @@ mod server_packs; mod server_travel; mod shader_packs; mod shield; +mod shoulders; mod sign_edit; mod sniffers; mod spawner; @@ -4574,6 +4575,7 @@ impl Game<'_> { } self.powder_snow_fire()?; self.tick_totem(); + self.handle_shoulder_entities(); let Some(player) = self.player.as_mut() else { return Ok(()); }; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8eb4cc911..1a04ef0eb 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -49,6 +49,8 @@ pub(super) struct Creatures { pub elder_apparition: i32, /// The wandering trader spawner's clock. pub trader: super::wandering_trader::Spawner, + /// When each player last put a parrot on a shoulder (`timeEntitySatOnShoulder`). + pub shoulder_time: std::collections::HashMap<[i32; 4], i64>, } pub(super) struct ProjWorld<'a, 'w> { pub w: &'a MobWorld<'w>, @@ -992,6 +994,7 @@ impl Game<'_> { } MobEvent::BecomeStatue { mob } => self.golem_become_statue(mob), MobEvent::EnterHive { mob, hive } => self.bee_enter_hive(mob, hive), + MobEvent::ParrotToShoulder { mob } => self.parrot_to_shoulder(mob), MobEvent::Gift { target, item } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == target) && m.saddle_item().is_none() diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..6e7f63f9c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -378,6 +378,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); + std::mem::swap(&mut self.level.player_extra, &mut g.saved); std::mem::swap(&mut self.stats, &mut play.stats); std::mem::swap(&mut self.hook, &mut play.hook); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); @@ -610,6 +611,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); + std::mem::swap(&mut self.level.player_extra, &mut g.saved); std::mem::swap(&mut self.stats, &mut play.stats); std::mem::swap(&mut self.hook, &mut play.hook); self.adv.loaded = adv_loaded; @@ -2178,6 +2180,7 @@ impl Game<'_> { if !g.effects.list.is_empty() { self.as_guest(host, conn, |game| game.tick_mob_effects()); } + self.as_guest(host, conn, |game| game.handle_shoulder_entities()); return; } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); @@ -2279,6 +2282,7 @@ impl Game<'_> { // LivingEntity.baseTick: outside the world border, then tickEffects. game.border_damage(); game.tick_mob_effects(); + game.handle_shoulder_entities(); let Some(player) = game.player.as_mut() else { return (Vec::new(), None); }; diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..4555474a5 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -80,6 +80,7 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { } | MobEvent::EffectPlayer { .. } | MobEvent::AxolotlSupportPlayer + | MobEvent::ParrotToShoulder { .. } ) } diff --git a/crates/horizon-client/src/game/shoulders.rs b/crates/horizon-client/src/game/shoulders.rs new file mode 100644 index 000000000..602c5a5af --- /dev/null +++ b/crates/horizon-client/src/game/shoulders.rs @@ -0,0 +1,120 @@ +//! Parrots on a player's shoulder: a tame parrot lands on its owner +//! (`LandOnOwnersShoulderGoal`), is kept as the player's `ShoulderEntityLeft` +//! or `ShoulderEntityRight`, and flies off again when the player is hurt, +//! falls, swims, flies or sleeps (`ServerPlayer.handleShoulderEntities`). +use super::Game; +use horizon_client::mobs::Species; +use horizon_world::nbt::Tag; + +const KEYS: [&str; 2] = ["ShoulderEntityLeft", "ShoulderEntityRight"]; + +/// A shoulder slot holds a parrot when its compound is not empty. +fn occupied(extra: &Tag, key: &str) -> bool { + matches!(extra.get(key), Some(Tag::Compound(c)) if !c.is_empty()) +} + +impl Game<'_> { + /// `ServerPlayer.setEntityOnShoulder` for a parrot that touched its + /// owner: stored in the first free slot, the parrot gone from the world. + pub(super) fn parrot_to_shoulder(&mut self, mob: u32) { + let Some(i) = self + .mobs + .iter() + .position(|m| m.id == mob && m.alive() && !m.removed && m.species() == Species::Parrot) + else { + return; + }; + let Some(p) = self.player.as_ref() else { + return; + }; + if self.riding.is_some() + || !p.ground.on_ground + || p.fluids.was_touching_water + || p.in_powder_snow + || p.flying + { + return; + } + let extra = self + .level + .player_extra + .get_or_insert_with(|| Tag::Compound(Default::default())); + let Some(key) = KEYS.into_iter().find(|k| !occupied(extra, k)) else { + return; + }; + let tag = self.mob_tree_nbt(i); + if let Some(Tag::Compound(map)) = self.level.player_extra.as_mut() { + map.insert(key.into(), tag); + } + let (uuid, now) = (self.acting_uuid(), self.world.game_time); + self.creatures.shoulder_time.insert(uuid, now); + self.mobs[i].removed = true; + } + + /// `ServerPlayer.handleShoulderEntities`: the parrots leave the shoulder + /// of a player who falls, swims, flies, sleeps, is hurt, dying, a + /// spectator or spinning with a riptide. + pub(super) fn handle_shoulder_entities(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let any = self + .level + .player_extra + .as_ref() + .is_some_and(|e| KEYS.iter().any(|k| occupied(e, k))); + if any + && (p.fall_distance > 0.5 + || p.fluids.was_touching_water + || p.flying + || p.spectator + || p.in_powder_snow + || p.auto_spin_attack_ticks > 0 + || p.health.hurt.hurt_time > 0 + || p.health.dead_or_dying() + || self.sleeping.is_some()) + { + self.remove_entities_on_shoulder(); + } + } + + /// `ServerPlayer.removeEntitiesOnShoulder` (not within a second of the + /// landing) and `respawnEntityOnShoulder`: the parrots come back at the + /// player, still owned by them. + fn remove_entities_on_shoulder(&mut self) { + let (uuid, now) = (self.acting_uuid(), self.world.game_time); + if self + .creatures + .shoulder_time + .get(&uuid) + .is_some_and(|t| t + 20 >= now) + { + return; + } + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let Some(Tag::Compound(map)) = self.level.player_extra.as_mut() else { + return; + }; + let tags: Vec = KEYS + .iter() + .filter_map(|k| map.remove(&(*k).into())) + .collect(); + let pos = [p.x, p.y + f64::from(0.7_f32), p.z]; + for mut tag in tags { + let Tag::Compound(c) = &mut tag else { + continue; + }; + if c.is_empty() { + continue; + } + c.insert( + "Pos".into(), + Tag::List(pos.iter().map(|v| Tag::Double(v.to_bits())).collect()), + ); + c.insert("Owner".into(), Tag::IntArray(uuid.to_vec())); + self.load_mob(tag, None); + } + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 4b67f738f..b7e38bb01 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -894,6 +894,11 @@ pub enum MobEvent { mob: u32, hive: [i32; 3], }, + /// `LandOnOwnersShoulderGoal`: a tame parrot touched its owner and sits + /// on their shoulder (the host stores its tag and discards it). + ParrotToShoulder { + mob: u32, + }, /// `CopperGolem.turnToStatue`. BecomeStatue { mob: u32, diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 0043ff9ef..82d808b7f 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -110,6 +110,35 @@ pub fn register_parrot(m: &mut Mob) { g.add(2, SitWhenOrdered); g.add(2, FollowOwner::new(1.0, 5.0, 1.0)); g.add(2, Stroll::avoiding_water(1.0)); + g.add(3, LandOnOwnersShoulder); +} +/// `LandOnOwnersShoulderGoal`: a standing parrot, 100 ticks old, lands on +/// the shoulder of the owner it touches; the host does the landing. +#[derive(Clone, Debug)] +struct LandOnOwnersShoulder; +impl Goal for LandOnOwnersShoulder { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // ShoulderRidingEntity.canSitOnShoulder: rideCooldownCounter > 100. + owner(m, cx.w).is_some_and(|(_, _, spectator)| !spectator) + && !m.extra.sitting + && m.age > 100 + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if !m.extra.sitting + && m.extra.leash.is_none() + && cx + .w + .player + .as_ref() + .is_some_and(|p| m.bounds().intersects(p.bounds)) + { + cx.events.push(MobEvent::ParrotToShoulder { mob: m.id }); + } + } } /// `Wolf.PREY_SELECTOR`: sheep, rabbits and foxes. fn wolf_prey(s: &super::Seen) -> bool { From 2886b8f9badc4cb7e4e7a775a84ef83e961751b9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:39:31 +0100 Subject: [PATCH 078/221] Horse armor reduces the damage a horse takes --- crates/horizon-client/src/mobs.rs | 8 +++++++- crates/horizon-client/src/mobs/spawning.rs | 13 +++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..e64d81f39 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1694,8 +1694,14 @@ impl Mob { /// the last-hurt-by bookkeeping goals read. /// The `armor` and `armor_toughness` modifiers of worn humanoid armour. pub fn worn_armor(&self) -> (f32, f32) { + // An equine keeps its horse armor in `extra.head`: the item's `armor` + // and `armor_toughness` modifiers of the body slot. if equine::is_equine(self.species()) { - return (0.0, 0.0); + return self + .extra + .head + .as_deref() + .map_or((0.0, 0.0), spawning::horse_armor_stats); } [ &self.extra.head, diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 93e3fe119..50d311db3 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -96,6 +96,19 @@ pub fn armor_stats(item: &str) -> (f32, f32) { }; (points[slot], toughness) } +/// The armour and toughness a horse armor item adds in the body slot +/// (`ArmorMaterial.createAttributes(ArmorType.BODY)`). +pub fn horse_armor_stats(item: &str) -> (f32, f32) { + match item.strip_prefix("minecraft:") { + Some("leather_horse_armor") => (3.0, 0.0), + Some("copper_horse_armor") => (4.0, 0.0), + Some("iron_horse_armor") => (5.0, 0.0), + Some("golden_horse_armor") => (7.0, 0.0), + Some("diamond_horse_armor") => (11.0, 2.0), + Some("netherite_horse_armor") => (19.0, 3.0), + _ => (0.0, 0.0), + } +} /// `Mob.populateDefaultEquipmentSlots`: sometimes a set of armour, from the /// head down, of one random material. fn populate_armor(m: &mut Mob, d: &LocalDifficulty) { From 50fdcad10fed4dc812228d0cd24390d3ed326002 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:40:42 +0100 Subject: [PATCH 079/221] A cookie poisons and kills a parrot --- crates/horizon-client/src/game/creatures.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 845d2aee6..45568dc12 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2560,6 +2560,7 @@ impl Game<'_> { .items() .get(&item) .is_some_and(|i| i.max_damage > 0); + let player_at = self.eye_position(); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2816,6 +2817,24 @@ impl Game<'_> { consume = true; } } + // Parrot.mobInteract: #parrot_poisonous_food (a cookie) poisons the + // parrot for 45 s and then hurts it with a player attack of + // Float.MAX_VALUE, which an invulnerable one shrugs off. + Species::Parrot + if self + .res + .items() + .item_tags + .get("minecraft:parrot_poisonous_food") + .is_some_and(|t| t.contains(&*item)) => + { + consume = true; + m.add_effect("minecraft:poison", 900, 0); + m.damage( + f32::MAX, + horizon_client::mobs::Damage::player(player_at.unwrap_or(center)), + ); + } // Parrot.mobInteract: parrot food may tame a wild one (one time in // ten); a parrot never takes it as Animal food (isFood is false). Species::Parrot if !m.extra.tame && is_food => { From c439b806b8b4922a8403cba5c2f5e24c82668a2d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:40:59 +0100 Subject: [PATCH 080/221] Let a compass lock onto a lodestone Using a compass on a lodestone now sets its lodestone target (in place for a single compass in survival, otherwise one is split off), and the target clears when the lodestone is gone. The target also travels in item packets on the server thread. --- crates/horizon-client/src/game.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 1 + crates/horizon-client/src/game/maps.rs | 87 +++++++++++++++++++ crates/horizon-client/src/item_sync.rs | 16 ++++ crates/horizon-client/src/lan/guest.rs | 15 ++++ crates/horizon-protocol/src/item.rs | 28 +++++- 6 files changed, 148 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..2ad3f10a2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3762,6 +3762,7 @@ impl Game<'_> { || self.place_minecart(hit, &stack) || self.place_painting(hit, &stack) || self.place_item_frame(hit, &stack) + || self.use_lodestone_compass(hit, &stack) || self.place_armor_stand(hit, &stack) || self.place_cushion(hit, &stack) || self.place_end_crystal(hit, &stack)) @@ -4661,6 +4662,7 @@ impl Game<'_> { horizon_client::spans::time("tick_thunder", || self.tick_thunder()); horizon_client::spans::time("tick_lecterns", || self.tick_lecterns()); horizon_client::spans::time("tick_maps", || self.tick_maps()); + self.tick_lodestone_compasses(); horizon_client::spans::time("tick_bolts", || self.tick_bolts()); horizon_client::spans::time("tick_fishing", || self.tick_fishing()); horizon_client::spans::time("tick_tridents", || self.tick_tridents()); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..e4f2d063c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1983,6 +1983,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { g.tick_fishing(); g.tick_maps(); + g.tick_lodestone_compasses(); g.count_tick_stats(sleeping); g.tick_advancements(); g.update_player_attributes(); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 6da65c592..f688c8298 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -714,6 +714,93 @@ impl Game<'_> { self.swing_arm(); true } + /// `CompassItem.useOn`: a compass used on a lodestone locks onto it (a + /// single one in survival changes in place, else one is split off). + pub(super) fn use_lodestone_compass(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:compass" { + return false; + } + let [x, y, z] = hit.pos; + if self + .res + .facts() + .get(self.world.block(x, y, z)) + .name + .as_ref() + != "minecraft:lodestone" + { + return false; + } + let at = [x, y, z].map(|v| f64::from(v) + 0.5); + self.audio + .play("minecraft:item.lodestone_compass.lock", Some(at), 1.0, 1.0); + let target = Tag::compound([( + "target", + Tag::compound([ + ("dimension", Tag::String(self.dimension_id().into())), + ("pos", Tag::IntArray(vec![x, y, z])), + ]), + )]); + if !self.creative && stack.count == 1 { + if let Some(held) = self.held_mut() { + held.data_mut() + .set_other("minecraft:lodestone_tracker", Some(target)); + } + } else { + let mut locked = stack.clone(); + locked.count = 1; + locked + .data_mut() + .set_other("minecraft:lodestone_tracker", Some(target)); + self.consume_held(); + self.give_or_drop_stack(locked); + } + self.stats.add("used", &stack.item, 1); + self.swing_arm(); + true + } + /// `CompassItem.inventoryTick` / `LodestoneTracker.tick`: a compass whose + /// lodestone is gone loses its target. A target in an unloaded chunk waits. + pub(super) fn tick_lodestone_compasses(&mut self) { + let dim = self.dimension_id(); + let gone = |game: &Self, stack: &ItemStack| -> bool { + let Some(tracker) = stack + .data() + .and_then(|d| d.other("minecraft:lodestone_tracker")) + else { + return false; + }; + let (Some(target), true) = ( + tracker.get("target"), + horizon_client::save::number(tracker.get("tracked")).is_none_or(|v| v != 0), + ) else { + return false; + }; + let Some(Tag::IntArray(pos)) = target.get("pos") else { + return false; + }; + let [x, y, z] = [pos[0], pos[1], pos[2]]; + horizon_client::save::text(target.get("dimension")).as_deref() == Some(dim) + && game.world.chunks.contains_key(&(x >> 4, z >> 4)) + && game + .res + .facts() + .get(game.world.block(x, y, z)) + .name + .as_ref() + != "minecraft:lodestone" + }; + for slot in (0..self.inventory.len()).chain([super::shield::OFFHAND_SLOT]) { + if self.stack_in(slot).is_some_and(|s| gone(self, s)) + && let Some(s) = self.stack_in_mut(slot) + { + s.data_mut().set_other( + "minecraft:lodestone_tracker", + Some(Tag::Compound(Default::default())), + ); + } + } + } fn give_or_drop_stack(&mut self, stack: ItemStack) { if let Some(rest) = self.give(stack) && let Some(eye) = self.eye_position() diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index fc35e15e7..fbc841ce1 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -95,6 +95,22 @@ fn components_tag(s: &Stack, builtin: &Builtin, synced: &Dynamic) -> Option ), ]), Component::FireworkExplosion(e) => fireworks_tag(e), + Component::LodestoneTracker { target, tracked } => { + let mut entries = Vec::new(); + if let Some((dimension, pos)) = target { + entries.push(( + "target", + Tag::compound([ + ("dimension", Tag::String(dimension.as_str().into())), + ("pos", Tag::IntArray(pos.to_vec())), + ]), + )); + } + if !tracked { + entries.push(("tracked", Tag::Byte(0))); + } + Tag::compound(entries) + } Component::Enchantments(list) => { // Enchantments are a synced (data-driven) registry: the // ids index the server's RegistryData, not the builtin diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 7e43cf04e..e5078644b 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -576,6 +576,21 @@ fn network_stack( )); } stack.added.extend(firework_components(d)); + // The compass's lodestone target. + if let Some(t) = d.other("minecraft:lodestone_tracker") { + let target = t.get("target").and_then(|g| { + let Some(horizon_world::nbt::Tag::IntArray(pos)) = g.get("pos") else { + return None; + }; + let dimension = crate::save::text(g.get("dimension"))?; + Some((dimension, [*pos.first()?, *pos.get(1)?, *pos.get(2)?])) + }); + let tracked = crate::save::number(t.get("tracked")).is_none_or(|v| v != 0); + stack.added.push(( + horizon_protocol::item::component::LODESTONE_TRACKER, + horizon_protocol::item::Component::LodestoneTracker { target, tracked }, + )); + } // PotionContents: the potion by its `minecraft:potion` id. if let Some(id) = (d.potion.as_deref()).and_then(|potion| { synced_id( diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 3d5bacfe9..07523b8f1 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -3,7 +3,7 @@ //! client sends back in container clicks (HashedStack). use crate::{ Result, - buf::{Codec, Reader, Writer}, + buf::{Codec, Reader, Writer, pack_block_pos, unpack_block_pos}, }; use horizon_world::nbt::Tag; @@ -40,6 +40,7 @@ pub mod component { pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; pub const TRIM: i32 = 58; + pub const LODESTONE_TRACKER: i32 = 69; pub const FIREWORK_EXPLOSION: i32 = 70; pub const FIREWORKS: i32 = 71; } @@ -99,6 +100,12 @@ pub enum Component { }, /// `FireworkExplosion` (a firework star). FireworkExplosion(FireworkExplosion), + /// `LodestoneTracker`: the target's dimension and block, and whether it + /// follows the lodestone. + LodestoneTracker { + target: Option<(String, [i32; 3])>, + tracked: bool, + }, /// `ArmorTrim` naming its material and pattern by registry id (`trim_material`, /// `trim_pattern`); a trim with a direct holder stays [`Component::Raw`]. Trim { @@ -316,6 +323,17 @@ impl Component { } } FIREWORK_EXPLOSION => Self::FireworkExplosion(FireworkExplosion::read(r)?), + LODESTONE_TRACKER => { + let target = if r.bool()? { + Some((r.string(32767)?, unpack_block_pos(r.i64()?))) + } else { + None + }; + Self::LodestoneTracker { + target, + tracked: r.bool()?, + } + } // ArmorTrim.STREAM_CODEC: two holders, each a reference's id plus // one. A direct material or pattern has no registry name: read past. TRIM => { @@ -437,6 +455,14 @@ impl Component { explosions.iter().for_each(|e| e.write(w)); } Self::FireworkExplosion(e) => e.write(w), + Self::LodestoneTracker { target, tracked } => { + w.bool(target.is_some()); + if let Some((dimension, pos)) = target { + w.string(dimension); + w.i64(pack_block_pos(*pos)); + } + w.bool(*tracked); + } Self::WritableBook(pages) => { w.varint(pages.len() as i32); for page in pages { From c30d51d65e1cde584b319f7105c4e772737077ce Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:41:45 +0100 Subject: [PATCH 081/221] Wolves fight other owners' tamed wolves --- crates/horizon-client/src/mobs.rs | 3 +++ crates/horizon-client/src/mobs/tame.rs | 6 ++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..66257ea8e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1215,6 +1215,8 @@ pub struct Seen { pub baby: bool, pub in_love: bool, pub tame: bool, + /// A tamed animal's owner (`getOwner`). + pub owner: Option<[i32; 4]>, pub hostile: bool, pub target: Option, pub health: f32, @@ -1302,6 +1304,7 @@ impl Mob { m.extra.in_love > 0 }, tame: m.extra.tame, + owner: m.extra.owner, hostile: m.hostile(), target: m.ai.target, health: m.health, diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1e725df80..b6d0b1bb7 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -442,7 +442,8 @@ impl Goal for OwnerHurt { m.ai.target = None; } } -/// `Wolf.wantsToAttack`: never creepers, ghasts or tame wolves and cats. +/// `Wolf.wantsToAttack`: never creepers, ghasts, tame cats and parrots, or a +/// tame wolf of the same owner. fn wants_to_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { let Who::Mob(id) = who else { return false; @@ -455,7 +456,8 @@ fn wants_to_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { }; match s.species { Species::Creeper | Species::Ghast => false, - Species::Wolf | Species::Cat | Species::Parrot => !s.tame, + Species::Wolf => !s.tame || s.owner != m.extra.owner, + Species::Cat | Species::Parrot => !s.tame, Species::Horse | Species::Donkey | Species::Mule | Species::Llama => !s.tame, _ => true, } From 63ee634ee03b27b6372b0907857b91a79f90bbb3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:43:42 +0100 Subject: [PATCH 082/221] Apply an armor stand's saved pose The Pose tag of an armor stand is now read and saved, drawn on the stand and its armor, and sent to clients on the server thread. --- crates/horizon-client/src/entities.rs | 16 ++++++ crates/horizon-client/src/entity_nbt.rs | 22 ++++++++ .../horizon-client/src/game/armor_stands.rs | 48 +++++++++++------ .../horizon-client/src/game/lan_entities.rs | 54 ++++++------------- .../horizon-client/src/game/remote_objects.rs | 4 ++ 5 files changed, 91 insertions(+), 53 deletions(-) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 69e053411..f0d1f83a4 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -710,9 +710,24 @@ pub struct ArmorStand { pub name_visible: bool, /// Game time of the last hit (the wobble and the second-hit window). pub last_hit: i64, + /// `DATA_HEAD_POSE` to `DATA_RIGHT_LEG_POSE`: head, body, left arm, right + /// arm, left leg, right leg, in degrees (`POSE_KEYS` order). + pub pose: [[f32; 3]; 6], } impl ArmorStand { pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"]; + /// The `Pose` compound's keys. + pub const POSE_KEYS: [&'static str; 6] = + ["Head", "Body", "LeftArm", "RightArm", "LeftLeg", "RightLeg"]; + /// `ArmorStand.DEFAULT_*_POSE`. + pub const DEFAULT_POSE: [[f32; 3]; 6] = [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [-10.0, 0.0, -10.0], + [-15.0, 0.0, 10.0], + [-1.0, 0.0, -1.0], + [1.0, 0.0, 1.0], + ]; pub fn new(id: u32, position: Vec3, yaw: f32) -> Self { Self { fire_ticks: 0, @@ -731,6 +746,7 @@ impl ArmorStand { custom_name: None, name_visible: false, last_hit: i64::MIN / 2, + pose: Self::DEFAULT_POSE, } } pub fn environment_tick( diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 7f3565067..9bf5b5303 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1494,6 +1494,15 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> } put(&mut tag, "Health", Tag::Float(a.health.to_bits())); put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16)); + // ArmorStand.addAdditionalSaveData: the `Pose` parts that are not default. + let pose: Vec<(&str, Tag)> = ArmorStand::POSE_KEYS + .into_iter() + .zip(a.pose) + .zip(ArmorStand::DEFAULT_POSE) + .filter(|((_, rotation), default)| rotation != default) + .map(|((key, rotation), _)| (key, floats(&rotation))) + .collect(); + put(&mut tag, "Pose", Tag::compound(pose)); // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. if let Tag::Compound(map) = &mut tag { for (key, value) in [ @@ -1533,6 +1542,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { a.invisible = flag(tag, "Invisible"); a.marker = flag(tag, "Marker"); a.on_ground = flag(tag, "OnGround"); + // ArmorStand.readAdditionalSaveData: each part of `Pose` that is a list of + // three numbers, the others staying at their defaults. + if let Some(pose) = tag.get("Pose") { + for (rotation, key) in a.pose.iter_mut().zip(ArmorStand::POSE_KEYS) { + if let Some(Tag::List(values)) = pose.get(key) + && values.len() == 3 + { + for (r, v) in rotation.iter_mut().zip(values) { + *r = float(Some(v)).unwrap_or(0.0) as f32; + } + } + } + } Some(a) } /// A boat entity (`minecraft:_boat`, `minecraft:bamboo_chest_raft`...): diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index f175af401..4b0631fb7 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -622,21 +622,8 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)) * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)); let mut poses = Poses::new(model); - // ArmorStand.DEFAULT_*_POSE and ArmorStandModel part visibility. - let deg = |v: f32| v.to_radians(); - for (name, rot) in [ - ("left_arm", [-10.0, 0.0, -10.0]), - ("right_arm", [-15.0, 0.0, 10.0]), - ("left_leg", [-1.0, 0.0, -1.0]), - ("right_leg", [1.0, 0.0, 1.0]), - ] { - if poses.has(name) { - let pose = poses.get(name); - pose[3] = deg(rot[0]); - pose[4] = deg(rot[1]); - pose[5] = deg(rot[2]); - } - } + // ArmorStandModel.setupAnim: the stand's pose and part visibility. + apply_pose(&mut poses, &a.pose); // Item layers pose from the hidden arms too (`visible` only skips drawing). let posed = poses.clone(); let mut hide = |name: &str| { @@ -706,7 +693,9 @@ impl Game<'_> { let color = undyed.map_or(0xFFFF_FFFF, |c| { 0xFF00_0000 | (c & 0xFF) << 16 | (c & 0xFF00) | (c >> 16) & 0xFF }); - let layer_poses = Poses::new(part); + // ArmorStandArmorModel.setupAnim: the same pose as the stand. + let mut layer_poses = Poses::new(part); + apply_pose(&mut layer_poses, &a.pose); horizon_client::mobs::render::draw( part, base, @@ -738,6 +727,33 @@ impl Game<'_> { } } } +/// The `Pose` rotations on the parts of an armor stand model or its armor +/// (`ArmorStandArmorModel.setupAnim`); the body also turns the sticks. +fn apply_pose(poses: &mut Poses, pose: &[[f32; 3]; 6]) { + let parts: [&[&str]; 6] = [ + &["head"], + &[ + "body", + "right_body_stick", + "left_body_stick", + "shoulder_stick", + ], + &["left_arm"], + &["right_arm"], + &["left_leg"], + &["right_leg"], + ]; + for (names, rotation) in parts.into_iter().zip(pose) { + for name in names { + if poses.has(name) { + let part = poses.get(name); + part[3] = rotation[0].to_radians(); + part[4] = rotation[1].to_radians(); + part[5] = rotation[2].to_radians(); + } + } + } +} fn overlaps(a: Aabb, b: Aabb) -> bool { let (a0, a1, b0, b1) = ( a.min_position(), diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 529666590..cee626117 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -11,18 +11,6 @@ use horizon_client::lan::{ use horizon_protocol::entity_data::{Value, serializer}; use horizon_world::nbt::Tag; -/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg, -/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21), -/// under their `Pose` keys. -const STAND_POSES: [(&str, [f32; 3]); 6] = [ - ("Head", [0.0, 0.0, 0.0]), - ("Body", [0.0, 0.0, 0.0]), - ("LeftArm", [-10.0, 0.0, -10.0]), - ("RightArm", [-15.0, 0.0, 10.0]), - ("LeftLeg", [-1.0, 0.0, -1.0]), - ("RightLeg", [1.0, 0.0, 1.0]), -]; - fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState { EntityState { id: id as i32, @@ -61,28 +49,21 @@ fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Val meta } -/// An armor stand's pose from its compound (`ArmorStandPose`), each part -/// that differs from the default. -fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> { - let Some(pose) = raw.and_then(|t| t.get("Pose")) else { - return Vec::new(); - }; +/// An armor stand's pose (`ArmorStandPose`), each part that differs from the +/// default, as DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21). +fn stand_poses(a: &horizon_client::entities::ArmorStand) -> Vec<(u8, i32, Value)> { let mut meta = Vec::new(); - for (i, (key, default)) in STAND_POSES.iter().enumerate() { - let Some(Tag::List(values)) = pose.get(key) else { - continue; - }; - let mut r = *default; - for (k, v) in values.iter().take(3).enumerate() { - if let Tag::Float(bits) = v { - r[k] = f32::from_bits(*bits); - } - } - if r != *default { + for (i, (rotation, default)) in a + .pose + .iter() + .zip(horizon_client::entities::ArmorStand::DEFAULT_POSE) + .enumerate() + { + if *rotation != default { meta.push(( 16 + i as u8, serializer::ROTATIONS, - Value::Floats(r.to_vec()), + Value::Floats(rotation.to_vec()), )); } } @@ -185,7 +166,7 @@ impl Game<'_> { if flags != 0 { e.meta.push((15, serializer::BYTE, Value::Byte(flags))); } - e.meta.extend(stand_poses(self.persist.raw.get(&a.id))); + e.meta.extend(stand_poses(a)); // Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5. for (slot, item) in a.equipment.iter().enumerate() { if item.is_some() { @@ -510,11 +491,9 @@ mod tests { #[test] fn armor_stand_poses_send_only_what_differs() { - let tag = - horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}") - .unwrap() - .0; - let meta = stand_poses(Some(&tag)); + let mut stand = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0); + stand.pose[0] = [10.0, 20.0, 0.0]; + let meta = stand_poses(&stand); assert_eq!( meta, vec![( @@ -523,6 +502,7 @@ mod tests { Value::Floats(vec![10.0, 20.0, 0.0]) )] ); - assert!(stand_poses(None).is_empty()); + let plain = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0); + assert!(stand_poses(&plain).is_empty()); } } diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 05b1a2b9e..83e00ca0f 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -153,6 +153,10 @@ impl Game<'_> { } (3, Value::Bool(visible)) => a.name_visible = *visible, (9, Value::Float(health)) => a.health = *health, + // ArmorStand.DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE. + (16..=21, Value::Floats(r)) if r.len() == 3 => { + a.pose[usize::from(index - 16)] = [r[0], r[1], r[2]]; + } // ArmorStand.DATA_CLIENT_FLAGS. (15, Value::Byte(flags)) => { a.small = flags & 1 != 0; From 78a5ee0e55c8944114a77f465c1ddbfbb5d5d3f0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:43:53 +0100 Subject: [PATCH 083/221] Let parrots imitate nearby mobs and dance to a jukebox Parrots only ever made their own sound. Follow Parrot.aiStep: one tick in 400 a parrot imitates a random mob within 20 blocks (half the time), and its ambient sound is sometimes a mob's voice. A parrot within 3.46 blocks of a playing jukebox now uses the party pose (level events 1010 and 1011). --- crates/horizon-client/src/game.rs | 6 + crates/horizon-client/src/game/jukebox.rs | 23 +++- crates/horizon-client/src/mobs.rs | 6 + crates/horizon-client/src/mobs/ai.rs | 4 + crates/horizon-client/src/mobs/body_anim.rs | 4 +- crates/horizon-client/src/mobs/parrot.rs | 138 ++++++++++++++++++++ 6 files changed, 179 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/src/mobs/parrot.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 58b89a140..8e4038b80 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2844,6 +2844,12 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + // LevelEventHandler 1010 and 1011: the parrots nearby dance or stop. + LevelEvent::LevelEvent { + id: id @ (1010 | 1011), + pos, + .. + } => self.notify_record_playing([pos.x, pos.y, pos.z], id == 1010), LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index c3ed75ebb..5c55c5f54 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -6,10 +6,15 @@ use super::Game; use horizon_client::{ containers::{BlockEntity, Jukebox}, items::ItemStack, + mobs::Species, particles::{ParticleOptions, ParticleType}, text::Text, }; -use horizon_core::{position::BlockPos, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + position::BlockPos, + random::RandomSource, +}; use horizon_world::level::flags as level_flags; impl Game<'_> { @@ -106,11 +111,27 @@ impl Game<'_> { self.titles .set_overlay(Text::translate("record.nowPlaying", &[description]), true); self.update_song_volumes(); + self.notify_record_playing(pos, true); } fn stop_song(&mut self, pos: [i32; 3]) { if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) { self.audio.stop_and_release(id); } + self.notify_record_playing(pos, false); + } + /// `LevelEventHandler.notifyNearbyEntities` (level events 1010 and 1011): + /// parrots within three blocks of the jukebox start or stop dancing. + pub(super) fn notify_record_playing(&mut self, pos: [i32; 3], playing: bool) { + let min = Vec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); + let area = Aabb::new(min, min.add_vector(Vec3::new(1.0, 1.0, 1.0))) + .inflate(Vec3::new(3.0, 3.0, 3.0)); + for m in self + .mobs + .iter_mut() + .filter(|m| m.species() == Species::Parrot && m.bounds().intersects(area)) + { + m.extra.party_jukebox = playing.then_some(pos); + } } /// `popOutTheItem`: the disc above the jukebox, and the song stops. fn eject_record(&mut self, pos: [i32; 3]) { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..058ab7a09 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -46,6 +46,7 @@ pub mod monster_brain; pub mod nautilus; pub mod nav; pub mod nether; +pub mod parrot; pub mod path; pub mod phantom; pub mod piglin; @@ -667,6 +668,8 @@ pub struct Extra { pub items: Vec>, pub tame: bool, pub sitting: bool, + /// `Parrot.partyParrot` and `jukebox`: the playing jukebox it dances to. + pub party_jukebox: Option<[i32; 3]>, /// The owner's UUID (tamed animals). pub owner: Option<[i32; 4]>, /// Slime/magma cube size (0 = not sized). @@ -1260,6 +1263,8 @@ pub struct Seen { pub stats: [f64; 3], /// `Wolf.isInSittingPose`. pub sitting: bool, + /// `Entity.isSilent`. + pub silent: bool, /// `Entity.isVehicle` or `isPassenger`. pub ridden: bool, } @@ -1335,6 +1340,7 @@ impl Mob { m.attrs.speed, ], sitting: m.extra.sitting, + silent: m.silent, ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), } } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 2676c3a37..20e6dd615 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -581,6 +581,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { "entity.wolf.pant" } } + Species::Parrot => super::parrot::ambient(m, w), Species::Cat if m.extra.tame && m.extra.in_love > 0 => "entity.cat.purr", Species::Cat if !m.extra.tame => "entity.cat.stray_ambient", Species::PolarBear if m.is_baby() => "entity.polar_bear.ambient_baby", @@ -632,6 +633,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } /// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions). fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &mut Vec) { + if m.species() == Species::Parrot { + super::parrot::ai_step(m, w, level_random, events); + } // Witch.aiStep runs before super.aiStep(). if m.species() == Species::Witch { let far = m diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 4411d347b..75d71c110 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -980,7 +980,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { Species::Parrot => { let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; let speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; - let pose = if m.extra.sitting { + let pose = if m.extra.party_jukebox.is_some() { + ParrotPose::Party + } else if m.extra.sitting { ParrotPose::Sitting } else if !m.on_ground && !m.fluids.in_water { ParrotPose::Flying diff --git a/crates/horizon-client/src/mobs/parrot.rs b/crates/horizon-client/src/mobs/parrot.rs new file mode 100644 index 000000000..c50176f7b --- /dev/null +++ b/crates/horizon-client/src/mobs/parrot.rs @@ -0,0 +1,138 @@ +//! What `Parrot.aiStep` adds: imitating the mobs around it (`imitateNearbyMobs`, +//! the ambient sound of `getAmbient`) and dancing near a playing jukebox. +use super::{Mob, MobEvent, MobWorld, Species}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; + +/// `Parrot.MOB_SOUND_MAP` (the happy ghast's is `SoundEvents.EMPTY`: ""). +const IMITATIONS: [(Species, &str); 41] = [ + (Species::Blaze, "entity.parrot.imitate.blaze"), + (Species::Bogged, "entity.parrot.imitate.bogged"), + (Species::Breeze, "entity.parrot.imitate.breeze"), + (Species::CamelHusk, "entity.parrot.imitate.camel_husk"), + (Species::CaveSpider, "entity.parrot.imitate.spider"), + (Species::Creaking, "entity.parrot.imitate.creaking"), + (Species::Creeper, "entity.parrot.imitate.creeper"), + (Species::Drowned, "entity.parrot.imitate.drowned"), + ( + Species::ElderGuardian, + "entity.parrot.imitate.elder_guardian", + ), + (Species::Endermite, "entity.parrot.imitate.endermite"), + (Species::Evoker, "entity.parrot.imitate.evoker"), + (Species::Ghast, "entity.parrot.imitate.ghast"), + (Species::HappyGhast, ""), + (Species::Guardian, "entity.parrot.imitate.guardian"), + (Species::Hoglin, "entity.parrot.imitate.hoglin"), + (Species::Husk, "entity.parrot.imitate.husk"), + (Species::Illusioner, "entity.parrot.imitate.illusioner"), + (Species::MagmaCube, "entity.parrot.imitate.magma_cube"), + (Species::Parched, "entity.parrot.imitate.parched"), + (Species::Phantom, "entity.parrot.imitate.phantom"), + (Species::Piglin, "entity.parrot.imitate.piglin"), + (Species::PiglinBrute, "entity.parrot.imitate.piglin_brute"), + (Species::Pillager, "entity.parrot.imitate.pillager"), + (Species::Ravager, "entity.parrot.imitate.ravager"), + (Species::Shulker, "entity.parrot.imitate.shulker"), + (Species::Silverfish, "entity.parrot.imitate.silverfish"), + (Species::Skeleton, "entity.parrot.imitate.skeleton"), + (Species::Slime, "entity.parrot.imitate.slime"), + (Species::Spider, "entity.parrot.imitate.spider"), + (Species::Stray, "entity.parrot.imitate.stray"), + (Species::Vex, "entity.parrot.imitate.vex"), + (Species::Vindicator, "entity.parrot.imitate.vindicator"), + (Species::Warden, "entity.parrot.imitate.warden"), + (Species::Witch, "entity.parrot.imitate.witch"), + (Species::Wither, "entity.parrot.imitate.wither"), + ( + Species::WitherSkeleton, + "entity.parrot.imitate.wither_skeleton", + ), + (Species::Zoglin, "entity.parrot.imitate.zoglin"), + (Species::Zombie, "entity.parrot.imitate.zombie"), + (Species::ZombieHorse, "entity.parrot.imitate.zombie_horse"), + ( + Species::ZombieNautilus, + "entity.parrot.imitate.zombie_nautilus", + ), + ( + Species::ZombieVillager, + "entity.parrot.imitate.zombie_villager", + ), +]; + +fn imitation(species: Species) -> Option<&'static str> { + IMITATIONS.iter().find(|i| i.0 == species).map(|i| i.1) +} + +/// `Parrot.getPitch`. +fn pitch(random: &mut LegacyRandom) -> f32 { + (random.next_float() - random.next_float()) * 0.2 + 1.0 +} + +/// The start of `Parrot.aiStep`: a jukebox that is gone or farther than +/// 3.46 blocks stops the dance, and one tick in 400 the parrot imitates a +/// mob nearby. +pub fn ai_step( + m: &mut Mob, + w: &MobWorld, + level_random: &mut LegacyRandom, + events: &mut Vec, +) { + if let Some(at) = m.extra.party_jukebox { + let d = |i: usize, v: f64| f64::from(at[i]) + 0.5 - v; + let (x, y, z) = (d(0, m.position.x), d(1, m.position.y), d(2, m.position.z)); + let jukebox = &*w.facts.get(w.world.block(at[0], at[1], at[2])).name == "minecraft:jukebox"; + if x * x + y * y + z * z >= 3.46 * 3.46 || !jukebox { + m.extra.party_jukebox = None; + } + } + if level_random.next_int_bound(400).unwrap_or(1) == 0 { + imitate_nearby_mobs(m, w, level_random, events); + } +} + +/// `Parrot.imitateNearbyMobs`: half the time, a random imitable mob within 20 +/// blocks is heard through the parrot's own mouth. +fn imitate_nearby_mobs( + m: &Mob, + w: &MobWorld, + random: &mut LegacyRandom, + events: &mut Vec, +) { + if !m.alive() || m.silent || random.next_int_bound(2).unwrap_or(1) != 0 { + return; + } + let area = m.bounds().inflate(Vec3::new(20.0, 20.0, 20.0)); + let mobs: Vec<_> = w + .others + .iter() + .filter(|s| s.alive && imitation(s.species).is_some() && s.bounds.intersects(area)) + .collect(); + if mobs.is_empty() { + return; + } + let mob = mobs[random.next_int_bound(mobs.len() as i32).unwrap_or(0) as usize]; + if mob.silent { + return; + } + if let Some(sound) = imitation(mob.species).filter(|s| !s.is_empty()) { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, 0.7, pitch(random))); + } +} + +/// `Parrot.getAmbient`: now and then (outside peaceful) the voice of a random +/// imitable mob instead of the parrot's own. +pub fn ambient(m: &mut Mob, w: &MobWorld) -> &'static str { + if w.difficulty.effective > 0.0 && m.random.next_int_bound(1000).unwrap_or(1) == 0 { + let i = m + .random + .next_int_bound(IMITATIONS.len() as i32) + .unwrap_or(0); + return IMITATIONS[i as usize].1; + } + "entity.parrot.ambient" +} From 94600b266f46779b592f5441d1f2549cf51b27cb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:44:07 +0100 Subject: [PATCH 084/221] Format the fox module order --- crates/horizon-client/src/mobs.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 847177657..aa86f669e 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -29,8 +29,8 @@ pub mod drops; pub mod enderman; pub mod equine; pub mod farm; -pub mod fox; pub mod finalize; +pub mod fox; pub mod gear; pub mod goals; pub mod golem; From 23019a7bf999938e19c0d7c0de33f7a43f049485 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:48:21 +0100 Subject: [PATCH 085/221] Cats lie beside a sleeping owner and may leave a morning gift --- .../examples/probe/mob_ai_probe.rs | 2 + crates/horizon-client/src/game/creatures.rs | 18 ++ crates/horizon-client/src/game/lan_mobs.rs | 2 + crates/horizon-client/src/mobs.rs | 14 ++ crates/horizon-client/src/mobs/tame.rs | 198 +++++++++++++++++- 5 files changed, 231 insertions(+), 3 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..e7c827541 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1060,6 +1060,8 @@ pub fn main() -> horizon_client::Result<()> { uuid: PLAYER_UUID, allies: Default::default(), remote: false, + sleeping: false, + sleep_timer: 0, } }); 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 845d2aee6..6374485d6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -196,6 +196,8 @@ impl Game<'_> { uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), remote: false, + sleeping: self.sleeping.is_some(), + sleep_timer: self.sleep_timer, }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -1037,6 +1039,22 @@ impl Game<'_> { [0.0, 0.2, 0.0], 10, ), + MobEvent::DropGift { table, at } => { + let stacks = + self.res + .items() + .loot_table(table, false, None, &mut self.world.random); + for stack in stacks { + // ItemEntity's own random motion. + let r = &mut self.world.random; + let v = [ + f64::from(r.next_float()) * 0.2 - 0.1, + 0.2, + f64::from(r.next_float()) * 0.2 - 0.1, + ]; + self.spawn_item(stack, at, v, 10); + } + } MobEvent::SetBlock { pos, state } => { self.world.set(pos[0], pos[1], pos[2], state)? } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..1d3b3d086 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -373,6 +373,8 @@ mod tests { uuid: [0; 4], allies: Default::default(), remote: false, + sleeping: false, + sleep_timer: 0, } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 6b1e16f5c..43da944d3 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -659,6 +659,8 @@ pub struct Extra { /// `Mob.canPickUpLoot` (also lets dispensers equip it). pub pick_up_loot: bool, pub saddled: bool, + /// `Cat.RELAX_STATE_ONE`: watching a sleeping owner before lying down. + pub relax_one: bool, /// The saddle's components (name, enchantments...) when it is not a bare /// one; `saddled` stays the gameplay flag. pub saddle_stack: Option, @@ -999,6 +1001,11 @@ pub enum MobEvent { count: u32, at: [f64; 3], }, + /// `Mob.dropFromGiftLootTable`: a gift loot table's items dropped at `at`. + DropGift { + table: &'static str, + at: [f64; 3], + }, SetBlock { pos: [i32; 3], state: horizon_world::registry::BlockStateId, @@ -1260,6 +1267,8 @@ pub struct Seen { pub stats: [f64; 3], /// `Wolf.isInSittingPose`. pub sitting: bool, + /// `Cat.isLying` or `isRelaxStateOne`. + pub lying: bool, /// `Entity.isVehicle` or `isPassenger`. pub ridden: bool, } @@ -1335,6 +1344,7 @@ impl Mob { m.attrs.speed, ], sitting: m.extra.sitting, + lying: m.species() == Species::Cat && (m.extra.flag || m.extra.relax_one), ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), } } @@ -1488,6 +1498,10 @@ 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, + /// `isSleeping` and `getSleepTimer` (100 once slept through, then the + /// ticks fading out after waking up). + pub sleeping: bool, + pub sleep_timer: u32, } #[derive(Clone)] pub struct MobWorld<'a> { diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1e725df80..7998b4763 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -12,7 +12,7 @@ use super::{ }; use horizon_core::geometry::trig::Mth; use horizon_core::{ - geometry::{Aabb, Vec3}, + geometry::{Aabb, Axis, Vec3}, random::RandomSource, }; use std::f32::consts::PI; @@ -719,6 +719,7 @@ pub fn register_cat(m: &mut Mob) { g.add(1, Float); g.add(1, TamePanic(Panic::new(1.5))); g.add(2, SitWhenOrdered); + g.add(3, CatRelaxOnOwner::default()); g.add(4, CatTempt(super::goals::Tempt::new(0.6, food, true))); g.add( 4, @@ -799,6 +800,192 @@ fn empty_above(w: &MobWorld, p: [i32; 3]) -> bool { .as_ref() == "minecraft:air" } +/// `Cat.CatRelaxOnOwnerGoal`: while the owner sleeps, the cat lies down beside +/// them, and may leave a morning gift when they wake up. +#[derive(Clone, Debug, Default)] +struct CatRelaxOnOwner { + goal: Option<[i32; 3]>, + on_bed_ticks: i32, +} +impl CatRelaxOnOwner { + /// `spaceIsOccupied`: another cat lying or relaxing within two blocks. + fn occupied(&self, m: &Mob, w: &MobWorld) -> bool { + let Some(g) = self.goal else { return true }; + let area = Aabb::new( + Vec3::new( + f64::from(g[0]) - 2.0, + f64::from(g[1]) - 2.0, + f64::from(g[2]) - 2.0, + ), + Vec3::new( + f64::from(g[0]) + 3.0, + f64::from(g[1]) + 3.0, + f64::from(g[2]) + 3.0, + ), + ); + w.others.iter().any(|o| { + o.species == Species::Cat && o.id != m.id && o.lying && o.bounds.intersects(area) + }) + } + /// The owner's sleeping state, when this cat may relax on them. + fn sleeping_owner<'w>(m: &Mob, w: &'w MobWorld) -> Option<&'w super::PlayerView> { + w.player + .as_ref() + .filter(|p| m.extra.tame && !m.extra.sitting && p.sleeping) + } +} +impl Goal for CatRelaxOnOwner { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let w = cx.w; + let Some(p) = Self::sleeping_owner(m, w) else { + return false; + }; + if m.distance_sqr(p.position) > 100.0 { + return false; + } + let at = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + if !has_tag(w, at, "minecraft:cats_can_lie_on") { + return false; + } + // The bed's foot: against `BedBlock.FACING`. + let back = match w.prop(at[0], at[1], at[2], "facing") { + Some("north") => [0, 0, 1], + Some("south") => [0, 0, -1], + Some("east") => [-1, 0, 0], + Some("west") => [1, 0, 0], + Some("up") => [0, -1, 0], + Some("down") => [0, 1, 0], + _ => [0, 0, 0], + }; + self.goal = Some([at[0] + back[0], at[1] + back[1], at[2] + back[2]]); + !self.occupied(m, w) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + Self::sleeping_owner(m, cx.w).is_some() && self.goal.is_some() && !self.occupied(m, cx.w) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(g) = self.goal { + m.extra.flag2 = false; + m.nav_move_to( + cx.w, + [f64::from(g[0]), f64::from(g[1]), f64::from(g[2])], + 1.1, + ); + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.flag = false; + // The `gameplay/cat_waking_up_gift_chance` of the `day` timeline: 0.7 + // from tick 23667 of the day to tick 362 of the next, 0 in between. + let day = cx.w.day_time.rem_euclid(24000); + let chance = if !cx.w.nether && !cx.w.end && !(362..23667).contains(&day) { + 0.7 + } else { + 0.0 + }; + if cx.w.player.as_ref().is_some_and(|p| p.sleep_timer >= 100) + && m.random.next_float() < chance + { + give_morning_gift(m, cx); + } + self.on_bed_ticks = 0; + m.extra.relax_one = false; + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let (Some(p), Some(g)) = (cx.w.player.as_ref(), self.goal) else { + return; + }; + m.extra.flag2 = false; + m.nav_move_to( + cx.w, + [f64::from(g[0]), f64::from(g[1]), f64::from(g[2])], + 1.1, + ); + if m.distance_sqr(p.position) < 2.5 { + self.on_bed_ticks += 1; + if self.on_bed_ticks > reduced(16) { + m.extra.flag = true; + m.extra.relax_one = false; + } else { + m.look_at_speed(p.eye, 45.0, 45.0); + m.extra.relax_one = true; + } + } else { + m.extra.flag = false; + } + } +} +/// `CatRelaxOnOwnerGoal.giveMorningGift`: hop to a spot within five blocks +/// (`randomTeleport`, avoiding `#dangerous_for_teleportation`) and drop a +/// `gameplay/cat_morning_gift` item at its feet. +fn give_morning_gift(m: &mut Mob, cx: &mut Cx) { + let w = cx.w; + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let x = at[0] + m.random.next_int_bound(11).unwrap_or(5) - 5; + let y = at[1] + m.random.next_int_bound(5).unwrap_or(2) - 2; + let z = at[2] + m.random.next_int_bound(11).unwrap_or(5) - 5; + let tagged = |p: [i32; 3], tag| has_tag(w, p, tag); + let mut ground = y - 1; + while ground > crate::chunk::MIN_Y + && !tagged([x, ground, z], "minecraft:entities_can_teleport_to") + { + ground -= 1; + } + if w.world.loaded(x, z) && ground > crate::chunk::MIN_Y { + let feet = f64::from(ground + 1); + let half = f64::from(m.width()) / 2.0; + let b = Aabb::new( + Vec3::new(f64::from(x) - half, feet, f64::from(z) - half), + Vec3::new( + f64::from(x) + half, + feet + f64::from(m.height()), + f64::from(z) + half, + ), + ); + let dangerous = |p| tagged(p, "minecraft:dangerous_for_teleportation"); + let in_box = |f: &dyn Fn([i32; 3]) -> bool| { + (b.min(Axis::X).floor() as i32..=b.max(Axis::X).floor() as i32).any(|bx| { + (b.min(Axis::Y).floor() as i32..=b.max(Axis::Y).floor() as i32).any(|by| { + (b.min(Axis::Z).floor() as i32..=b.max(Axis::Z).floor() as i32) + .any(|bz| f([bx, by, bz])) + }) + }) + }; + let fluids = w.fluids(b, feet); + if !dangerous([x, ground, z]) + && w.no_collision(b) + && !(fluids.in_water || fluids.in_lava) + && !in_box(&dangerous) + { + m.position = Vec3::new(f64::from(x), feet, f64::from(z)); + m.previous = m.position; + m.velocity = Vec3::ZERO; + } + } + let yaw = m.body_yaw * (PI / 180.0); + let here = [ + m.position.x.floor() - f64::from(yaw.msin()), + m.position.y.floor(), + m.position.z.floor() + f64::from(yaw.mcos()), + ]; + cx.events.push(MobEvent::DropGift { + table: "minecraft:gameplay/cat_morning_gift", + at: here, + }); +} /// `CatLieOnBlockGoal`: tame cats lie on beds and other warm blocks. #[derive(Clone, Debug)] struct CatLieOnBlock(super::goals::MoveToBlock); @@ -941,6 +1128,7 @@ impl Goal for OcelotAttack { /// `Cat.tick`: lying and relaxing amounts and the purr. pub fn cat_ai_step(m: &mut Mob, events: &mut Vec) { let lying = m.extra.flag; + let relaxing = m.extra.relax_one; let v = &mut m.anim.v; if lying { v[LIE] = (v[LIE] + 0.15).min(1.0); @@ -949,8 +1137,12 @@ pub fn cat_ai_step(m: &mut Mob, events: &mut Vec) { v[LIE] = (v[LIE] - 0.22).max(0.0); v[LIE_TAIL] = (v[LIE_TAIL] - 0.13).max(0.0); } - v[RELAX] = (v[RELAX] - 0.13).max(0.0); - if lying && m.age.is_multiple_of(5) { + v[RELAX] = if relaxing { + (v[RELAX] + 0.1).min(1.0) + } else { + (v[RELAX] - 0.13).max(0.0) + }; + if (lying || relaxing) && m.age.is_multiple_of(5) { let volume = 0.6 + 0.4 * (m.random.next_float() - m.random.next_float()); events.push(MobEvent::Sound("entity.cat.purr", m.center(), volume, 1.0)); } From 58a99a2ce9b267ccdf210cbdbe26ff551b7fbc3f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:49:41 +0100 Subject: [PATCH 086/221] Sulfur cubes bounce, slide and keep speed by their block's archetype --- crates/horizon-client/src/mobs/living.rs | 67 ++++++++++++-- crates/horizon-client/src/mobs/sulfur_cube.rs | 92 +++++++++++++++++-- 2 files changed, 145 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 394821ace..4f57e4fcf 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -411,19 +411,45 @@ impl Mob { } else if !matches!(self.kind.species, super::Species::Bat | super::Species::Bee) { self.check_fall_damage(w, moved, events); } - // restituteMovementAfterCollisions with no bounciness: the colliding - // components become (signed) zero. + // Entity.restituteMovementAfterCollisions: the colliding components + // bounce back by the entity's bounciness (zero for most mobs, so they + // become signed zero). Block bounciness is not modelled for mobs. if moved_vertically && vertical || self.horizontal_collision { let v = self.velocity; + let restitution = self.entity_bounciness(); + let mut after = v; if x_hit { - self.velocity.x = -v.x * 0.0; + after.x = -v.x * restitution; } if z_hit { - self.velocity.z = -v.z * 0.0; + after.z = -v.z * restitution; } if vertical { - self.velocity.y = (0.0 - v.y) * 1.0 * 0.0; + let mut restitution = restitution; + if self.vertical_collision_below { + // Only a hard enough landing bounces, and never on honey. + let on = ( + self.position.x.floor() as i32, + (self.position.y - f64::from(0.2_f32)).floor() as i32, + self.position.z.floor() as i32, + ); + if -v.y <= self.gravity() + || restitution > 0.0 + && w.block_name(on.0, on.1, on.2) == "minecraft:honey_block" + { + restitution = 0.0; + } + } + let (compensation, drag) = if restitution > 0.0 { + let portion = moved.y / v.y; + let air_drag = f64::from(self.air_drag()); + (portion * self.gravity(), 1.0 + portion * (air_drag - 1.0)) + } else { + (0.0, 1.0) + }; + after.y = (compensation - v.y) * drag * restitution; } + self.velocity = after; } // Entity.checkSupportingBlock self.supporting = self.supporting_block(w, moved); @@ -716,9 +742,33 @@ impl Mob { let y = (self.position.y - 0.500_001).floor() as i32; w.facts.get(w.world.block(x, y, z)).friction } + /// `getAttributeValue(BOUNCINESS)`. + fn entity_bounciness(&self) -> f64 { + super::sulfur_cube::physics(self).map_or(0.0, |a| f64::from(a.bounciness.clamp(0.0, 1.0))) + } + /// `LivingEntity.computeModifiedFriction`. + fn modified_friction(friction: f32, modifier: f32) -> f32 { + (1.0 - (1.0 - friction) * modifier).clamp(0.0, 1.0) + } + /// `LivingEntity.getAirDrag`: what vertical air drag a bounce applies. + fn air_drag(&self) -> f32 { + let base = if self.kind.flags.omnidirectional { + 0.91 + } else { + 0.98 + }; + Self::modified_friction(base, self.air_drag_modifier()) + } + /// `getAttributeValue(AIR_DRAG_MODIFIER)`. + fn air_drag_modifier(&self) -> f32 { + super::sulfur_cube::physics(self).map_or(1.0, |a| a.air_drag_modifier.clamp(0.0, 2048.0)) + } fn travel_in_air(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec) { let friction = if self.on_ground { - self.block_friction(w) + // FRICTION_MODIFIER scales the block's slipperiness. + let modifier = super::sulfur_cube::physics(self) + .map_or(1.0, |a| a.friction_modifier.clamp(0.0, 2048.0)); + Self::modified_friction(self.block_friction(w), modifier) } else { 1.0 }; @@ -752,12 +802,13 @@ impl Mob { self.velocity = Vec3::new(movement.x, y, movement.z); return; } - let drag = 0.91f32; + let air_drag_modifier = self.air_drag_modifier(); + let drag = Self::modified_friction(0.91, air_drag_modifier); let f = friction * drag; let vertical = if self.kind.flags.omnidirectional { drag } else { - 0.98 + Self::modified_friction(0.98, air_drag_modifier) }; self.velocity = Vec3::new( movement.x * f64::from(f), diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index 00b846b86..eecb05d3f 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -32,6 +32,12 @@ pub struct Archetype { pub contact_damage: Option, /// The knockback resistance modifier (the attribute clamps to 0..1). pub knockback_resistance: f64, + /// `Attributes.BOUNCINESS` (the modifier added to a base of 0). + pub bounciness: f32, + /// `Attributes.FRICTION_MODIFIER` and `AIR_DRAG_MODIFIER` (base 1 times + /// the archetype's factor). + pub friction_modifier: f32, + pub air_drag_modifier: f32, pub horizontal_power: f32, pub vertical_power: f32, pub hit_sound: &'static str, @@ -40,13 +46,16 @@ pub struct Archetype { pub push_threshold: f32, } macro_rules! arch { - ($n:literal, $b:expr, $e:expr, $c:expr, $k:expr, $h:expr, $v:expr, $cd:expr, $t:expr) => { + ($n:literal, $b:expr, $e:expr, $c:expr, $k:expr, $phys:expr, $h:expr, $v:expr, $cd:expr, $t:expr) => { Archetype { name: $n, buoyant: $b, explosion: $e, contact_damage: $c, knockback_resistance: $k, + bounciness: $phys.0, + friction_modifier: $phys.1, + air_drag_modifier: $phys.2, horizontal_power: $h, vertical_power: $v, hit_sound: concat!("entity.sulfur_cube.", $n, ".hit"), @@ -58,13 +67,25 @@ macro_rules! arch { } /// `data/minecraft/sulfur_cube_archetype/*.json`. pub const ARCHETYPES: [Archetype; 12] = [ - arch!("bouncy", true, None, None, -2.0, 0.4125, 0.105, 0.7, 0.3), + arch!( + "bouncy", + true, + None, + None, + -2.0, + (0.9, 0.3, 0.01), + 0.4125, + 0.105, + 0.7, + 0.3 + ), arch!( "explosive", true, Some((120, 3.0, false)), None, -1.0, + (0.5, 0.3, 0.3), 0.4125, 0.09, 0.7, @@ -76,6 +97,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, -1.0, + (0.5, 0.2, 0.01), 0.9125, 0.09, 0.9, @@ -87,6 +109,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.5, + (0.1, 0.05, 0.01), 0.6625, 0.09, 1.0, @@ -98,20 +121,55 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.7, + (0.2, 1.0, 0.01), 0.4125, 0.09, 0.7, 0.03 ), - arch!("hot", true, None, Some(1.0), -1.0, 0.4125, 0.09, 0.7, 0.2), - arch!("light", true, None, None, -1.0, 0.4125, 0.18, 0.7, 0.2), - arch!("regular", true, None, None, -1.0, 0.4125, 0.09, 0.5, 0.2), + arch!( + "hot", + true, + None, + Some(1.0), + -1.0, + (0.5, 0.3, 0.1), + 0.4125, + 0.09, + 0.7, + 0.2 + ), + arch!( + "light", + true, + None, + None, + -1.0, + (1.0, 0.3, 1.8), + 0.4125, + 0.18, + 0.7, + 0.2 + ), + arch!( + "regular", + true, + None, + None, + -1.0, + (0.5, 0.3, 0.1), + 0.4125, + 0.09, + 0.5, + 0.2 + ), arch!( "slow_bouncy", false, None, None, 0.4, + (0.6, 0.3, 0.05), 0.4125, 0.24, 0.5, @@ -123,6 +181,7 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.5, + (0.4, 0.4, 0.1), 0.4125, 0.105, 0.9, @@ -134,12 +193,24 @@ pub const ARCHETYPES: [Archetype; 12] = [ None, None, 0.8, + (0.1, 0.05, 0.01), 0.4125, 0.09, 1.0, 0.02 ), - arch!("sticky", false, None, None, -2.0, 0.4125, 0.09, 0.5, 0.05), + arch!( + "sticky", + false, + None, + None, + -2.0, + (0.0, 2.0, 0.01), + 0.4125, + 0.09, + 0.5, + 0.05 + ), ]; /// `SulfurCubeArchetype.DEFAULT_*`: no block swallowed. const DEFAULT_PUSH: (&str, f32, f32) = ("entity.sulfur_cube.regular.push", 0.5, 0.2); @@ -178,6 +249,15 @@ pub fn has_body(m: &Mob) -> bool { pub fn archetype(m: &Mob) -> Option<&'static Archetype> { m.extra.head.as_deref().and_then(archetype_of) } +/// The archetype whose bounciness, friction and air drag attributes a +/// sulfur cube's physics use (no other mob has those modifiers). +pub fn physics(m: &Mob) -> Option<&'static Archetype> { + if m.species() == super::Species::SulfurCube { + archetype(m) + } else { + None + } +} pub fn fuse(m: &Mob) -> i32 { m.extra.counter2 - 1 } From 8a309c393dcff4adf462bebc6a9c3e23c65ee8de Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:50:50 +0100 Subject: [PATCH 087/221] Show join and leave messages in a LAN host's own chat --- crates/horizon-client/src/game/lan.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..19658cdf2 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1026,6 +1026,16 @@ impl Game<'_> { "INFO", &format!("System chat: {} joined the game", g.name), ); + } else if self.player.is_some() + && let Some(g) = host.hub.guest(conn) + && g.placed + { + // The host's chat hears of the newcomer as the guests do. + let who = self.player_text(&g.name, g.uuid); + self.system_message( + Text::translate("multiplayer.player.joined", &[who]) + .with_color(horizon_client::text::YELLOW), + ); } } HostEvent::Left(mut guest) => { @@ -1057,6 +1067,13 @@ impl Game<'_> { "INFO", &format!("System chat: {} left the game", guest.name), ); + } else if self.player.is_some() && guest.placed { + // ServerGamePacketListenerImpl.removePlayerFromWorld. + let who = self.player_text(&guest.name, guest.uuid); + self.system_message( + Text::translate("multiplayer.player.left", &[who]) + .with_color(horizon_client::text::YELLOW), + ); } } HostEvent::Packet(conn, packet) => { From 54b1c4f9415adc0bf42585e1e1d7c5022521cf83 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:51:03 +0100 Subject: [PATCH 088/221] Make climbing follow vanilla: no climbing while flying, open trapdoors over ladders climb --- crates/horizon-client/src/motion.rs | 54 +++++++++++++++++++++-------- 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fcdd32cbd..d96c07ff0 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -13,6 +13,7 @@ use horizon_world::{ attributes::{Modifier, Operation, entity::Catalog, live::LiveAttributes}, block_collision::BlockCollisionRegistry, block_landing::BlockLandingRegistry, + climbing::{self, ClimbingRegistry, ClimbingWorld}, collision_context::{CollisionContext, CollisionEntity, CollisionItem}, edge_backoff::{self, EdgeBackoffInput, EdgeBackoffWorld}, entity_move::{self, CollisionFlags, EntityMoveWorld, MovementHistory, MoverType}, @@ -50,6 +51,8 @@ pub struct MotionResources { pub attributes: Arc, pub blocks: BoundMovementProperties, pub climbable: BTreeSet, + /// `LivingEntity.onClimbable` tags plus open trapdoors above a ladder. + pub climbing: ClimbingRegistry<'static>, pub fall_reset: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, @@ -97,6 +100,12 @@ impl MotionResources { .cloned() .collect()) }; + let climbing = ClimbingRegistry::new( + assets.registry, + &tag("minecraft:trapdoors")?, + &tag("minecraft:climbable")?, + &tag("minecraft:can_glide_through")?, + )?; Ok(Self { landing: crate::landing::load(root, &properties)?, health: crate::health::HealthResources::load(root)?, @@ -108,6 +117,7 @@ impl MotionResources { suppresses_bounce: tag("minecraft:suppresses_bounce")?, })?, climbable: tag("minecraft:climbable")?, + climbing, fall_reset: tag("minecraft:fall_damage_resetting")?, }) } @@ -753,23 +763,15 @@ impl MotionWorld<'_, '_, '_> { supporting_block: self.player.ground.supporting_block, } } - /// `LivingEntity.onClimbable` at the player's feet (it remembers the block). + /// `Player.onClimbable` (never while flying) over `LivingEntity.onClimbable` + /// at the player's feet: the climbable tag or an open trapdoor above a + /// matching ladder. It remembers the block. pub fn climbable(&mut self) -> Result { - if self.player.spectator { + if self.player.flying { return Ok(false); } - let p = BlockPos::containing(self.player.position); - let name = &self - .assets - .registry - .state(self.block(p)) - .ok_or("missing scene state")? - .name; - let climbable = self.resources.climbable.contains(name); - if climbable { - self.player.last_climbable = Some(p); - } - Ok(climbable) + let resources = self.resources; + climbing::on_climbable(self, &resources.climbing).map_err(|e| e.to_string().into()) } pub fn travel_in_air(&mut self, input: Vec3) -> Result<()> { living_air::travel_in_air(self, input) @@ -1611,6 +1613,30 @@ impl MotionWorld<'_, '_, '_> { Ok(()) } } +impl ClimbingWorld for MotionWorld<'_, '_, '_> { + type Error = std::convert::Infallible; + fn is_spectator(&mut self) -> std::result::Result { + Ok(self.player.spectator) + } + fn block_position(&mut self) -> std::result::Result { + Ok(BlockPos::containing(self.player.position)) + } + fn in_block_state(&mut self) -> std::result::Result { + Ok(self.block(BlockPos::containing(self.player.position))) + } + fn is_fall_flying(&mut self) -> std::result::Result { + Ok(self.player.fall_flying) + } + fn block_state( + &mut self, + position: BlockPos, + ) -> std::result::Result { + Ok(self.block(position)) + } + fn set_last_climbable_position(&mut self, position: BlockPos) { + self.player.last_climbable = Some(position); + } +} impl crate::auto_jump::AutoJumpWorld for MotionWorld<'_, '_, '_> { type Error = Box; fn collision_shape(&mut self, p: BlockPos) -> Result { From 4575f4f1dffa435d615f02b1da7d33b725f7f552 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:51:18 +0100 Subject: [PATCH 089/221] Honour spawn-protection on a dedicated server Players who are not operators can no longer start digging or use an item on a block within the radius of the world spawn. They get the spawn protection message and the client gets the block back, like DedicatedServer.isUnderSpawnProtection. --- crates/horizon-client/src/game/dedicated.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 77 +++++++++++++++---- crates/horizon-client/src/lan/hub.rs | 4 + 3 files changed, 71 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..07b07a27b 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -644,6 +644,9 @@ impl Game<'_> { return Ok(()); } self.sync_ops(&lists); + if let Some(host) = self.lan.as_mut() { + host.hub.spawn_protection = props.spawn_protection; + } log( "INFO", &format!( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 43bb573dc..0430b9013 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -926,6 +926,45 @@ impl Game<'_> { d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < range * range } + /// DedicatedServer.isUnderSpawnProtection: no operators, an operator or a + /// radius of 0 or less is never under it; else a block within the radius + /// of the world spawn (square, in the Overworld) is. + fn under_spawn_protection(&self, host: &LanHost, gi: usize, pos: [i32; 3]) -> bool { + let g = &host.hub.guests[gi]; + let radius = host.hub.spawn_protection; + if self.options.dedicated.is_none() || radius <= 0 || g.dimension != "minecraft:overworld" { + return false; + } + let Some(spawn) = self.level.world_spawn else { + return false; + }; + if host.hub.ops.is_empty() || host.hub.ops.contains_key(&g.uuid) { + return false; + } + let dx = pos[0].abs_diff(spawn[0]); + let dz = pos[2].abs_diff(spawn[2]); + dx.max(dz) <= radius as u32 + } + + /// ServerPlayer.sendSpawnProtectionMessage. + fn spawn_protection_message(&self, host: &LanHost, conn: u32, pos: [i32; 3]) { + let message = horizon_client::text::Text::translate( + "build.spawn_protection", + &[horizon_client::text::Text::literal(format!( + "{}, {}, {}", + pos[0], pos[1], pos[2] + ))], + ) + .with_color(horizon_client::text::RED); + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&message.component()), + overlay: true, + }), + ); + } + /// A packet from a guest that the hub does not handle itself. pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { @@ -950,6 +989,12 @@ impl Game<'_> { if spectator { return; } + // ServerPlayerGameMode.handleBlockBreakAction: no dig starts + // under spawn protection (the ack puts the block back). + if self.under_spawn_protection(host, gi, a.pos) { + self.spawn_protection_message(host, conn, a.pos); + return; + } let face = direction(i32::from(a.direction)); let play = host.play.entry(conn).or_default(); play.digging = Some((a.pos, face)); @@ -1063,19 +1108,25 @@ impl Game<'_> { ], }; let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; - let logged = self.world.block_log.as_ref().map_or(0, Vec::len); - let heard = self.audio.capture.as_ref().map_or(0, Vec::len); - let swung = self.as_guest(host, conn, |g| { - g.forced_hit = Some(hit); - g.guest_use = Some(GuestUse::OnBlock(hand)); - let swings = g.swings_started; - let _ = g.use_item(); - g.forced_hit = None; - g.guest_use = None; - g.swings_started != swings - }); - self.lan_swing_back(host, conn, swung); - self.guest_use_sounds(host, conn, logged, heard); + // handleUseItemOn: under spawn protection nothing is used or + // placed; the player is told and the blocks below go back. + if self.under_spawn_protection(host, gi, p.pos) { + self.spawn_protection_message(host, conn, p.pos); + } else { + let logged = self.world.block_log.as_ref().map_or(0, Vec::len); + let heard = self.audio.capture.as_ref().map_or(0, Vec::len); + let swung = self.as_guest(host, conn, |g| { + g.forced_hit = Some(hit); + g.guest_use = Some(GuestUse::OnBlock(hand)); + let swings = g.swings_started; + let _ = g.use_item(); + g.forced_hit = None; + g.guest_use = None; + g.swings_started != swings + }); + self.lan_swing_back(host, conn, swung); + self.guest_use_sounds(host, conn, logged, heard); + } // The client predicted a result: correct it with what really is. for pos in [ p.pos, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index b1a8cbc62..f2a8edfff 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -168,6 +168,9 @@ pub struct Hub { level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, + /// `spawn-protection` (dedicated servers): the radius around the world + /// spawn that only operators may change. + pub spawn_protection: i32, chat_type: i32, dimension_type: i32, clock_ids: Vec, @@ -332,6 +335,7 @@ impl Hub { ticking: (20.0, false), stepping: 0, ops: Default::default(), + spawn_protection: 0, weather: (false, 0.0, 0.0), level_sync: Default::default(), chat_type, From de808e36129670562bdc55ecc0fe56108b4dedce Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:51:31 +0100 Subject: [PATCH 090/221] Empty a bundle by holding right click --- crates/horizon-client/src/bundle.rs | 4 +- crates/horizon-client/src/game.rs | 59 ++++++++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 11 +++++ 3 files changed, 73 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 42473729f..6842d2584 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -49,10 +49,12 @@ impl Weight { /// The sounds of `BundleItem` (`Entity.playSound` at the player): insert /// and remove one at volume 0.8 and pitch `0.8 + random * 0.4`, a failed -/// insert at 1, 1. +/// insert at 1, 1; the drop of its contents is played at the player's block +/// like remove one. pub const INSERT: &str = "minecraft:item.bundle.insert"; pub const INSERT_FAIL: &str = "minecraft:item.bundle.insert_fail"; pub const REMOVE_ONE: &str = "minecraft:item.bundle.remove_one"; +pub const DROP_CONTENTS: &str = "minecraft:item.bundle.drop_contents"; fn max_stack(items: &Items, stack: &ItemStack) -> u32 { items.get(&stack.item).map_or(64, |i| i.max_stack).max(1) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cca1f1ee6..5e3b6864c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3741,6 +3741,14 @@ impl Game<'_> { self.use_spyglass(); return Ok(true); } + // BundleItem.use: startUsingItem, then onUseTick empties it. + if !on_block && info.bundle { + if self.using.is_none() { + self.using = Some((self.held_slot(), 0)); + } + self.swing_arm(); + return Ok(true); + } if !on_block && &*stack.item == "minecraft:bow" { if self.using.is_none() && (self.creative || self.projectile_slot("minecraft:bow").is_some()) @@ -4010,6 +4018,10 @@ impl Game<'_> { } return; } + if info.bundle { + self.tick_bundle(slot, ticks); + return; + } let Some(consumable) = info.consumable.as_ref() else { self.using = None; return; @@ -4031,6 +4043,53 @@ impl Game<'_> { self.using = Some((slot, ticks)); } } + /// `BundleItem.onUseTick` and `getUseDuration` (200): the first tick and + /// then every second tick from the 11th on drop one stack out of the + /// bundle in `slot`; the use ends after 200 ticks. + fn tick_bundle(&mut self, slot: usize, ticks: u32) { + const USE_DURATION: u32 = 200; + let remaining = USE_DURATION - ticks.min(USE_DURATION); + if ticks == 0 || (remaining < USE_DURATION - 10 && remaining.is_multiple_of(2)) { + self.drop_bundle_content(slot); + } + self.using = (ticks + 1 < USE_DURATION).then_some((slot, ticks + 1)); + } + /// `BundleItem.dropContent`: `removeOneItemFromBundle` and `Player.drop`, + /// then the drop sound and the used statistic. + fn drop_bundle_content(&mut self, slot: usize) { + let items = self.res.items(); + let Some(mut bundle) = self.stack_in(slot).cloned() else { + return; + }; + let Some(mut contents) = horizon_client::bundle::Contents::of(items, &bundle) else { + return; + }; + let Some(removed) = contents.remove_one(items) else { + return; + }; + contents.store(&mut bundle); + let item = Arc::clone(&bundle.item); + *self.stack_in_mut(slot) = Some(bundle); + let Some(position) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let at = [position.x, position.y, position.z]; + // playRemoveOneSound, then Player.drop and playDropContentsSound at + // the player's block. + let pitch = 0.8 + self.world.random.next_float() * 0.4; + self.audio + .play(horizon_client::bundle::REMOVE_ONE, Some(at), 0.8, pitch); + self.player_drop(removed); + let block = BlockPos::containing(position); + let pitch = 0.8 + self.world.random.next_float() * 0.4; + self.audio.play( + horizon_client::bundle::DROP_CONTENTS, + Some([block.x, block.y, block.z].map(|v| f64::from(v) + 0.5)), + 0.8, + pitch, + ); + self.stats.add("used", &item, 1); + } /// `LivingEntity.releaseUsingItem` (`Item.releaseUsing`) for `stack`, /// used for `ticks`, its hand acting: a bow or a trident lets go (not /// when its hand changed), a spyglass stops scoping. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..54c4aa5df 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4318,7 +4318,10 @@ impl Game<'_> { if self.using.is_some() { return; } + let bundle = self.res.items().get(&held.item).is_some_and(|i| i.bundle); let start = match &*held.item { + // BundleItem.use: always starts; the server drops the contents. + _ if bundle => true, // BowItem.use: with an arrow, or in creative. "minecraft:bow" => self.creative || self.projectile_slot("minecraft:bow").is_some(), // CrossbowItem.use: charging when not charged and with ammunition; @@ -4383,6 +4386,14 @@ impl Game<'_> { // Another hotbar slot picked: LivingEntity.updatingUsingItem sees a // different stack in the hand. The off hand keeps its item. let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT; + // BundleItem.getUseDuration: 200 ticks, the server drops the contents. + if stack + .as_ref() + .is_some_and(|s| self.res.items().get(&s.item).is_some_and(|i| i.bundle)) + { + self.using = (in_hand && ticks + 1 < 200).then_some((slot, ticks + 1)); + return; + } // A drawn bow, a charging crossbow, a raised shield...: held until // the button lets go. if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { From 89c195fa6e6691a8ea301d736270b9cdc97f1371 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:51:46 +0100 Subject: [PATCH 091/221] Don't back off from edges while flying --- crates/horizon-client/src/motion.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index fcdd32cbd..24fe185d8 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1742,7 +1742,8 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { let input = EdgeBackoffInput { movement, bounds: self.player.bounds(), - flying: false, + // Player.maybeBackOffFromEdge: not while flying. + flying: self.player.flying, self_or_player: matches!(mover, MoverType::SelfMovement | MoverType::Player), fall_distance: self.player.fall_distance, query_budget: 1_000_000, From 9ae3882c1af4c74352e69d7a0ea6352b802ebe1f Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:52:46 +0100 Subject: [PATCH 092/221] Kick unlisted players when enforce-whitelist is on Whitelist remove, reload and on, and deop, now disconnect online players who are not on the whitelist, like MinecraftServer.kickUnlistedPlayers. --- crates/horizon-client/src/game/dedicated.rs | 47 +++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..9b9f4a4ed 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -950,6 +950,10 @@ impl Game<'_> { self.console_reply(Text::translate(key, &[lit(&user.name)])); let lists = state.lists.clone(); self.sync_ops(&lists); + // DeOpCommands.deopPlayers. + if command == "deop" && changed { + self.kick_unlisted_players(&lists); + } } "whitelist" => self.console_whitelist(state, &rest), "ban" if !rest.is_empty() => { @@ -1161,6 +1165,7 @@ impl Game<'_> { ["on"] | ["off"] => { let on = rest[0] == "on"; let mut l = state.lists.lock().unwrap(); + let turned_on = on && !l.use_whitelist; let key = match (on, l.use_whitelist) { (true, true) => "commands.whitelist.alreadyOn", (true, false) => "commands.whitelist.enabled", @@ -1171,6 +1176,10 @@ impl Game<'_> { drop(l); self.store_property("white-list", on.to_string()); self.console_reply(Text::translate(key, &[])); + if turned_on { + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); + } } ["list"] => { let names: Vec = state @@ -1194,6 +1203,8 @@ impl Game<'_> { ["reload"] => { let _ = state.lists.lock().unwrap().white.load(); self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); } ["add", name] | ["remove", name] => { let Some(user) = self.resolve(name) else { @@ -1219,6 +1230,10 @@ impl Game<'_> { Vec::new() }; self.console_reply(Text::translate(key, &args)); + if ok && rest[0] == "remove" { + let lists = state.lists.clone(); + self.kick_unlisted_players(&lists); + } } _ => self.console_reply(Text::translate("command.unknown.argument", &[])), } @@ -1234,6 +1249,38 @@ impl Game<'_> { } } + /// MinecraftServer.kickUnlistedPlayers: with `enforce-whitelist` and the + /// whitelist on, whoever is online and not on the whitelist file is + /// disconnected (operators are not spared here). + fn kick_unlisted_players(&mut self, lists: &Arc>) { + let unlisted: Vec = { + let l = lists.lock().unwrap(); + let Some(host) = self.lan.as_ref() else { + return; + }; + if !(l.enforce_whitelist && l.use_whitelist) { + return; + } + host.hub + .guests + .iter() + .filter(|g| { + !l.white.contains(&NameAndId { + id: g.uuid, + name: g.name.clone(), + }) + }) + .map(|g| g.uuid) + .collect() + }; + for uuid in unlisted { + self.kick_uuid( + uuid, + translatable("multiplayer.disconnect.not_whitelisted", &[]), + ); + } + } + fn kick_uuid(&mut self, uuid: u128, reason: Tag) { if let Some(h) = self.lan.as_mut() { let conns: Vec = h From 2d72e987c59db0d610cc30a3ae69b61790d3d1be Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:53:15 +0100 Subject: [PATCH 093/221] Play ambient sounds and spawn fireflies around firefly bushes, eyeblossoms, pale moss and dry plants --- .../examples/probe/marker_particles_probe.rs | 3 + crates/horizon-client/src/animate_tick.rs | 146 +++++++++++++++++- crates/horizon-client/src/game/render_tick.rs | 22 ++- 3 files changed, 169 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/examples/probe/marker_particles_probe.rs b/crates/horizon-client/examples/probe/marker_particles_probe.rs index 72ebaff22..aec1ccff6 100644 --- a/crates/horizon-client/examples/probe/marker_particles_probe.rs +++ b/crates/horizon-client/examples/probe/marker_particles_probe.rs @@ -74,6 +74,9 @@ pub fn main() -> Result<()> { biomes: &biomes, registry: assets.registry, raining_at: &|_| false, + height_no_leaves: &|_| 0, + firefly_bush_sounds: false, + sky_darken: 0, marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)), }; engine.seed_randoms(1057, 0, 0); diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 28b28544b..7d3d2ca6c 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -70,6 +70,14 @@ enum Animate { waterlogged: bool, }, EndPortal, + FireflyBush, + /// An open eyeblossom (`Type.OPEN.emitSounds()`). + OpenEyeblossom, + PaleHangingMoss, + /// `DryVegetationBlock`: a dead bush. + DeadBush, + /// `ShortDryGrassBlock` and `TallDryGrassBlock`. + DryGrass, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -149,6 +157,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { waterlogged: prop("waterlogged").as_deref() == Some("true"), }, "end_portal" => Animate::EndPortal, + "firefly_bush" => Animate::FireflyBush, + "open_eyeblossom" => Animate::OpenEyeblossom, + "pale_hanging_moss" => Animate::PaleHangingMoss, + "dead_bush" => Animate::DeadBush, + "short_dry_grass" | "tall_dry_grass" => Animate::DryGrass, "sculk_sensor" | "calibrated_sculk_sensor" if prop("sculk_sensor_phase").as_deref() == Some("active") => { @@ -194,6 +207,10 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, + /// `#triggers_ambient_desert_dry_vegetation_block_sounds`. + desert_dry_vegetation_sounds: Vec, + terracotta: Vec, + pale_oak_logs: Vec, /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged). burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). @@ -269,6 +286,11 @@ impl AnimateTables { power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), + desert_dry_vegetation_sounds: by_state( + "minecraft:triggers_ambient_desert_dry_vegetation_block_sounds", + ), + terracotta: by_state("minecraft:terracotta"), + pale_oak_logs: by_state("minecraft:pale_oak_logs"), burnable, ambient, }) @@ -294,6 +316,12 @@ pub struct AnimateContext<'a> { pub registry: &'a BlockRegistry, /// `Level.isRainingAt`. pub raining_at: &'a dyn Fn([i32; 3]) -> bool, + /// `getHeight(MOTION_BLOCKING_NO_LEAVES, x, z)` at a position's column. + pub height_no_leaves: &'a dyn Fn([i32; 3]) -> i32, + /// `EnvironmentAttributes.FIREFLY_BUSH_SOUNDS` (overworld day timeline). + pub firefly_bush_sounds: bool, + /// `Level.getSkyDarken`, for `getMaxLocalRawBrightness`. + pub sky_darken: i32, /// Creative main-hand marker block and a resolver for each placed state's sprite. pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option)>, } @@ -344,6 +372,12 @@ impl AnimateContext<'_> { ], )) } + /// `Level.getMaxLocalRawBrightness`: the brighter of block light and + /// sky light less the sky darkening. + fn max_local_raw_brightness(&self, p: [i32; 3]) -> i32 { + let light = self.world.light(p[0], p[1], p[2]); + i32::from(light & 15).max(i32::from(light >> 4) - self.sky_darken) + } fn foliage(&self, p: [i32; 3]) -> u32 { let biome = self .world @@ -395,7 +429,7 @@ fn do_animate_tick( return; } let state = ctx.state(pos); - block_animate_tick(tables, engine, ctx, state, pos); + block_animate_tick(tables, engine, ctx, state, pos, center); let facts = ctx.facts.get(state); if facts.fluid != Fluid::None { fluid_animate_tick( @@ -504,6 +538,22 @@ fn try_spawn_drip( } } } +/// `AmbientDesertBlockSoundsPlayer.shouldPlayDesertDryVegetationBlockSounds`: +/// sand or terracotta two blocks deep. +fn desert_dry_vegetation_sounds( + tables: &AnimateTables, + ctx: &AnimateContext, + below: [i32; 3], +) -> bool { + let triggers = |p: [i32; 3]| { + tables + .desert_dry_vegetation_sounds + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(false) + }; + triggers(below) && triggers([below[0], below[1] - 1, below[2]]) +} /// `WaterFluid.animateTick` / `LavaFluid.animateTick`. fn fluid_animate_tick( engine: &mut ParticleEngine, @@ -579,6 +629,7 @@ fn block_animate_tick( ctx: &AnimateContext, state: BlockStateId, pos: [i32; 3], + player: [i32; 3], ) { let (fx, fy, fz) = (f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])); match tables.kind(state) { @@ -935,6 +986,99 @@ fn block_animate_tick( } } } + Animate::FireflyBush => { + // FireflyBushBlock.animateTick: the idle sound on a quiet night + // under open sky, and fireflies in the dark within 5 blocks. + if next_int(engine.random(), 30) == 0 + && ctx.firefly_bush_sounds + && (ctx.height_no_leaves)(pos) <= pos[1] + { + let name = "minecraft:block.firefly_bush.idle"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + if ctx.max_local_raw_brightness(pos) <= 13 { + let r = engine.random(); + if r.next_double() <= 0.7 { + let p = [ + fx + r.next_double() * 10.0 - 5.0, + fy + r.next_double() * 5.0, + fz + r.next_double() * 10.0 - 5.0, + ]; + add(engine, T::Firefly, p, [0.0; 3]); + } + } + } + Animate::OpenEyeblossom => { + // EyeblossomBlock.animateTick: pale moss below. + if next_int(engine.random(), 700) == 0 { + let below = ctx.state([pos[0], pos[1] - 1, pos[2]]); + if ctx + .registry + .state(below) + .is_some_and(|s| s.name == "minecraft:pale_moss_block") + { + let name = "minecraft:block.eyeblossom.idle"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } + Animate::PaleHangingMoss => { + // HangingMossBlock.animateTick: under pale oak logs or leaves. + if next_int(engine.random(), 500) == 0 { + let above = ctx.state([pos[0], pos[1] + 1, pos[2]]); + let pale_leaves = ctx + .registry + .state(above) + .is_some_and(|s| s.name == "minecraft:pale_oak_leaves"); + if pale_leaves + || tables + .pale_oak_logs + .get(above.0 as usize) + .copied() + .unwrap_or(false) + { + let name = "minecraft:block.pale_hanging_moss.idle"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } + Animate::DeadBush => { + // AmbientDesertBlockSoundsPlayer.playAmbientDeadBushSounds. + if next_int(engine.random(), 130) == 0 { + let below = [pos[0], pos[1] - 1, pos[2]]; + let state = ctx.state(below); + let red_sand = ctx + .registry + .state(state) + .is_some_and(|s| s.name == "minecraft:red_sand"); + let terracotta = tables + .terracotta + .get(state.0 as usize) + .copied() + .unwrap_or(false); + if (red_sand || terracotta) && next_int(engine.random(), 3) != 0 { + return; + } + if desert_dry_vegetation_sounds(tables, ctx, below) { + let name = "minecraft:block.deadbush.idle"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } + Animate::DryGrass => { + // AmbientDesertBlockSoundsPlayer.playAmbientDryGrassSounds: + // played at the player. + if next_int(engine.random(), 200) == 0 + && desert_dry_vegetation_sounds(tables, ctx, [pos[0], pos[1] - 1, pos[2]]) + { + let at = [ + f64::from(player[0]) + 0.5, + f64::from(player[1]), + f64::from(player[2]) + 0.5, + ]; + sound(engine, "minecraft:block.dry_grass.ambient", at, 1.0, 1.0); + } + } Animate::EndPortal => { // EndPortalBlock.animateTick: one smoke particle above the surface. let r = engine.random(); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index e013c8d29..d106e32ad 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -18,10 +18,22 @@ use horizon_core::random::{LegacyRandom, RandomSource}; /// The first motion-blocking block at or below `from` (Heightmap MOTION_BLOCKING), plus one. fn motion_blocking(world: &World, facts: &BlockFacts, x: i32, z: i32, from: i32) -> i32 { + motion_blocking_leaves(world, facts, x, z, from, true) +} +/// `motion_blocking` where leaves count only for MOTION_BLOCKING, not for +/// MOTION_BLOCKING_NO_LEAVES. +fn motion_blocking_leaves( + world: &World, + facts: &BlockFacts, + x: i32, + z: i32, + from: i32, + leaves: bool, +) -> i32 { let mut y = from.min(MIN_Y + HEIGHT - 1); while y > MIN_Y { let f = facts.get(world.block(x, y, z)); - if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") { + if f.full_collision || f.fluid != Fluid::None || leaves && f.name.contains("leaves") { return y + 1; } y -= 1; @@ -271,6 +283,11 @@ impl Game<'_> { && motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1] && rains_at(world, biomes, p[0], p[1], p[2]) }; + let height_no_leaves = + |p: [i32; 3]| motion_blocking_leaves(world, facts, p[0], p[2], i32::MAX, false); + // The day timeline: firefly bush sounds from 12600 to 23400. + let firefly_bush_sounds = self.dim == Dim::Overworld + && (12600..23401).contains(&self.world.day_time.rem_euclid(24000)); let ctx = AnimateContext { world, facts, @@ -278,6 +295,9 @@ impl Game<'_> { biomes, registry: self.pack.assets.registry, raining_at: &raining_at, + height_no_leaves: &height_no_leaves, + firefly_bush_sounds, + sky_darken: self.sky_darken(), marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)), }; if let Some(e) = eye { From d17df3ca055ab9dfaa207f818e0ed913fb6a8db0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:53:41 +0100 Subject: [PATCH 094/221] Give /op the level from op-permission-level The console's /op always granted level 4. It now grants the permission level set in server.properties, like PlayerList.op. --- crates/horizon-client/src/game/dedicated.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..29ab2bac2 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -409,6 +409,8 @@ struct ServerState { paused: bool, /// `broadcast-console-to-ops`. broadcast_console: bool, + /// `op-permission-level`: what `/op` grants (operatorUserPermissions). + op_level: i32, } /// The dedicated-only commands' replies vanilla sends with `broadcast` @@ -663,6 +665,7 @@ impl Game<'_> { ticks: Default::default(), paused: false, broadcast_console: props.broadcast_console_to_ops, + op_level: props.op_permission_level, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -924,7 +927,7 @@ impl Game<'_> { let Some(user) = self.resolve(rest[0]) else { return; }; - let level = 4; + let level = state.op_level; let changed = { let mut l = state.lists.lock().unwrap(); if command == "op" { From b5adad15eb0bc5efbc225454108ac30de3f7fa84 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:53:42 +0100 Subject: [PATCH 095/221] Stop the riptide ground lift at ceilings --- crates/horizon-client/src/game/trident.rs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index d934e85aa..421bfa13e 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -253,8 +253,24 @@ impl Game<'_> { // Player.startAutoSpinAttack(20, 8, stack). p.auto_spin_attack_ticks = 20; p.auto_spin_attack_dmg = 8.0; - if p.ground.on_ground { - p.position.y += 1.2; + } + // `player.move(SELF, (0, 1.1999999, 0))` when on the ground: the lift + // stops at a ceiling. + let lift = self + .player + .as_ref() + .filter(|p| p.ground.on_ground) + .map(|p| p.bounds()); + if let Some(bounds) = lift { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + let up = Vec3::new(0.0, f64::from(1.1999999f32), 0.0); + let moved = scene.resolve(bounds, up, 0.0, true).unwrap_or(Vec3::ZERO); + if let Some(p) = self.player.as_mut() { + p.position.y += moved.y; } } let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3)); From aed4e26f599f1c98230bdcba283a5b0640cac3bb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:54:23 +0100 Subject: [PATCH 096/221] Apply the legacy announce-player-achievements key The key was parsed and dropped. It now sets the show_advancement_messages game rule when the dedicated server starts, like DedicatedServer.initServer. --- crates/horizon-client/src/game/dedicated.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index fa5365195..4caa827eb 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -570,6 +570,14 @@ impl Game<'_> { // DedicatedServer.initServer: worldData.setGameType; forceDifficulty. self.set_default_game_mode(game_mode); self.ui.difficulty = props.difficulty as u8; + // DedicatedServer.initServer: a legacy `announce-player-achievements` + // sets the show_advancement_messages rule once, as the file is read. + if let Some(announce) = props.announce_player_achievements { + self.ui.rules.set( + "show_advancement_messages", + horizon_client::gamerules::Value::Bool(announce), + ); + } self.settings.render_distance = props.view_distance.clamp(2, 32); self.settings.simulation_distance = props.simulation_distance.clamp(2, 32); self.streaming.radius = self.settings.render_distance; From fbdd04d8172a884dd281cdf8897a12744eff2976 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 19:58:03 +0100 Subject: [PATCH 097/221] Use armor stand, boat, cart and item eye heights for facing entity eyes --- crates/horizon-client/src/entities.rs | 11 +++++++++++ crates/horizon-client/src/game/commands/execute.rs | 12 ++++++++++++ 2 files changed, 23 insertions(+) diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 69e053411..3a23a6c32 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -713,6 +713,17 @@ pub struct ArmorStand { } impl ArmorStand { pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"]; + /// The eye height of `getDimensionsMarker`: none for a marker, halved + /// (with `BABY_DIMENSIONS`' 0.9875) when small. + pub fn eye_height(&self) -> f64 { + if self.marker { + 0.0 + } else if self.small { + f64::from(0.9875f32) + } else { + f64::from(1.7775f32) + } + } pub fn new(id: u32, position: Vec3, yaw: f32) -> Self { Self { fire_ticks: 0, diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 3f7e4c2a0..cda51eabb 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -145,6 +145,18 @@ impl Game<'_> { .iter() .find(|m| m.id == id) .map_or(0.0, |m| m.eye_y() - m.position.y), + Target::Stand(id) => self + .armor_stands + .iter() + .find(|a| a.id == id) + .map_or(0.0, |a| a.eye_height()), + // EntityType eyeHeight: boats 0.5625, items 0.2125; the rest keep + // the default of 0.85 of the height (minecarts 0.7, experience + // orbs and paintings 0.5), item frames 0. + Target::Boat(_) => f64::from(0.5625f32), + Target::Item(_) => f64::from(0.2125f32), + Target::Cart(_) => f64::from(0.7f32 * 0.85), + Target::Orb(_) | Target::Painting(_) => f64::from(0.5f32 * 0.85), _ => 0.0, } } From e872d3ae54795ab03e9eade7c4230a3783e88d6c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 20:26:12 +0100 Subject: [PATCH 098/221] Send isFlat in every dimension and use the dimension's min y for the horizon --- crates/horizon-client/src/game.rs | 9 ++++----- crates/horizon-client/src/game/lan.rs | 2 +- crates/horizon-client/src/game/remote.rs | 2 +- crates/horizon-client/src/game/render_tick.rs | 16 +++++++++++----- crates/horizon-client/src/lan/hub.rs | 10 +++++----- 5 files changed, 22 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 23b66e649..9f21fbd34 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1389,8 +1389,8 @@ struct Game<'a> { sleep_timer: u32, dim: Dim, world_root: PathBuf, - /// The world's overworld is superflat (`ClientLevelData.isFlat`). - overworld_flat: bool, + /// The world is superflat (`ServerLevel.isFlat`, for every dimension). + world_flat: bool, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, /// A server's players on their way to another level, each waiting for @@ -7938,8 +7938,7 @@ impl Game<'_> { book.to_be_displayed.retain(|r| index.contains(r)); self.dim = dim; self.world_root = save_root.clone(); - self.overworld_flat = - horizon_client::save::WorldGen::read(&save_root).is_some_and(|w| w.flat); + self.world_flat = horizon_client::save::WorldGen::read(&save_root).is_some_and(|w| w.flat); self.block_ticks = Ticks::new(self.level.seed as i32); self.tick_chunks.clear(); self.clear_entities(); @@ -12276,7 +12275,7 @@ impl<'a> Game<'a> { sleep_timer: 0, dim: Dim::Overworld, world_root: PathBuf::new(), - overworld_flat: false, + world_flat: false, travelling: None, server_trips: Vec::new(), level_teleports: Vec::new(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 30ba4bcb0..840081156 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -583,7 +583,7 @@ impl Game<'_> { self.next_entity += 1; let host_entity = self.next_entity as i32; let mut hub = Hub::new(lan, sync, encoder, config); - hub.flat_overworld = self.overworld_flat; + hub.flat_world = self.world_flat; let port = hub.lan.port; self.world.block_log = Some(Vec::new()); self.world.light_log = Some(Default::default()); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index b83bd6d66..04c47a9dc 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -115,7 +115,7 @@ pub(super) struct Remote { joined: bool, status: String, pub(super) entity_id: i32, - dimension: DimensionType, + pub(super) dimension: DimensionType, /// What chunk packets decode with (the dimension's height and sky, the /// biome registry); replaced whenever one of them changes. pub(super) chunk_format: Arc, diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 36840dabd..74e2c12d9 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -91,8 +91,7 @@ impl Game<'_> { distant_terrain: self.lod.is_some(), cloud_range_chunks: self.settings.cloud_range, camera_y: camera.y, - // level.getMinY(): the Nether and the End start at y 0. - min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, + min_y: self.level_min_y(), flat: self.level_flat(), forward: forward.map(|c| c as f32), rain, @@ -107,11 +106,18 @@ impl Game<'_> { }, ) } - /// `ClientLevelData.isFlat`: on the server thread, as its spawn info said. + /// `ClientLevelData.isFlat`: on the server thread, the world-wide flag. fn level_flat(&self) -> bool { match self.remote.as_ref() { Some(r) => r.flat, - None => self.dim == Dim::Overworld && self.overworld_flat, + None => self.world_flat, + } + } + /// `Level.getMinY`: the current dimension type's minimum y. + fn level_min_y(&self) -> i32 { + match self.remote.as_ref() { + Some(r) => r.dimension.min_y, + None => self.dim.min_y(), } } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon and not under @@ -119,7 +125,7 @@ impl Game<'_> { /// otherwise y 63. pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool { let horizon = if self.level_flat() { - f64::from(MIN_Y) + f64::from(self.level_min_y()) } else { 63.0 }; diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 96e043492..2e07586b9 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -147,9 +147,9 @@ pub struct Hub { /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), /// whose moves are never checked. pub singleplayer_owner: Option, - /// The overworld is superflat (`ServerLevel.isFlat`, sent as - /// `CommonPlayerSpawnInfo.isFlat`). - pub flat_overworld: bool, + /// The world is superflat (`ServerLevel.isFlat`, a world-wide flag, sent as + /// `CommonPlayerSpawnInfo.isFlat` in every dimension). + pub flat_world: bool, /// Who rides what, set by the game before each tick. pub riding: super::entity::Riding, /// The scoreboard's teams, set by the game each tick, for players' @@ -324,7 +324,7 @@ impl Hub { ticks: 0, movement_checks: (true, true), singleplayer_owner: None, - flat_overworld: false, + flat_world: false, riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, @@ -552,7 +552,7 @@ impl Hub { game_type: game_mode, previous_game_type: None, debug: false, - flat: self.flat_overworld && self.config.dimension == "minecraft:overworld", + flat: self.flat_world, last_death: None, portal_cooldown: 0, sea_level: 63, From d97b58fd4a836bd2ba0d5cc4a842c4ef431b3f8a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:15:49 +0100 Subject: [PATCH 099/221] Send the thrower's entity id with a tracked trident --- crates/horizon-client/src/game/lan_entities.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 529666590..3c5b11988 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -386,6 +386,9 @@ impl Game<'_> { let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); e.pitch = t.pitch; e.velocity = at(t.velocity); + // Projectile.getAddEntityPacket: the owner's id; a trident here is + // always the host player's. + e.data = owner(Some(horizon_client::mobs::Who::Player)); e.meta = arrow_meta(false, t.no_physics, 0, t.in_ground); // ThrownTrident.ID_LOYALTY and ID_FOIL. if t.loyalty != 0 { From d0df2389726563ee5d65efb184108c60f2de0df8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:19:49 +0100 Subject: [PATCH 100/221] Include equipment modifiers in a mob's knockback resistance for the sonic boom push --- crates/horizon-client/src/game/creatures.rs | 2 +- .../horizon-client/src/game/lan_attributes.rs | 31 +++++++++++++++++++ crates/horizon-client/src/mobs/finalize.rs | 11 +++++-- 3 files changed, 40 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index c7b033c03..b7fb75fb4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -993,7 +993,7 @@ impl Game<'_> { .mobs .iter() .find(|m| m.id == id) - .map_or(0.0, |m| m.attrs.knockback_resistance); + .map_or(0.0, |m| self.mob_knockback_resistance(m)); (hurt, resistance) } }; diff --git a/crates/horizon-client/src/game/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs index 73942e770..9909c88f6 100644 --- a/crates/horizon-client/src/game/lan_attributes.rs +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -24,6 +24,37 @@ fn slot_in_group(group: &str, slot: &str) -> bool { } impl Game<'_> { + /// `getAttributeValue(KNOCKBACK_RESISTANCE)` of a mob: its own value plus + /// the modifiers of the items it wears or holds in matching slots. + pub(super) fn mob_knockback_resistance(&self, m: &Mob) -> f64 { + let e = &m.extra; + let slots = [ + ("mainhand", &e.main_hand), + ("offhand", &e.off_hand), + ("feet", &e.feet), + ("legs", &e.legs), + ("chest", &e.chest), + ("head", &e.head), + ]; + let mut extra = Vec::new(); + for (slot, item) in slots { + let Some(info) = item.as_ref().and_then(|i| self.res.items().get(i)) else { + continue; + }; + for (attribute, _, amount, op, group) in &info.modifiers { + if attribute == "minecraft:knockback_resistance" && slot_in_group(group, slot) { + let op = match operation_named(op) { + 1 => Op::AddMultipliedBase, + 2 => Op::AddMultipliedTotal, + _ => Op::AddValue, + }; + extra.push((*amount, op)); + } + } + } + finalize::value_with(m, Attr::KnockbackResistance, &extra) + } + /// The registry id of a client-syncable attribute the entity type has /// (`AttributeMap.getInstance` is null for the others), by name. fn synced_attribute(&self, entity: &str, name: &str) -> Option { diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 4eeed885b..be1ff952a 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -516,9 +516,13 @@ fn effect_modifiers(m: &Mob, a: Attr) -> impl Iterator + '_ { } /// `AttributeInstance.getValue`: the base, then the modifiers by operation. pub fn value(m: &Mob, a: Attr) -> f64 { - compute(m, a, true) + compute(m, a, true, &[]) } -fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 { +/// `value` with more modifiers, such as the ones worn equipment grants. +pub fn value_with(m: &Mob, a: Attr, extra: &[(f64, Op)]) -> f64 { + compute(m, a, true, extra) +} +fn compute(m: &Mob, a: Attr, with_transient: bool, extra: &[(f64, Op)]) -> f64 { let mut base = base_value(m, a); let empty = Vec::new(); let mods = m.extra.attributes.as_ref().map_or(&empty, |s| &s.modifiers); @@ -531,6 +535,7 @@ fn compute(m: &Mob, a: Attr, with_transient: bool) -> f64 { ops.extend(transient(m, a)); ops.extend(effect_modifiers(m, a)); } + ops.extend(extra.iter().copied()); for (amount, op) in &ops { if *op == Op::AddValue { base += amount; @@ -573,7 +578,7 @@ fn refresh(m: &mut Mob, a: Attr) { /// The value without the transient baby modifier (`speed_bonus` applies /// that one to movement speed). fn base_with_modifiers(m: &Mob, a: Attr) -> f64 { - compute(m, a, false) + compute(m, a, false, &[]) } /// `AttributeInstance.setBaseValue`. pub fn set_base(m: &mut Mob, a: Attr, v: f64) { From 2d70e55fbbffeb5c8b7105ca970a22d195332ef5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:21:42 +0100 Subject: [PATCH 101/221] Load the respawn search's candidate chunks instead of skipping unloaded ones --- crates/horizon-client/src/game.rs | 18 ++++- crates/horizon-client/src/game/end.rs | 33 +++++++-- .../horizon-client/src/game/initial_spawn.rs | 73 +++++++++---------- .../horizon-client/src/game/server_travel.rs | 34 +++++++-- 4 files changed, 106 insertions(+), 52 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2d853cbe5..e6abe53b4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1366,6 +1366,9 @@ struct Game<'a> { spawn_spiral: horizon_client::world_spawn::ChunkSpiral, /// A new player's spawn search, while its candidates' chunks load. player_spawn: Option, + /// Chunks a respawn search waits for this tick, kept loading beside the + /// player's own (taken by `update_world`). + spawn_wait: Vec<(i32, i32)>, mobs: Vec, creatures: creatures::Creatures, sculk: sculk::SculkState, @@ -4256,8 +4259,12 @@ impl Game<'_> { let column = [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32]; if self.level.world_spawn == Some(column) { // TeleportTransition.missingRespawnBlock: PlayerSpawnFinder - // around the world spawn, not its exact column. - self.respawn_spawn(column) + // around the world spawn, not its exact column; its candidates' + // chunks load first. + let Some(feet) = self.find_player_spawn(column)? else { + return Ok(()); + }; + feet } else { // A spawnpoint: the stored column, lifted onto its current surface. let y = self @@ -11137,8 +11144,14 @@ impl Game<'_> { self.streaming.loading = self.options.execution_role.is_client() && self.loading_reason().is_some(); self.tick_pregen(); + let areas = self.streaming.extra.len(); + let waiting = std::mem::take(&mut self.spawn_wait); + self.streaming + .extra + .extend(waiting.into_iter().map(|chunk| (chunk, 0))); let (uploads, unloaded) = horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world)); + self.streaming.extra.truncate(areas); if let Some(lod) = &mut self.lod { self.lod_observe .extend(uploads.iter().map(|(key, _)| (key.0, key.2))); @@ -12426,6 +12439,7 @@ impl<'a> Game<'a> { spawn_origin: None, spawn_spiral: Default::default(), player_spawn: None, + spawn_wait: Vec::new(), mobs: Vec::new(), creatures: Default::default(), sculk: Default::default(), diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index f11d4a61c..cffe3aa4b 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -11,6 +11,7 @@ use horizon_client::{ motion::PlayerMotion, particles::{ParticleOptions, ParticleType}, vanillagen::VanillaTerrain, + world_spawn::PlayerSpawnFinder, }; use horizon_core::{ geometry::Vec3, @@ -521,7 +522,15 @@ impl Game<'_> { let position = if let Some(job) = self.end.job.take() { self.resolve_gateway(job, target)? } else { - let (position, yaw) = self.end_arrival(target)?; + let mut finder = self.player_spawn.take(); + let arrival = self.end_arrival(target, &mut finder); + self.player_spawn = finder; + let Some((position, yaw)) = arrival? else { + // A spawn candidate's chunk is loading: try again next tick. + self.travelling = Some((player, target)); + self.end_travel = true; + return Ok(()); + }; if let Some(yaw) = yaw { self.yaw = yaw; player.yaw = yaw; @@ -546,7 +555,13 @@ impl Game<'_> { /// Where an End portal's traveller lands once `target` has loaded, and /// the yaw it faces there: the platform below the End's spawn point, /// facing west, or the top of the Overworld's spawn column. - pub(super) fn end_arrival(&mut self, target: Vec3) -> Result<(Vec3, Option)> { + /// None while a candidate of the world spawn's search loads (`finder` + /// keeps it, see `search_spawn`). + pub(super) fn end_arrival( + &mut self, + target: Vec3, + finder: &mut Option, + ) -> Result)>> { if self.dim == Dim::End { // EndPlatformFeature.createEndPlatform below the spawn point. let origin = [END_SPAWN[0], END_SPAWN[1] - 1, END_SPAWN[2]]; @@ -566,14 +581,14 @@ impl Game<'_> { } } // Direction.WEST.toYRot(). - return Ok((target, Some(90.0))); + return Ok(Some((target, Some(90.0)))); } // ServerPlayer.findRespawnPositionAndUseSpawnBlock: where the bed or // anchor puts the player, facing it; else onto the spawn column. let mut target = target; if let Some(c) = self.respawn_config.filter(|c| c.dim == self.dim) { if let Some((at, yaw)) = self.find_respawn_and_use(c, false)? { - return Ok((at, Some(yaw))); + return Ok(Some((at, Some(yaw)))); } let s = self.level.spawn.unwrap_or([0.0, 64.0, 0.0]); target = Vec3::new(s[0].floor() + 0.5, s[1], s[2].floor() + 0.5); @@ -582,10 +597,16 @@ impl Game<'_> { // TeleportTransition.missingRespawnBlock: PlayerSpawnFinder around // the world spawn. if let Some(world) = self.level.world_spawn.filter(|w| w[0] == x && w[2] == z) { - return Ok((self.respawn_spawn(world), None)); + return Ok(match self.search_spawn(world, finder) { + Ok(at) => Some((at, None)), + Err(chunk) => { + self.spawn_wait.push(chunk); + None + } + }); } let y = self.land_column(x, z).map_or(target.y, f64::from); - Ok((Vec3::new(target.x, y, target.z), None)) + Ok(Some((Vec3::new(target.x, y, target.z), None))) } /// Dying away from the Overworld respawns at the world spawn there. diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index bcea90337..d4c48c140 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -145,61 +145,58 @@ impl Game<'_> { entity_random().next_int_bound(n).unwrap_or(0) }) } - /// PlayerSpawnFinder.findSpawn around the world spawn for a player placed - /// at once (TeleportTransition.createDefault and missingRespawnBlock): the - /// first free column within the respawn radius, the suggestion's own - /// column when none is. A candidate whose chunk is not loaded counts as - /// not free; the suggestion's chunk must be. - pub(super) fn respawn_spawn(&self, suggestion: [i32; 3]) -> Vec3 { - let mut finder = self.spawn_finder(suggestion); - while let Some(candidate) = finder.next_candidate() { - let SpawnCandidate::Column(x, z) = candidate else { - break; - }; - if !self.streaming.is_lit(x >> 4, z >> 4) { - continue; - } - if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z) - && self.player_fits(pos) - { - return bottom_center(pos); - } - } - self.fixup_spawn_height(suggestion) - } - /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a - /// player who has no position yet. None while a candidate's chunk loads. - pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { - let mut finder = match self.player_spawn { - Some(finder) => finder, - None => self.spawn_finder(suggestion), - }; - let found = loop { + /// PlayerSpawnFinder.findSpawn around the world spawn, as far as the loaded + /// chunks allow: the feet of the first free column within the respawn + /// radius, else the suggestion's own column. The finder waits in `state` + /// (None to begin); Err gives the chunk of the candidate being waited for, + /// which the caller must have loaded (the finder tries at most 1024 + /// columns). + pub(super) fn search_spawn( + &self, + suggestion: [i32; 3], + state: &mut Option, + ) -> std::result::Result { + let mut finder = state + .take() + .unwrap_or_else(|| self.spawn_finder(suggestion)); + let suggestion = finder.suggestion; + loop { let Some(candidate) = finder.next_candidate() else { - break Some(self.fixup_spawn_height(suggestion)); + return Ok(self.fixup_spawn_height(suggestion)); }; let (x, z) = match candidate { SpawnCandidate::Column(x, z) => (x, z), SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]), }; if !self.streaming.is_lit(x >> 4, z >> 4) { - self.streaming.center = (x >> 4, z >> 4); finder.retry(); - break None; + *state = Some(finder); + return Err((x >> 4, z >> 4)); } match candidate { SpawnCandidate::Column(x, z) => { if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z) && self.player_fits(pos) { - break Some(bottom_center(pos)); + return Ok(bottom_center(pos)); } } - SpawnCandidate::Suggestion => break Some(self.fixup_spawn_height(suggestion)), + SpawnCandidate::Suggestion => return Ok(self.fixup_spawn_height(suggestion)), } - }; - self.player_spawn = found.is_none().then_some(finder); - Ok(found) + } + } + /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a + /// player who has no position yet. None while a candidate's chunk loads. + pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { + let mut state = self.player_spawn.take(); + match self.search_spawn(suggestion, &mut state) { + Ok(feet) => Ok(Some(feet)), + Err(chunk) => { + self.streaming.center = chunk; + self.player_spawn = state; + Ok(None) + } + } } /// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the /// block's bottom centre touches no block or liquid. diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index e22cd60e9..ac983dff1 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -11,7 +11,7 @@ use super::end::GatewayJob; use super::nether_portal::{PLAYER_DELAY, Plan}; use super::respawn_anchor::RespawnConfig; use super::{Dim, Game, lan::LanHost}; -use horizon_client::{lan::hub::TickCtx, text::Text}; +use horizon_client::{lan::hub::TickCtx, text::Text, world_spawn::PlayerSpawnFinder}; use horizon_core::{geometry::Vec3, position::BlockPos}; use horizon_protocol::packets::play::{self, Clientbound as C}; @@ -34,6 +34,8 @@ pub(super) struct Trip { /// A respawn at the world spawn, moved onto a free column within the /// respawn radius once the chunks around it have loaded. world_spawn: bool, + /// The search for that column while a candidate's chunk loads. + finder: Option, /// Sent by a command: the player is already where it goes. placed: bool, } @@ -258,6 +260,7 @@ impl Game<'_> { gateway: None, respawn: None, world_spawn: false, + finder: None, placed: false, }); if let Err(e) = self.enter_level(Some(host), source) { @@ -278,6 +281,7 @@ impl Game<'_> { gateway: None, respawn: Some(config), world_spawn: false, + finder: None, placed: false, }); } @@ -327,6 +331,7 @@ impl Game<'_> { gateway: None, respawn: None, world_spawn: true, + finder: None, placed: false, }); } @@ -372,6 +377,7 @@ impl Game<'_> { gateway: Some(job), respawn: None, world_spawn: false, + finder: None, placed: false, }); } @@ -398,7 +404,7 @@ impl Game<'_> { k += 1; continue; } - let trip = self.server_trips.remove(k); + let mut trip = self.server_trips.remove(k); if trip.placed { continue; } @@ -416,7 +422,15 @@ impl Game<'_> { // PlayerSpawnFinder.findSpawn around the world spawn. let suggestion = [trip.target.x, trip.target.y, trip.target.z].map(|v| v.floor() as i32); - (self.respawn_spawn(suggestion), yaw) + match self.search_spawn(suggestion, &mut trip.finder) { + Ok(at) => (at, yaw), + Err(chunk) => { + self.spawn_wait.push(chunk); + self.server_trips.insert(k, trip); + k += 1; + continue; + } + } } else if let Some(job) = trip.gateway { match self.resolve_gateway(job, trip.target) { Ok(at) => (at, yaw), @@ -426,12 +440,19 @@ impl Game<'_> { } } } else if trip.end { - let arrival = match self.as_guest(host, trip.conn, |g| g.end_arrival(trip.target)) { + let arrival = match self.as_guest(host, trip.conn, |g| { + g.end_arrival(trip.target, &mut trip.finder) + }) { Some(arrival) => arrival, - None => self.end_arrival(trip.target), + None => self.end_arrival(trip.target, &mut trip.finder), }; match arrival { - Ok((at, turned)) => (at, turned.unwrap_or(yaw)), + Ok(Some((at, turned))) => (at, turned.unwrap_or(yaw)), + Ok(None) => { + self.server_trips.insert(k, trip); + k += 1; + continue; + } Err(e) => { log::error!("End arrival: {e}"); (trip.target, yaw) @@ -493,6 +514,7 @@ impl Game<'_> { gateway: None, respawn: None, world_spawn: false, + finder: None, placed: true, }); if let Err(e) = self.enter_level(Some(host), source) { From fba004eb3d6b44250fa4e8bcd4d72b700e4a58c5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:22:41 +0100 Subject: [PATCH 102/221] Skip leaves in the no-leaves heightmap for firefly bush sounds --- crates/horizon-client/src/game/render_tick.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index d106e32ad..70e404a3d 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -33,7 +33,14 @@ fn motion_blocking_leaves( let mut y = from.min(MIN_Y + HEIGHT - 1); while y > MIN_Y { let f = facts.get(world.block(x, y, z)); - if f.full_collision || f.fluid != Fluid::None || leaves && f.name.contains("leaves") { + // #minecraft:leaves block motion, but MOTION_BLOCKING_NO_LEAVES skips them + // (their water still counts). + let blocks = if f.name.ends_with("_leaves") { + leaves + } else { + f.full_collision + }; + if blocks || f.fluid != Fluid::None { return y + 1; } y -= 1; From 1a5e5eb35828554deff92538bc21dd50cb0f0209 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:37:58 +0100 Subject: [PATCH 103/221] Owner combat goals only follow the wolf's own owner --- crates/horizon-client/src/mobs/tame.rs | 28 ++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index b6d0b1bb7..5c59f840d 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -388,7 +388,12 @@ impl Goal for OwnerHurtBy { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) else { + let Some((who, at)) = + cx.w.player + .as_ref() + .filter(|p| m.extra.owner == Some(p.uuid)) + .and_then(|p| p.hurt_by) + else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -399,7 +404,12 @@ impl Goal for OwnerHurtBy { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.hurt_by) { + if let Some((who, at)) = + cx.w.player + .as_ref() + .filter(|p| m.extra.owner == Some(p.uuid)) + .and_then(|p| p.hurt_by) + { m.ai.target = Some(who); self.timestamp = at; } @@ -422,7 +432,12 @@ impl Goal for OwnerHurt { if !m.extra.tame || m.extra.sitting { return false; } - let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) else { + let Some((who, at)) = + cx.w.player + .as_ref() + .filter(|p| m.extra.owner == Some(p.uuid)) + .and_then(|p| p.last_hurt) + else { return false; }; at != self.timestamp && wants_to_attack(m, cx.w, who) @@ -433,7 +448,12 @@ impl Goal for OwnerHurt { .is_some_and(|t| t.alive) } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - if let Some((who, at)) = cx.w.player.as_ref().and_then(|p| p.last_hurt) { + if let Some((who, at)) = + cx.w.player + .as_ref() + .filter(|p| m.extra.owner == Some(p.uuid)) + .and_then(|p| p.last_hurt) + { m.ai.target = Some(who); self.timestamp = at; } From be714b38bbc3e27aa2d5aa1b3f0244b490c7d16b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:38:16 +0100 Subject: [PATCH 104/221] Only let a tame parrot land on its saved owner --- crates/horizon-client/src/game/shoulders.rs | 4 ++++ crates/horizon-client/src/mobs/tame.rs | 16 +++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/shoulders.rs b/crates/horizon-client/src/game/shoulders.rs index 602c5a5af..7dfc2f355 100644 --- a/crates/horizon-client/src/game/shoulders.rs +++ b/crates/horizon-client/src/game/shoulders.rs @@ -27,6 +27,10 @@ impl Game<'_> { let Some(p) = self.player.as_ref() else { return; }; + // The acting player must be the saved owner (`getOwner`). + if !horizon_client::mobs::tame::owned_by(self.mobs[i].extra.owner, self.acting_uuid()) { + return; + } if self.riding.is_some() || !p.ground.on_ground || p.fluids.was_touching_water diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 82d808b7f..3002ce1f7 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -123,13 +123,15 @@ impl Goal for LandOnOwnersShoulder { } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { // ShoulderRidingEntity.canSitOnShoulder: rideCooldownCounter > 100. - owner(m, cx.w).is_some_and(|(_, _, spectator)| !spectator) + is_owner(m, cx.w) + && owner(m, cx.w).is_some_and(|(_, _, spectator)| !spectator) && !m.extra.sitting && m.age > 100 } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { if !m.extra.sitting && m.extra.leash.is_none() + && is_owner(m, cx.w) && cx .w .player @@ -172,6 +174,18 @@ fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { let p = w.player.as_ref()?; Some((p.position, p.eye[1], p.spectator)) } +/// Whether the player the mob sees is the one saved as its owner (with +/// guests on, that player is whoever stands nearest). +fn is_owner(m: &Mob, w: &MobWorld) -> bool { + w.player + .as_ref() + .is_some_and(|p| owned_by(m.extra.owner, p.uuid)) +} +/// Whether `uuid` is the saved owner. A host with no UUID yet owns what it +/// tamed under the placeholder `[0, 0, 0, 1]`. +pub fn owned_by(owner: Option<[i32; 4]>, uuid: [i32; 4]) -> bool { + owner.is_some_and(|o| o == uuid || (o == [0, 0, 0, 1] && uuid == [0; 4])) +} /// `TamableAnimal.unableToMoveToOwner`. fn unable_to_move_to_owner(m: &Mob, w: &MobWorld) -> bool { m.extra.sitting || w.player.as_ref().is_some_and(|p| p.spectator) From 7eaa5f592bf777340b949253732253bbb70df1ea Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:38:21 +0100 Subject: [PATCH 105/221] Send jukebox play and stop events to guests so their parrots dance --- crates/horizon-client/src/game.rs | 4 ++++ crates/horizon-client/src/game/jukebox.rs | 14 ++++++++++++-- crates/horizon-client/src/game/lan.rs | 11 +++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 8e4038b80..dafc68cba 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1640,6 +1640,9 @@ struct Game<'a> { guest_use: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + /// Jukebox level events 1010 (song name) and 1011 (`None`) for the guests; + /// the song's network id is only known once the hub is in hand. + lan_songs: Vec<([i32; 3], Option)>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, @@ -12664,6 +12667,7 @@ impl<'a> Game<'a> { forced_hit: None, guest_use: None, lan_events: Vec::new(), + lan_songs: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), lan_critical_hits: Vec::new(), diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 5c55c5f54..895b69490 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -99,7 +99,7 @@ impl Game<'_> { } /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. fn start_song(&mut self, pos: [i32; 3], song: &str) { - self.stop_song(pos); + self.stop_sound(pos); let Some(s) = self.res.items().songs.get(song).cloned() else { return; }; @@ -112,12 +112,22 @@ impl Game<'_> { .set_overlay(Text::translate("record.nowPlaying", &[description]), true); self.update_song_volumes(); self.notify_record_playing(pos, true); + if self.audio.capture.is_some() { + self.lan_songs.push((pos, Some(song.to_owned()))); + } } - fn stop_song(&mut self, pos: [i32; 3]) { + fn stop_sound(&mut self, pos: [i32; 3]) { if let Some(id) = self.jukebox_sounds.remove(&(pos[0], pos[1], pos[2])) { self.audio.stop_and_release(id); } + } + /// Level event 1011: the song ends, here and for the guests. + fn stop_song(&mut self, pos: [i32; 3]) { + self.stop_sound(pos); self.notify_record_playing(pos, false); + if self.audio.capture.is_some() { + self.lan_songs.push((pos, None)); + } } /// `LevelEventHandler.notifyNearbyEntities` (level events 1010 and 1011): /// parrots within three blocks of the jukebox start or stop dancing. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..cb6c0b470 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -664,6 +664,7 @@ impl Game<'_> { self.world.light_log = None; self.audio.capture = None; self.lan_events.clear(); + self.lan_songs.clear(); self.lan_critical_hits.clear(); self.streaming.extra.clear(); if announce { @@ -1255,6 +1256,16 @@ impl Game<'_> { } host.hub.level_event(kind, pos, data, acting); } + // Level events 1010 and 1011: the guests' parrots dance or stop. + for (pos, song) in std::mem::take(&mut self.lan_songs) { + match song { + Some(name) => { + let id = host.hub.registry_id("minecraft:jukebox_song", &name); + host.hub.level_event(1010, pos, id.unwrap_or(0), None); + } + None => host.hub.level_event(1011, pos, 0, None), + } + } for (pos, b0, b1, state) in std::mem::take(&mut self.lan_block_events) { host.hub.block_event(pos, b0, b1, state); } From 2a297a43eb65807666978fd75128bb779e61b8f5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:42:51 +0100 Subject: [PATCH 106/221] Credit the feeder with a parrot's cookie kill --- crates/horizon-client/src/game/creatures.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 45568dc12..069768cb8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2830,10 +2830,15 @@ impl Game<'_> { { consume = true; m.add_effect("minecraft:poison", 900, 0); - m.damage( + let id = m.id; + let hurt = m.damage( f32::MAX, horizon_client::mobs::Damage::player(player_at.unwrap_or(center)), ); + // The feeder gets the kill, as for a normal player attack. + if hurt { + self.last_hurt_by_player.insert(id, self.lan_acting); + } } // Parrot.mobInteract: parrot food may tame a wild one (one time in // ten); a parrot never takes it as Animal food (isFood is false). From daee960ba2ee0f868e26b02e7e5ce0ab468a6f5a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:43:21 +0100 Subject: [PATCH 107/221] Send an armor stand's default pose when it is reset --- crates/horizon-client/src/game/lan_entities.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index cee626117..55334cac7 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -167,6 +167,18 @@ impl Game<'_> { e.meta.push((15, serializer::BYTE, Value::Byte(flags))); } e.meta.extend(stand_poses(a)); + // A pose put back to its default (`/data`) is sent as that default. + e.defaults.push((15, serializer::BYTE, Value::Byte(0))); + for (i, default) in horizon_client::entities::ArmorStand::DEFAULT_POSE + .iter() + .enumerate() + { + e.defaults.push(( + 16 + i as u8, + serializer::ROTATIONS, + Value::Floats(default.to_vec()), + )); + } // Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5. for (slot, item) in a.equipment.iter().enumerate() { if item.is_some() { From 512e003cbd50f13572286ee759a26a33ef0b08dc Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:43:50 +0100 Subject: [PATCH 108/221] Wolf armor: check the acting player's UUID and keep the armor's components --- crates/horizon-client/src/entity_nbt.rs | 8 +++++--- crates/horizon-client/src/game/creatures.rs | 11 +++++++---- crates/horizon-client/src/game/lan.rs | 6 +++++- crates/horizon-client/src/game/lan_mobs.rs | 8 ++++++++ crates/horizon-client/src/mobs.rs | 3 +++ crates/horizon-client/src/mobs/drops.rs | 1 + 6 files changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 18f89d884..8e64652c9 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -551,6 +551,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { { let mut stack = crate::items::ItemStack::new(id, 1); stack.damage = m.extra.body_damage.max(0) as u32; + stack.extra = m.extra.body_extra.clone(); equipment.insert(slot.into(), crate::save::item_to_nbt(&stack)); continue; } @@ -790,11 +791,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - crate::mobs::tame::set_tame(&mut m, tame); m.health = health; m.extra.sitting = flag(tag, "Sitting"); - m.extra.body_damage = tag + let armor = tag .get("equipment") .and_then(|e| e.get("body")) - .and_then(crate::save::item_from_nbt) - .map_or(0, |s| s.damage as i32); + .and_then(crate::save::item_from_nbt); + m.extra.body_damage = armor.as_ref().map_or(0, |s| s.damage as i32); + m.extra.body_extra = armor.and_then(|s| s.extra); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); if let Some(Tag::String(v)) = tag.get("variant") { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index a72d53c6b..7f470252c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2559,10 +2559,11 @@ impl Game<'_> { .items() .get(&item) .is_some_and(|i| i.max_damage > 0); - let me = self.level.player_uuid.or(Some([0, 0, 0, 1])); + let me = self.acting_owner(); let sneaking = self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft) || self.keys.contains(&winit::keyboard::KeyCode::ShiftRight); let held_damage = held.as_ref().map_or(0, |h| h.damage as i32); + let held_extra = held.as_ref().and_then(|h| h.extra.clone()); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2653,6 +2654,7 @@ impl Game<'_> { { let mut stack = ItemStack::new("minecraft:wolf_armor", 1); stack.damage = m.extra.body_damage.max(0) as u32; + stack.extra = m.extra.body_extra.take(); armor_drop = Some(stack); m.extra.head = None; m.extra.body_damage = 0; @@ -2682,6 +2684,7 @@ impl Game<'_> { { m.extra.head = Some(item.as_str().into()); m.extra.body_damage = held_damage; + m.extra.body_extra = held_extra; consume = true; eat = Some(("item.armor.equip_wolf", 1.0, 1.0)); } @@ -2745,7 +2748,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { horizon_client::mobs::tame::set_tame(m, true); - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = me; m.persistent = true; m.nav_stop(); m.ai.target = None; @@ -2821,7 +2824,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0; if tamed { m.extra.tame = true; - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = me; m.extra.sitting = true; } eat = eating_sound(m, &mut self.world.random); @@ -2877,7 +2880,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0; if tamed { m.extra.tame = true; - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = me; } let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 7897b5c57..2000a0db5 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -385,7 +385,11 @@ fn mob_equipment( } else { 0 }, - extra: None, + extra: if slot == 5 && m.species() == horizon_client::mobs::Species::Wolf { + e.body_extra.clone() + } else { + None + }, }; out.push((slot, hub.stack(&Some(stack)))); } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..d1f0e16cd 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -328,6 +328,14 @@ impl Game<'_> { .collect() } /// The UUID of the player acting: the guest `as_guest` runs, else the host. + /// The owner a wolf, cat or parrot gets when the acting player tames it + /// (a host with no UUID yet owns under `[0, 0, 0, 1]`). + pub(super) fn acting_owner(&self) -> Option<[i32; 4]> { + self.lan_acting_uuid + .map(horizon_client::lan::playerdata::uuid_ints) + .or(self.level.player_uuid) + .or(Some([0, 0, 0, 1])) + } pub(super) fn acting_uuid(&self) -> [i32; 4] { self.lan_acting_uuid .map(horizon_client::lan::playerdata::uuid_ints) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f9a53f0f2..81f2b90f0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -663,6 +663,8 @@ pub struct Extra { pub saddled: bool, /// The durability a wolf's body armor (`extra.head`) has lost. pub body_damage: i32, + /// The components (dye, name...) of that armor stack. + pub body_extra: Option>, /// The saddle's components (name, enchantments...) when it is not a bare /// one; `saddled` stays the gameplay flag. pub saddle_stack: Option, @@ -1858,6 +1860,7 @@ impl Mob { if after >= WOLF_ARMOR_DURABILITY { self.extra.head = None; self.extra.body_damage = 0; + self.extra.body_extra = None; self.outbox .push(MobEvent::Sound("item.wolf_armor.break", at, 1.0, 1.0)); } else { diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 28ba2a0cd..be3a06174 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -286,6 +286,7 @@ pub fn clear_slot(m: &mut Mob, slot: &str) { "body" if body => { m.extra.head = None; m.extra.body_damage = 0; + m.extra.body_extra = None; return; } "saddle" => { From 6145077d7e094b19a0940fbf94bd13de10a03a37 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:44:11 +0100 Subject: [PATCH 109/221] Make a tame parrot answer only to its owner --- crates/horizon-client/src/game/creatures.rs | 10 ++++++++-- crates/horizon-client/src/game/lan_mobs.rs | 15 ++++++++++++++- crates/horizon-client/src/mobs/tame.rs | 6 +++++- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8eb4cc911..1b9a31679 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2565,6 +2565,7 @@ impl Game<'_> { .item_tags .get("minecraft:parrot_poisonous_food") .is_some_and(|t| t.contains(&*item)); + let acting = self.acting_uuid(); let m = &mut self.mobs[index]; if !m.alive() { return Ok(false); @@ -2772,7 +2773,12 @@ impl Game<'_> { } // Parrot.mobInteract: the owner makes a tame parrot on the ground // sit or stand (poisonous food is handled apart). - Species::Parrot if m.extra.tame && m.on_ground && !parrot_poisonous => { + Species::Parrot + if m.extra.tame + && m.extra.owner == Some(acting) + && m.on_ground + && !parrot_poisonous => + { m.extra.sitting = !m.extra.sitting; self.world.modified.insert(( m.position.x.floor() as i32 >> 4, @@ -2841,7 +2847,7 @@ impl Game<'_> { let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0; if tamed { m.extra.tame = true; - m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); + m.extra.owner = Some(acting); } let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 4f53cec60..39bbd9794 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -5,7 +5,7 @@ //! (hits, pushes, fire, its projectiles) runs with that guest swapped in. use super::{Game, lan::LanHost}; use horizon_client::{ - mobs::{Mob, MobEvent, PlayerView, Who}, + mobs::{Mob, MobEvent, PlayerView, Species, Who}, projectiles::{Hit, Projectile}, }; use horizon_core::geometry::{Aabb, Vec3}; @@ -26,6 +26,19 @@ pub(super) fn player_for( guests: &GuestViews, bound: Option, ) -> Option { + // A tame parrot sees its owner (`TamableAnimal.getOwner`), while they + // are in play, whoever is nearer. + if m.species() == Species::Parrot + && m.extra.tame + && let Some(owner) = m.extra.owner + { + if host.is_some_and(|v| v.alive && v.uuid == owner) { + return None; + } + if let Some((conn, _)) = guests.iter().find(|(_, v)| v.alive && v.uuid == owner) { + return Some(*conn); + } + } let targeting = m.ai.target == Some(Who::Player) || m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100; choose(m.position, targeting, host, guests, bound) diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 0043ff9ef..d757db0fe 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -135,12 +135,16 @@ pub fn set_tame(m: &mut Mob, tame: bool) { m.attrs.max_health = 8.0; } } -/// The owner (the local player) when tame. +/// The owner (the local player) when tame. A parrot's owner is the player +/// its saved UUID names (`TamableAnimal.getOwner`), not whoever is nearest. fn owner(m: &Mob, w: &MobWorld) -> Option<(Vec3, f64, bool)> { if !m.extra.tame { return None; } let p = w.player.as_ref()?; + if m.species() == Species::Parrot && m.extra.owner != Some(p.uuid) { + return None; + } Some((p.position, p.eye[1], p.spectator)) } /// `TamableAnimal.unableToMoveToOwner`. From b0ce58adeab076fe9bd0eb93ff3c985032be6267 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:48:18 +0100 Subject: [PATCH 110/221] Check the cat's owner and sync lying and relaxing to clients --- crates/horizon-client/src/game/lan.rs | 9 ++++++ crates/horizon-client/src/game/lan_mobs.rs | 16 +++++++++- crates/horizon-client/src/game/remote.rs | 5 ++++ .../src/game/remote_mob_data.rs | 3 ++ crates/horizon-client/src/mobs/tame.rs | 29 ++++++++++++++----- 5 files changed, 54 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 5292cd31b..44c669bd6 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -252,6 +252,15 @@ fn mob_meta( if let Some(v) = id(registry, name) { meta.push((index, serializer, Value::Id(v))); } + // Cat.IS_LYING and RELAX_STATE_ONE. + if kind == "minecraft:cat" { + for (index, on) in [(21, e.flag), (22, e.relax_one)] { + if on { + meta.push((index, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((index, serializer::BOOLEAN, Value::Bool(false))); + } + } // Wolf.DATA_COLLAR_COLOR and Cat's, red by default. let collar = if kind == "minecraft:cat" { 23 } else { 21 }; let red = i32::from(horizon_client::mobs::tame::RED); diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 1d3b3d086..0d37de086 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -5,7 +5,7 @@ //! (hits, pushes, fire, its projectiles) runs with that guest swapped in. use super::{Game, lan::LanHost}; use horizon_client::{ - mobs::{Mob, MobEvent, PlayerView, Who}, + mobs::{Mob, MobEvent, PlayerView, Species, Who}, projectiles::{Hit, Projectile}, }; use horizon_core::geometry::{Aabb, Vec3}; @@ -26,6 +26,20 @@ pub(super) fn player_for( guests: &GuestViews, bound: Option, ) -> Option { + // A tame cat reads its owner wherever they are while they sleep, or just + // woke up (`CatRelaxOnOwnerGoal` uses `getOwner`, not the nearest player). + if m.species() == Species::Cat + && m.extra.tame + && let Some(owner) = m.extra.owner + { + let asleep = |v: &PlayerView| v.uuid == owner && (v.sleeping || v.sleep_timer > 0); + if host.is_some_and(asleep) { + return None; + } + if let Some((conn, _)) = guests.iter().find(|(_, v)| asleep(v)) { + return Some(*conn); + } + } let targeting = m.ai.target == Some(Who::Player) || m.ai.last_hurt_by == Some(Who::Player) && m.age as i32 - m.ai.last_hurt_by_time <= 100; choose(m.position, targeting, host, guests, bound) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..3eb6b56db 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3535,6 +3535,11 @@ impl Game<'_> { m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; *steps -= 1; } + // Cat.tick: the lying and relaxing amounts follow the synched flags. + if m.species() == horizon_client::mobs::Species::Cat { + m.anim.vo = m.anim.v; + horizon_client::mobs::tame::cat_amounts(m); + } // Chicken.aiStep: the wings follow the server's on-ground flag. if m.species() == horizon_client::mobs::Species::Chicken { horizon_client::mobs::farm::chicken_flap(m); diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..3d775d6dd 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -71,6 +71,9 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti m.extra.sitting = flags & 1 != 0; m.extra.tame = flags & 4 != 0; } + // Cat.IS_LYING and RELAX_STATE_ONE. + (Species::Cat, 21, Value::Bool(lying)) => m.extra.flag = *lying, + (Species::Cat, 22, Value::Bool(relaxing)) => m.extra.relax_one = *relaxing, // Wolf.DATA_COLLAR_COLOR and Cat's. (Species::Wolf, 21, Value::Int(c)) | (Species::Cat, 23, Value::Int(c)) => { m.extra.color = (*c & 15) as u8; diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 7998b4763..4396c4487 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -800,6 +800,11 @@ fn empty_above(w: &MobWorld, p: [i32; 3]) -> bool { .as_ref() == "minecraft:air" } +/// Whether `p` is the player that owns `m` (a cat without a recorded owner +/// belongs to whoever it sees). +pub fn is_owner(m: &Mob, p: &super::PlayerView) -> bool { + m.extra.owner.is_none_or(|o| o == p.uuid) +} /// `Cat.CatRelaxOnOwnerGoal`: while the owner sleeps, the cat lies down beside /// them, and may leave a morning gift when they wake up. #[derive(Clone, Debug, Default)] @@ -827,11 +832,12 @@ impl CatRelaxOnOwner { o.species == Species::Cat && o.id != m.id && o.lying && o.bounds.intersects(area) }) } - /// The owner's sleeping state, when this cat may relax on them. + /// The owner's sleeping state, when this cat may relax on them: the + /// player it sees has to be its owner (`Cat.getOwner`). fn sleeping_owner<'w>(m: &Mob, w: &'w MobWorld) -> Option<&'w super::PlayerView> { w.player .as_ref() - .filter(|p| m.extra.tame && !m.extra.sitting && p.sleeping) + .filter(|p| m.extra.tame && !m.extra.sitting && p.sleeping && is_owner(m, p)) } } impl Goal for CatRelaxOnOwner { @@ -891,7 +897,11 @@ impl Goal for CatRelaxOnOwner { } else { 0.0 }; - if cx.w.player.as_ref().is_some_and(|p| p.sleep_timer >= 100) + if cx + .w + .player + .as_ref() + .is_some_and(|p| is_owner(m, p) && p.sleep_timer >= 100) && m.random.next_float() < chance { give_morning_gift(m, cx); @@ -1127,6 +1137,15 @@ impl Goal for OcelotAttack { } /// `Cat.tick`: lying and relaxing amounts and the purr. pub fn cat_ai_step(m: &mut Mob, events: &mut Vec) { + cat_amounts(m); + if (m.extra.flag || m.extra.relax_one) && m.age.is_multiple_of(5) { + let volume = 0.6 + 0.4 * (m.random.next_float() - m.random.next_float()); + events.push(MobEvent::Sound("entity.cat.purr", m.center(), volume, 1.0)); + } +} +/// The lying and relaxing amounts of `Cat.tick` (also a client's, from the +/// synched flags). +pub fn cat_amounts(m: &mut Mob) { let lying = m.extra.flag; let relaxing = m.extra.relax_one; let v = &mut m.anim.v; @@ -1142,10 +1161,6 @@ pub fn cat_ai_step(m: &mut Mob, events: &mut Vec) { } else { (v[RELAX] - 0.13).max(0.0) }; - if (lying || relaxing) && m.age.is_multiple_of(5) { - let volume = 0.6 + 0.4 * (m.random.next_float() - m.random.next_float()); - events.push(MobEvent::Sound("entity.cat.purr", m.center(), volume, 1.0)); - } } /// `Cat.finalizeSpawn` variant: any but all-black, which a full moon allows. pub fn cat_variant(m: &mut Mob, w_moon_full: bool) -> u8 { From 4b4361fbc052751a5118192b312d857b4607c5c4 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:48:20 +0100 Subject: [PATCH 111/221] Clear a piglin's hoglin target once it dies or disappears --- crates/horizon-client/src/mobs/piglin.rs | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index 5b8c17fb3..0644b40e6 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -331,8 +331,18 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.species() == Species::Hoglin && m.alive() { hoglin_repellent(m, w); } - if m.species() == Species::Piglin && m.extra.ints[0] > 0 { - m.extra.ints[0] -= 1; + if m.species() == Species::Piglin { + if m.extra.ints[0] > 0 { + m.extra.ints[0] -= 1; + } + // `StopAttackingIfTargetInvalid`: a hoglin handed over by a hunt + // broadcast has no target goal of its own to drop it when it dies. + if let Some(who @ Who::Mob(_)) = m.ai.target + && w.target_info(who) + .is_none_or(|t| !t.alive || !t.can_be_seen_as_enemy) + { + m.ai.target = None; + } } if m.extra.anger > 0 { m.extra.anger -= 1; From e9797d69d0ea0b5ee0b75c68a9b483cdbf13f364 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 21:51:25 +0100 Subject: [PATCH 112/221] Use the berry damage type for sweet berry bushes and check the whole move for contact --- .../horizon-client/src/game/commands/world_cmds.rs | 3 ++- crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/mobs.rs | 9 ++++++++- crates/horizon-client/src/mobs/ai.rs | 14 ++++++++++---- crates/horizon-client/src/mobs/sulfur_cube.rs | 1 + 5 files changed, 22 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 687eb3f88..859d86397 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -117,7 +117,8 @@ impl Game<'_> { "drown" => DamageKind::Drown, "magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic, "sting" => DamageKind::Sting, - "cactus" | "sweet_berry_bush" => DamageKind::Cactus, + "cactus" => DamageKind::Cactus, + "sweet_berry_bush" => DamageKind::SweetBerryBush, "in_wall" => DamageKind::InWall, "thorns" => DamageKind::Thorns, _ => DamageKind::Generic, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2b65a3289..04228a722 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3283,6 +3283,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) K::Magic => "minecraft:magic", K::Sting => "minecraft:sting", K::Cactus => "minecraft:cactus", + K::SweetBerryBush => "minecraft:sweet_berry_bush", K::Generic => "minecraft:generic", K::InWall => "minecraft:in_wall", K::Thorns => "minecraft:thorns", diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 0edcd3620..4498e9b75 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -518,6 +518,8 @@ pub enum DamageKind { Magic, Sting, Cactus, + /// `sweet_berry_bush`. + SweetBerryBush, Generic, InWall, Thorns, @@ -573,7 +575,11 @@ impl Damage { pub fn causes_panic(&self) -> bool { !matches!( self.kind, - DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall + DamageKind::Fall + | DamageKind::Drown + | DamageKind::Generic + | DamageKind::InWall + | DamageKind::SweetBerryBush ) } /// DamageTypeTags.BYPASSES_ARMOR @@ -608,6 +614,7 @@ impl Damage { | DamageKind::Drown | DamageKind::Magic | DamageKind::Cactus + | DamageKind::SweetBerryBush | DamageKind::Generic | DamageKind::InWall | DamageKind::OutOfWorld diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index ffc74d0b9..458ccd097 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -433,14 +433,20 @@ pub fn tick( /// that hurt or hold a mob: the cactus (`CactusBlock.entityInside`, 1) and the /// sweet berry bush (`SweetBerryBushBlock.entityInside`: stuck at 0.8, 0.75, /// 0.8, and a grown bush pricks for 1 when the mob moved at least 0.003 on X -/// or Z this tick). The blocks are those the mob's box touches where it -/// started the tick and where it ended. +/// or Z this tick). The blocks are those the mob's box touches anywhere along +/// its move this tick, from where it started to where it ended. fn effects_from_blocks(m: &mut Mob, w: &MobWorld) { let mut visited: Vec<[i32; 3]> = Vec::new(); - for at in [m.previous, m.position] { + let travel = m.position.subtract(m.previous); + let longest = travel.x.abs().max(travel.y.abs()).max(travel.z.abs()); + let steps = ((longest / 0.2).ceil() as i32).clamp(1, 100); + for step in 0..=steps { if !m.alive() { return; } + let at = m + .previous + .add_vector(travel.scale(f64::from(step) / f64::from(steps))); let b = m.bounds_at(at).deflate(Vec3::new(1e-5, 1e-5, 1e-5)); for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 { for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 { @@ -465,7 +471,7 @@ fn effects_from_blocks(m: &mut Mob, w: &MobWorld) { && (moved.x.abs() >= f64::from(0.003_f32) || moved.z.abs() >= f64::from(0.003_f32)) { - m.damage(1.0, Damage::of(DamageKind::Cactus)); + m.damage(1.0, Damage::of(DamageKind::SweetBerryBush)); } } _ => continue, diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index 00b846b86..5a5c2f48a 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -297,6 +297,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool { | DamageKind::Fall | DamageKind::Sting | DamageKind::Cactus + | DamageKind::SweetBerryBush ); if immune { if let Some(from) = source.from { From 024415e09dff8438725dfb68dd5fe78bb691ea91 Mon Sep 17 00:00:00 2001 From: masa-masa-0314 <348336850+masa-masa-0314@users.noreply.github.com> Date: Tue, 27 Oct 2026 05:11:35 +0800 Subject: [PATCH 113/221] Inventory: animate every animated block and item sprite The shared atlas packs animated block and item textures as their first frame, and only fire re-drew itself: an animated block held or previewed in the GUI (sculk, magma) sat still, while the same block animated in the world. The atlas now keeps every animated block or item sprite's frame list and re-uploads the current frame into its rect as the animation ticks, with the mcmeta's interpolation mixing the frame into the next one the way the world's sprite arrays already do, so GUI items animate like vanilla's stitched atlas. Co-Authored-By: ZCode --- crates/horizon-client/src/game.rs | 12 ++-- crates/horizon-client/src/gfx.rs | 2 +- crates/horizon-client/src/hud.rs | 114 +++++++++++++++++++----------- 3 files changed, 78 insertions(+), 50 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f9edd98bb..e93911e65 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -13505,10 +13505,10 @@ fn build_renderer( previous, api, ))?; - renderer.hud.fire_animations = atlas - .fire_animations + renderer.hud.sprite_animations = atlas + .sprite_animations .iter() - .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0))) .collect(); Ok(renderer) } @@ -13558,10 +13558,10 @@ fn loading_renderer( api, ))?; if let Some(atlas) = atlas { - renderer.hud.fire_animations = atlas - .fire_animations + renderer.hud.sprite_animations = atlas + .sprite_animations .iter() - .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .map(|(rect, animation)| (*rect, animation.clone(), (usize::MAX, 0, 0))) .collect(); } Ok(renderer) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 70d882a98..74c544168 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -3390,7 +3390,7 @@ impl Renderer { if self.animated_textures { self.animate(&mut encoder, frame.ticks); self.hud - .animate_fire(&mut self.uploads, &mut encoder, frame.ticks); + .animate_sprites(&mut self.uploads, &mut encoder, frame.ticks); } self.update_lightmap( &mut encoder, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 2b6acda41..d2bef127e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -64,7 +64,10 @@ pub struct HudAtlas { /// Sprites whose `.png.mcmeta` sets `blur` or `clamp`; the others /// sample as vanilla's defaults (nearest, repeat). pub flags: HashMap, - pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, + /// Every animated block or item sprite the atlas packs: its atlas rect + /// and the mcmeta-driven frame list, re-uploaded into the rect as the + /// frames turn (vanilla's stitched atlas animates all of these). + pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation)>, /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). pub font: crate::font::Font, white: Rect, @@ -373,7 +376,7 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - type Decoded = (PackedImage, Option, Option<(u32, u32)>); + type Decoded = (PackedImage, Option, Option<(u32, u32)>, bool); let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) @@ -396,14 +399,20 @@ impl HudAtlas { .and_then(|d| png_size(&d.join(format!("{name}.png")))) .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) .filter(|&size| size != (w, h)); - let flags = fs::read_to_string(path.with_extension("png.mcmeta")) - .ok() - .and_then(|json| TextureFlags::from_mcmeta(&json)); + let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); + let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta); + let animated = frames + && mcmeta.as_deref().is_some_and(|json| { + serde_json::from_str::(json) + .ok() + .is_some_and(|meta| meta.get("animation").is_some()) + }); let (gw, gh) = gui_size.unwrap_or((w, h)); (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( (name, w, h, pixels), flags, gui_size, + animated, )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); @@ -422,14 +431,18 @@ impl HudAtlas { }); let mut flags = HashMap::new(); let mut gui_sizes = HashMap::new(); + let mut animated: Vec = Vec::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags, gui_size) in decoded { + for (image, image_flags, gui_size, is_animated) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } if let Some(size) = gui_size { gui_sizes.insert(image.0.clone(), size); } + if is_animated { + animated.push(image.0.clone()); + } images.push(image); } if full { @@ -495,35 +508,32 @@ impl HudAtlas { }, ); } - let mut fire_sprites = crate::sprites::Sprites::default(); - let mut fire_animations = Vec::new(); - for name in [ - "block/fire_0", - "block/fire_1", - "block/soul_fire_0", - "block/soul_fire_1", - ] { - if let Some(rect) = sprites.get(name).copied() { - let layer = fire_sprites.insert(root, &format!("minecraft:{name}"))?; - if let Some(animation) = fire_sprites - .animations - .iter() - .find(|a| a.layer == layer) - .cloned() - { - let (tw, th) = rect.texels((width, height)); - let image = animation.resized_pixels(animation.frame(0), tw, th); - let x = (rect.u0 * width as f32).round() as usize; - let y = (rect.v0 * height as f32).round() as usize; - let row_bytes = tw as usize * 4; - for row in 0..th as usize { - let dst = ((y + row) * width as usize + x) * 4; - let src = row * row_bytes; - pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); - } - fire_animations.push((rect, animation)); - } + // Every animated sprite animates: the packed strip is the raw first + // frame, while the mcmeta's frame list may start anywhere, so each + // animation's frame(0) overwrites its atlas rect before drawing. + let mut loaded = crate::sprites::Sprites::default(); + let mut sprite_animations = Vec::new(); + animated.sort(); + for name in animated { + let Some(rect) = sprites.get(&name).copied() else { + continue; + }; + let layer = loaded.insert(root, &format!("minecraft:{name}"))?; + let Some(animation) = loaded.animations.iter().find(|a| a.layer == layer).cloned() + else { + continue; + }; + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); + let x = (rect.u0 * width as f32).round() as usize; + let y = (rect.v0 * height as f32).round() as usize; + let row_bytes = tw as usize * 4; + for row in 0..th as usize { + let dst = ((y + row) * width as usize + x) * 4; + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } + sprite_animations.push((rect, animation)); } let white = sprites["horizon/white"]; let font = crate::font::Font::load( @@ -541,7 +551,7 @@ impl HudAtlas { sprites, translucent, flags, - fire_animations, + sprite_animations, font, white, }) @@ -1033,7 +1043,7 @@ impl HudUniform { } } pub struct HudRenderer { - pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>, + pub sprite_animations: Vec<(Rect, crate::sprites::SpriteAnimation, (usize, usize, u32))>, /// The shared atlas texture, for run-time glyph uploads. pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, @@ -1235,7 +1245,7 @@ impl HudRenderer { }); Ok(Self { atlas_texture: None, - fire_animations: Vec::new(), + sprite_animations: Vec::new(), pipeline, invert_pipeline, additive_pipeline, @@ -1248,7 +1258,7 @@ impl HudRenderer { capacity, }) } - pub fn animate_fire( + pub fn animate_sprites( &mut self, uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, @@ -1257,13 +1267,31 @@ impl HudRenderer { let Some(texture) = &self.atlas_texture else { return; }; - for (rect, animation, previous) in &mut self.fire_animations { - let frame = animation.frame(tick); - if frame == *previous { + for (rect, animation, previous) in &mut self.sprite_animations { + // `SpriteContents.AnimationState`: the frame from the mcmeta's + // list, blended into the next one by the sub-frame's thousandths + // when the sprite interpolates. + let blend = animation.blend(tick); + let state = (blend.frame, blend.next, blend.millis); + if state == *previous { continue; } let (w, h) = rect.texels((texture.width(), texture.height())); - let pixels = animation.resized_pixels(frame, w, h); + let pixels = if blend.millis == 0 { + animation.resized_pixels(blend.frame, w, h) + } else { + let current = animation.resized_pixels(blend.frame, w, h); + let next = animation.resized_pixels(blend.next, w, h); + let millis = blend.millis; + current + .iter() + .zip(next) + .map(|(&a, b)| { + ((u32::from(a) * (1000 - millis) + u32::from(b) * millis + 500) / 1000) + as u8 + }) + .collect() + }; uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1280,7 +1308,7 @@ impl HudRenderer { h, &pixels, ); - *previous = frame; + *previous = state; } } /// Stage the batch's atlas patches, vertices and uniform: before the From 25c53cc80330575cf822d2718ca9a0c4afbc3587 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:56:31 +0100 Subject: [PATCH 114/221] Server-thread clients animate ravager, hoglin, iron golem, creaking, vex, allay, axolotl, guardian, copper golem and strider Builds on the warden, sniffer, breeze, camel and shulker sync. Each of these mobs now sends its synched data and entity events, and the client runs the animation steps vanilla runs on the client. --- crates/horizon-client/src/game/lan.rs | 60 ++++++++++++++++ crates/horizon-client/src/game/remote.rs | 38 ++++++++++ .../src/game/remote_mob_data.rs | 21 +++++- crates/horizon-client/src/mobs/allay.rs | 5 ++ .../horizon-client/src/mobs/copper_golem.rs | 14 +++- crates/horizon-client/src/mobs/creaking.rs | 70 +++++++++++++------ crates/horizon-client/src/mobs/golem.rs | 34 ++++++++- crates/horizon-client/src/mobs/guardian.rs | 46 +++++++----- crates/horizon-client/src/mobs/piglin.rs | 19 +++++ crates/horizon-client/src/mobs/ravager.rs | 41 ++++++++++- crates/horizon-client/src/mobs/sync.rs | 33 +++++++-- 11 files changed, 334 insertions(+), 47 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6e00df8fe..bab38a334 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -399,6 +399,66 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(16))); } + // Vex.DATA_FLAGS_ID: charging in bit 0 (the arms and the glowing + // texture). + "minecraft:vex" => { + if e.flag { + meta.push((16, serializer::BYTE, Value::Byte(1))); + } + defaults.push((16, serializer::BYTE, Value::Byte(0))); + } + // Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN. + "minecraft:creaking" => { + if e.flag2 { + meta.push((16, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(true))); + if e.flag { + meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); + if horizon_client::mobs::creaking::tearing_down(m) { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } + // Allay.DATA_DANCING and DATA_CAN_DUPLICATE (the held item is its + // main hand equipment). + "minecraft:allay" => { + if e.flag { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + if e.egg_time > 0 { + meta.push((17, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + // Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT). + "minecraft:axolotl" => { + if horizon_client::mobs::axolotl::is_playing_dead(m) { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } + // CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE). + "minecraft:copper_golem" => { + if e.variant3 != 0 { + meta.push(( + 17, + serializer::COPPER_GOLEM_STATE, + Value::Id(i32::from(e.variant3)), + )); + } + defaults.push((17, serializer::COPPER_GOLEM_STATE, Value::Id(0))); + } + // Strider.DATA_SUFFOCATING (after DATA_BOOST_TIME): the shiver. + "minecraft:strider" => { + if e.flag { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5994af375..24401e68c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3182,6 +3182,7 @@ impl Game<'_> { self.border.tick(); self.player_border(); self.tick_remote_entities(running); + self.tick_remote_guardian_eyes(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells, // and the moving pistons a block event's client-side moveBlocks made // (their progress advances between the server's block updates). @@ -3464,6 +3465,43 @@ impl Game<'_> { } /// ClientLevel.tickEntities; a frozen level only ticks the players /// (`TickRateManager.isEntityFrozen`). + /// `GuardianRenderer.getEntityToLookAt`: a guardian's eye follows its + /// synched attack target, else the camera. + fn tick_remote_guardian_eyes(&mut self, running: bool) { + use horizon_client::mobs::{Species, Who, guardian}; + if !running { + return; + } + let camera = self.player.as_ref().map(|p| { + [ + p.position.x, + p.position.y + f64::from(p.dimensions.eye_height), + p.position.z, + ] + }); + let looks: Vec<_> = self + .mobs + .iter() + .enumerate() + .filter(|(_, m)| { + matches!(m.species(), Species::Guardian | Species::ElderGuardian) && m.alive() + }) + .filter_map(|(i, m)| { + let look = match m.ai.target.filter(|_| m.extra.flag) { + Some(Who::Mob(id)) => self + .mobs + .iter() + .find(|t| t.id == id) + .map(|t| [t.position.x, t.eye_y(), t.position.z]), + _ => camera, + }; + look.map(|look| (i, look)) + }) + .collect(); + for (i, look) in looks { + guardian::look_at(&mut self.mobs[i], look); + } + } fn tick_remote_entities(&mut self, running: bool) { if running { self.tick_text_displays(); diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index bd452ba85..ca54d52f4 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,7 +4,7 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, camel, sniffer, sync, tame}; +use horizon_client::mobs::{Mob, Species, Who, bat, camel, creaking, sniffer, sync, tame}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; @@ -104,6 +104,25 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Camel | Species::CamelHusk, 20, Value::Long(tick)) => { camel::set_synced_pose_tick(m, *tick); } + // Vex.DATA_FLAGS_ID: charging in bit 0. + (Species::Vex, 16, Value::Byte(flags)) => m.extra.flag = flags & 1 != 0, + // Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN. + (Species::Creaking, 16, Value::Bool(can_move)) => m.extra.flag2 = !*can_move, + (Species::Creaking, 17, Value::Bool(active)) => m.extra.flag = *active, + (Species::Creaking, 18, Value::Bool(true)) => creaking::set_tearing_down(m), + // Allay.DATA_DANCING and DATA_CAN_DUPLICATE (a cooldown running + // is any non-zero `egg_time`). + (Species::Allay, 16, Value::Bool(dancing)) => m.extra.flag = *dancing, + (Species::Allay, 17, Value::Bool(can)) => m.extra.egg_time = i32::from(!*can), + // Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT): the factors + // ease in `sync::client_tick`. + (Species::Axolotl, 19, Value::Bool(dead)) => m.extra.axolotl.playing_dead = *dead, + // CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE). + (Species::CopperGolem, 17, Value::Id(state)) => { + m.extra.variant3 = (*state).clamp(0, 4) as u8; + } + // Strider.DATA_SUFFOCATING (after DATA_BOOST_TIME). + (Species::Strider, 19, Value::Bool(cold)) => m.extra.flag = *cold, // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, diff --git a/crates/horizon-client/src/mobs/allay.rs b/crates/horizon-client/src/mobs/allay.rs index 029ddb6e5..22461945d 100644 --- a/crates/horizon-client/src/mobs/allay.rs +++ b/crates/horizon-client/src/mobs/allay.rs @@ -133,6 +133,11 @@ pub fn ai_step(m: &mut Mob) { if m.extra.egg_time > 0 { m.extra.egg_time -= 1; } + animate(m); +} +/// `Allay.tick`'s client half: the hold and spin clocks (the server's and a +/// client's). +pub fn animate(m: &mut Mob) { let holding = m.extra.main_hand.is_some(); let v = &mut m.anim.v; v[HOLD] = (v[HOLD] + if holding { 1.0 } else { -1.0 }).clamp(0.0, 5.0); diff --git a/crates/horizon-client/src/mobs/copper_golem.rs b/crates/horizon-client/src/mobs/copper_golem.rs index 5f4ffba13..c5e0dbece 100644 --- a/crates/horizon-client/src/mobs/copper_golem.rs +++ b/crates/horizon-client/src/mobs/copper_golem.rs @@ -70,6 +70,16 @@ pub fn sound(m: &Mob, what: &str) -> &'static str { } /// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin. pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { + if animate(m) { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); + } +} +/// `CopperGolem.setupAnimationStates`, for the server and a client alike; +/// returns whether the head spin sound plays now (a client's sound is the +/// server's `LocalSound`). +pub fn animate(m: &mut Mob) -> bool { + let mut spin = false; let age = m.age as f32; let state = m.extra.variant3; let st = &mut m.anim.states; @@ -93,8 +103,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { m.extra.ints[0] = tick + 200 + r.next_int_bound(40).unwrap_or(0); } if tick == m.extra.ints[0] + 10 { - let at = [m.position.x, m.position.y, m.position.z]; - events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0)); + spin = true; m.extra.ints[0] = 0; } } @@ -106,6 +115,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec) { } _ => {} } + spin } /// `CopperGolem.updateWeathering` on the level random: the first tick sets /// the next weathering tick, which advances the weather state; once diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs index fd6248d2b..e23cd817c 100644 --- a/crates/horizon-client/src/mobs/creaking.rs +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -152,8 +152,26 @@ pub fn sway(m: &mut Mob, events: &mut Vec) { } /// `Creaking.doHurtTarget`: the attack animation (the sound is the /// `playAttackSound` that ends `Mob.doHurtTarget`). -pub fn on_attack(m: &mut Mob, _events: &mut Vec) { +pub fn on_attack(m: &mut Mob, events: &mut Vec) { m.extra.ints[ATTACKING] = ATTACK_TICKS; + broadcast(m, 4, events); +} +/// `Level.broadcastEntityEvent` for a creaking (guests run `entity_event`). +fn broadcast(m: &Mob, event: i8, events: &mut Vec) { + events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at: [m.position.x, m.position.y, m.position.z], + }); +} +/// `Creaking.handleEntityEvent` on a client: 66 the invulnerability flash, +/// 4 the attack swing (the sounds are the server's). +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 66 => m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS, + 4 => m.extra.ints[ATTACKING] = ATTACK_TICKS, + _ => {} + } } /// The heart this creaking is bound to protects it (`isProtector`); a link /// read from a save is trusted until the heart resolves it. @@ -176,15 +194,12 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if heart_bound(m) && m.alive() && !protected(m, w) { m.health = 0.0; } - for slot in [INVULNERABLE, ATTACKING] { - if m.extra.ints[slot] > 0 { - m.extra.ints[slot] -= 1; - } + // hurtServer set the invulnerability clock since the last tick: entity + // event 66. + if m.extra.ints[INVULNERABLE] == INVULNERABILITY_TICKS { + broadcast(m, 66, events); } - let age = m.age as f32; - m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); - m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); - m.anim.states[2].animate_when(tearing_down(m), age); + animate(m); if m.extra.counter & HURT != 0 { // hurtServer: sway, and the heart reacts to a player's hit. if protected(m, w) { @@ -200,18 +215,6 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } m.extra.counter &= !(HURT | HURT_BY_PLAYER); } - // checkEyeBlink: the eyes of a creaking falling apart flicker. - if m.death_time > m.extra.ints[NEXT_FLICKER] { - let glowing = m.extra.ints[EYES] != 0; - let (lo, hi) = if glowing { - (2, 8) - } else { - (m.death_time / 4, m.death_time / 2) - }; - let span = (hi - lo + 1).max(1); - m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); - m.extra.ints[EYES] = i32::from(!glowing); - } if !m.alive() { return; } @@ -226,6 +229,31 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.extra.flag2 = !now; } } +/// The clocks and keyframe states `Creaking.aiStep`, `setupAnimationStates` +/// and `checkEyeBlink` run (the server's and a client's). +pub fn animate(m: &mut Mob) { + for slot in [INVULNERABLE, ATTACKING] { + if m.extra.ints[slot] > 0 { + m.extra.ints[slot] -= 1; + } + } + let age = m.age as f32; + m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age); + m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age); + m.anim.states[2].animate_when(tearing_down(m), age); + // checkEyeBlink: the eyes of a creaking falling apart flicker. + if m.death_time > m.extra.ints[NEXT_FLICKER] { + let glowing = m.extra.ints[EYES] != 0; + let (lo, hi) = if glowing { + (2, 8) + } else { + (m.death_time / 4, m.death_time / 2) + }; + let span = (hi - lo + 1).max(1); + m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0); + m.extra.ints[EYES] = i32::from(!glowing); + } +} /// `Mob.stopInPlace`. pub fn stop_in_place(m: &mut Mob) { m.nav_stop(); diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index c41c34f11..ae73ef854 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -157,12 +157,16 @@ impl Goal for OfferFlower { fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { self.ticks > 0 } - fn start(&mut self, m: &mut Mob, _: &mut Cx) { + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { self.ticks = 400; m.extra.counter = 400; + // IronGolem.offerFlower(true): entity event 11. + entity_event(m, 11, cx); } fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { m.extra.counter = 0; + // IronGolem.offerFlower(false): entity event 34. + entity_event(m, 34, cx); // A copper golem the offer ran out beside takes the poppy on its // antenna (#accepts_iron_golem_gift) when it has none. if self.ticks == 0 @@ -198,6 +202,7 @@ impl Goal for OfferFlower { /// the target is thrown upward. pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { m.extra.anim_ticks = 10; + entity_event(m, 4, cx); let attack = m.attrs.attack_damage; let amount = if attack as i32 > 0 { attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32 @@ -224,6 +229,33 @@ pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { 1.0, )); } +/// `Level.broadcastEntityEvent` for an iron golem (guests run `client_event`). +fn entity_event(m: &Mob, event: i8, cx: &mut Cx) { + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at: [m.position.x, m.position.y, m.position.z], + }); +} +/// `IronGolem.handleEntityEvent` on a client: 4 the swing, 11 and 34 the +/// poppy offer starting and stopping. +pub fn client_event(m: &mut Mob, event: u8) { + match event { + 4 => m.extra.anim_ticks = 10, + 11 => m.extra.counter = 400, + 34 => m.extra.counter = 0, + _ => {} + } +} +/// The swing and offer clocks of `IronGolem.aiStep` on a client. +pub fn client_tick(m: &mut Mob) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + if m.extra.counter > 0 { + m.extra.counter -= 1; + } +} /// `IronGolem.aiStep` timers and anger. pub fn iron_ai_step(m: &mut Mob) { if m.extra.anim_ticks > 0 { diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 880655361..029dc7af4 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -214,12 +214,9 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec } true } -/// `Guardian.aiStep`: the client animations, air, flopping on land, the -/// beam's clock, and the spikes' thorns. -pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { - if !m.alive() { - return; - } +/// `Guardian.aiStep`'s `clientSideTailAnimation` and +/// `clientSideSpikesAnimation` (the server's and a client's). +pub fn tail_and_spikes(m: &mut Mob) { let moving = m.extra.flag2; let in_water = m.fluids.in_water; // Tail and spikes (clientSideTailAnimation / clientSideSpikesAnimation). @@ -244,6 +241,16 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } else { a.v[SPIKES] += (1.0 - a.v[SPIKES]) * 0.06; } +} +/// `Guardian.aiStep`: the client animations, air, flopping on land, the +/// beam's clock, and the spikes' thorns. +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if !m.alive() { + return; + } + let moving = m.extra.flag2; + let in_water = m.fluids.in_water; + tail_and_spikes(m); client_tick(m); if in_water { m.air = 300; @@ -276,17 +283,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { None => w.player.as_ref().map(|p| p.eye), }; if let Some(look) = look { - m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; - let yaw = m.head_yaw.to_radians(); - let pitch = m.head_pitch.to_radians(); - let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; - let d = [m.position.x - look[0], m.position.z - look[2]]; - let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); - let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); - // Vec3.yRot(pi / 2) of the direction from the target. - let side = [dz, -dx]; - let dot = view[0] * side[0] + view[1] * side[1]; - m.anim.v[EYE_X] = dot.abs().sqrt() * 2.0 * dot.signum(); + look_at(m, look); } // Guardian.hurtServer: a still guardian's spikes hurt a melee attacker. if m.hurt_time == 10 @@ -317,6 +314,21 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } } +/// `GuardianModel.setupAnim`'s eye: it follows `look` (the attack target's +/// eye, else the camera's), from where the guardian faces. +pub fn look_at(m: &mut Mob, look: [f64; 3]) { + m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 }; + let yaw = m.head_yaw.to_radians(); + let pitch = m.head_pitch.to_radians(); + let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()]; + let d = [m.position.x - look[0], m.position.z - look[2]]; + let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9); + let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32); + // Vec3.yRot(pi / 2) of the direction from the target. + let side = [dz, -dx]; + let dot = view[0] * side[0] + view[1] * side[1]; + m.anim.v[EYE_X] = dot.abs().sqrt() * 2.0 * dot.signum(); +} /// `ElderGuardian.customServerAiStep`: every minute, mining fatigue III for /// players within 50 blocks; a home within 16 blocks. pub fn elder_server_ai_step(m: &mut Mob, cx: &mut Cx) { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index de9ba42dd..393920fd9 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -378,6 +378,12 @@ fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { /// `HoglinBase.hurtAndThrowTarget`. pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { m.extra.anim_ticks = 10; + // Entity event 4: clients start the headbutt. + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: [m.position.x, m.position.y, m.position.z], + }); let attack = m.attrs.attack_damage; let amount = if !m.is_baby() && attack as i32 > 0 { attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32 @@ -499,6 +505,19 @@ pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, _ => {} } } +/// `Hoglin.handleEntityEvent` and `Zoglin`'s event 4 on a client: the +/// headbutt, which `aiStep` then counts down. +pub fn client_event(m: &mut Mob, event: u8) { + if event == 4 { + m.extra.anim_ticks = 10; + } +} +/// The headbutt's countdown (`Hoglin.aiStep`, `Zoglin.aiStep`) on a client. +pub fn client_tick(m: &mut Mob) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } +} /// `HoglinModel.setupAnim`. pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) { let (pos, sp) = (s.pos, s.speed); diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 49bac4d9f..4c179aeda 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -49,9 +49,14 @@ pub fn register(m: &mut Mob) { pub fn immobile(m: &Mob) -> bool { m.extra.counter > 0 || m.extra.counter2 > 0 || m.extra.anim_ticks > 0 } -/// `Ravager.doHurtTarget`: the bite animation. +/// `Ravager.doHurtTarget`: the bite animation (entity event 4 for clients). pub fn on_attack(m: &mut Mob, events: &mut Vec) { m.extra.counter = 10; + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: [m.position.x, m.position.y, m.position.z], + }); events.push(MobEvent::Sound( "entity.ravager.attack", [m.position.x, m.position.y, m.position.z], @@ -67,6 +72,12 @@ pub fn blocked(m: &mut Mob, events: &mut Vec) -> bool { } if m.random.next_double() < 0.5 { m.extra.counter2 = 40; + // Entity event 39: the stun starts on clients. + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 39, + at: [m.position.x, m.position.y, m.position.z], + }); events.push(MobEvent::Sound( "entity.ravager.stunned", [m.position.x, m.position.y, m.position.z], @@ -155,6 +166,34 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } } +/// `Ravager.handleEntityEvent` 4 and 39 on a client. +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 4 => m.extra.counter = 10, + 39 => m.extra.counter2 = 40, + _ => {} + } +} +/// `Ravager.aiStep`'s clocks on a client: the bite and roar run down, and +/// the end of the stun starts the roar (the sounds, particles and the roar's +/// damage are the server's). +pub fn client_tick(m: &mut Mob) { + if !m.alive() { + return; + } + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + if m.extra.counter > 0 { + m.extra.counter -= 1; + } + if m.extra.counter2 > 0 { + m.extra.counter2 -= 1; + if m.extra.counter2 == 0 { + m.extra.anim_ticks = 20; + } + } +} /// `Ravager.roar`: 6 damage to everything but illagers within 4 blocks, /// and a strong knockback (players too, through the client). fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs index d1c5b6609..2b3b75b44 100644 --- a/crates/horizon-client/src/mobs/sync.rs +++ b/crates/horizon-client/src/mobs/sync.rs @@ -15,7 +15,10 @@ //! them in `entity_event`; //! - run its client side animation in `client_tick`, sharing the function //! with the server's `ai_step` where the server computes the same. -use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; +use super::{ + Mob, Species, allay, axolotl, breeze, camel, copper_golem, creaking, golem, guardian, piglin, + ravager, shulker, sniffer, warden, +}; // `Pose.id` of the poses mobs take. pub const STANDING: u8 = 0; @@ -60,6 +63,23 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { Species::Breeze => breeze::ai_step(m), Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), Species::Shulker => shulker::client_tick(m), + Species::Ravager => ravager::client_tick(m), + Species::Hoglin | Species::Zoglin => piglin::client_tick(m), + Species::IronGolem => golem::client_tick(m), + Species::Creaking => creaking::animate(m), + Species::Allay => { + m.anim.vo = m.anim.v; + allay::animate(m); + } + Species::Axolotl => axolotl::tick_animation(m), + Species::Guardian | Species::ElderGuardian => { + m.anim.vo = m.anim.v; + guardian::tail_and_spikes(m); + } + // The head spin's sound is the server's. + Species::CopperGolem if !m.no_ai => { + copper_golem::animate(m); + } _ => {} } } @@ -68,8 +88,8 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { /// (`ClientboundEntityEventPacket` for a mob of a client). pub fn entity_event(m: &mut Mob, event: u8) { let age = m.age as f32; - if m.species() == Species::Warden { - match event { + match m.species() { + Species::Warden => match event { // Attack: the roar ends, the swing starts. 4 => { m.anim.states[warden::ROAR].stop(); @@ -80,6 +100,11 @@ pub fn entity_event(m: &mut Mob, event: u8) { // The sonic boom. 62 => m.anim.states[warden::SONIC_BOOM].start(age), _ => {} - } + }, + Species::Ravager => ravager::entity_event(m, event), + Species::Hoglin | Species::Zoglin => piglin::client_event(m, event), + Species::IronGolem => golem::client_event(m, event), + Species::Creaking => creaking::entity_event(m, event), + _ => {} } } From 11e1ff12d0c516f3300c7919babfd4f66fc15131 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 22:59:54 +0100 Subject: [PATCH 115/221] Let armadillos roll up when scared, peek out and take less damage as a ball --- .../examples/probe/mob_ai_probe.rs | 2 + crates/horizon-client/src/game/creatures.rs | 2 + crates/horizon-client/src/game/lan.rs | 8 + crates/horizon-client/src/game/lan_mobs.rs | 2 + .../src/game/remote_mob_data.rs | 7 +- crates/horizon-client/src/mobs.rs | 9 + crates/horizon-client/src/mobs/ai.rs | 14 +- crates/horizon-client/src/mobs/armadillo.rs | 407 ++++++++++++++++++ crates/horizon-client/src/mobs/body_anim.rs | 2 +- crates/horizon-client/src/mobs/goals.rs | 12 +- crates/horizon-client/src/mobs/keyframes.rs | 6 + crates/horizon-client/src/mobs/sync.rs | 6 +- 12 files changed, 472 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/mobs/armadillo.rs diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 5b6c26d2f..8e005e235 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1056,6 +1056,8 @@ pub fn main() -> horizon_client::Result<()> { last_hurt: None, velocity: Vec3::ZERO, yaw: 0.0, + sprinting: false, + riding: false, hero: false, effects: Vec::new(), uuid: PLAYER_UUID, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0ea8dd4d0..9d7fc3cc6 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -192,6 +192,8 @@ impl Game<'_> { last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)), velocity: p.velocity, yaw: self.yaw, + sprinting: p.sprinting, + riding: self.riding.is_some(), hero: self.potions.effects.get("hero_of_the_village").is_some(), effects: self.potions.effects.list.iter().map(|e| e.id).collect(), uuid: self.level.player_uuid.unwrap_or_default(), diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6e00df8fe..baf8089cb 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -399,6 +399,14 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(16))); } + // Armadillo.ARMADILLO_STATE (after AgeableMob's two). + "minecraft:armadillo" => { + let state = horizon_client::mobs::armadillo::state(m); + if state != 0 { + meta.push((18, serializer::ARMADILLO_STATE, Value::Id(i32::from(state)))); + } + defaults.push((18, serializer::ARMADILLO_STATE, Value::Id(0))); + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 6527f1015..a4880d18a 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -369,6 +369,8 @@ mod tests { last_hurt: None, velocity: Vec3::ZERO, yaw: 0.0, + sprinting: false, + riding: false, hero: false, effects: Vec::new(), uuid: [0; 4], diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index bd452ba85..341b97905 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,7 +4,7 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, camel, sniffer, sync, tame}; +use horizon_client::mobs::{Mob, Species, Who, armadillo, bat, camel, sniffer, sync, tame}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; @@ -92,6 +92,11 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Sniffer, 18, Value::Id(state)) => { sniffer::set_state(m, (*state).clamp(0, 6) as u8); } + // Armadillo.ARMADILLO_STATE (after AgeableMob's two): the shell and + // its animations follow it in `sync::client_tick`. + (Species::Armadillo, 18, Value::Id(state)) => { + armadillo::set_state(m, (*state).clamp(0, 3) as u8); + } // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID. (Species::Shulker, 16, Value::Id(face)) => m.extra.variant3 = (*face).clamp(0, 5) as u8, (Species::Shulker, 17, Value::Byte(peek)) => m.extra.counter = i32::from(*peek), diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3daeeb10a..b5a7dbf9a 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -11,6 +11,7 @@ pub mod ambient; pub mod anim; pub mod animal_brain; pub mod aquatic; +pub mod armadillo; pub mod axolotl; pub mod bat; pub mod bee; @@ -786,6 +787,8 @@ pub struct Extra { pub brain: Option>, /// A bee's nectar, anger, flower and hive state. pub bee: Option>, + /// An armadillo's state and scare brain. + pub armadillo: armadillo::State, } #[derive(Clone, Debug)] pub struct Mob { @@ -1545,6 +1548,9 @@ pub struct PlayerView { pub last_hurt: Option<(Who, i64)>, pub velocity: Vec3, pub yaw: f32, + /// `Player.isSprinting` and `isPassenger` (what scares an armadillo). + pub sprinting: bool, + pub riding: bool, /// The Hero of the Village effect. pub hero: bool, /// The active effects, without namespace (`slowness`, `poison`...). @@ -1811,6 +1817,9 @@ impl Mob { return false; } let mut amount = if reflected { 1000.0 } else { amount }; + if self.species() == Species::Armadillo { + amount = armadillo::reduce_damage(self, amount); + } if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 258c1ccc7..63b0a8326 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -178,6 +178,7 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + Family::Generic if m.species() == Species::Armadillo => super::armadillo::register(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { @@ -408,7 +409,10 @@ pub fn tick( } // Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen // creaking's waits). - if m.alive() && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) { + if m.alive() + && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) + && !super::armadillo::scared(m) + { m.body_rotation_tick(); } events.append(&mut m.outbox); @@ -964,6 +968,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events), Species::Bee => super::bee::server_ai_step(m, cx), + Species::Armadillo => super::armadillo::server_ai_step(m, cx), _ => {} } } @@ -1016,6 +1021,7 @@ fn species_ai_step( } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Armadillo => super::armadillo::tick(m), Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; @@ -1126,6 +1132,7 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] { match m.species() { Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m), Species::SulfurCube => super::sulfur_cube::sounds(m), + Species::Armadillo => super::armadillo::sounds(m), // The sound variant's baby_sounds (classic sets, like the rest here). Species::Pig if m.is_baby() => [ "entity.baby_pig.ambient", @@ -1148,6 +1155,10 @@ pub fn feed_animal( m: &mut Mob, level: &mut impl RandomSource, ) -> Option> { + // Armadillo.mobInteract: a ball takes no food. + if super::armadillo::scared(m) { + return None; + } if m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; @@ -1338,6 +1349,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) { m.ai.no_action_time = 0; match m.species() { Species::Enderman => super::enderman::after_hurt(m, source), + Species::Armadillo => super::armadillo::after_hurt(m, source), Species::Shulker => super::shulker::after_hurt(m), Species::Warden => super::warden::hurt(m, source), Species::Wolf => super::tame::after_hurt(m, source), diff --git a/crates/horizon-client/src/mobs/armadillo.rs b/crates/horizon-client/src/mobs/armadillo.rs new file mode 100644 index 000000000..8837d8cf8 --- /dev/null +++ b/crates/horizon-client/src/mobs/armadillo.rs @@ -0,0 +1,407 @@ +//! Armadillos (`Armadillo`, `ArmadilloAi`): a player who sprints or rides +//! nearby, an undead mob or the last attacker scares one into a ball (IDLE, +//! ROLLING, SCARED, UNROLLING); it peeks out now and then, and a ball takes +//! less damage. The brain's `ARMADILLO_SCARE_DETECTED` sensor, its +//! `DANGER_DETECTED_RECENTLY` memory and the `ArmadilloBallUp` behaviour are +//! kept in `State`; the walking behaviours are the goals of `register`. +//! AnimState states: roll out, roll up, peek. +use super::{ + Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, + goals::{ + Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone, + }, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +pub const IDLE: u8 = 0; +pub const ROLLING: u8 = 1; +pub const SCARED: u8 = 2; +pub const UNROLLING: u8 = 3; + +const ROLL_OUT: usize = 0; +const ROLL_UP: usize = 1; +const PEEK: usize = 2; + +/// `ArmadilloState.animationDuration`. +fn animation_duration(state: u8) -> i32 { + match state { + ROLLING => 10, + SCARED => 50, + UNROLLING => 30, + _ => 0, + } +} + +/// `Armadillo.ARMADILLO_STATE` and the brain's memory and behaviour. +#[derive(Clone, Debug, Default)] +pub struct State { + pub state: u8, + /// `inStateTicks`. + pub in_state_ticks: i32, + /// `DANGER_DETECTED_RECENTLY`: ticks to live, 0 when absent. + danger: i32, + /// Ticks to the sensor's next scan. + sensor: i32, + /// `ArmadilloBallUp`: running, its peek timer and whether it saw the + /// danger around last tick. + ball_up: bool, + next_peek: i32, + danger_was_around: bool, + /// Whether the PANIC activity was the active one after the last tick. + panic_activity: bool, + /// `peekReceivedClient`. + peek_received: bool, +} + +pub fn register(m: &mut Mob) { + let mut panic = Panic::new(2.0); + panic.environmental = true; + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, ArmadilloPanic(panic)); + g.add(2, Rolled); + g.add(5, Stroll::avoiding_water(1.0)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); +} + +/// `Armadillo.isScared`. +pub fn scared(m: &Mob) -> bool { + m.extra.armadillo.state != IDLE +} +/// `ArmadilloState.shouldHideInShell`: the model shows its shell. +pub fn hiding_in_shell(m: &Mob) -> bool { + let a = &m.extra.armadillo; + match a.state { + ROLLING => a.in_state_ticks > 5, + SCARED => true, + UNROLLING => a.in_state_ticks < 26, + _ => false, + } +} +/// `Armadillo.getState`, as it is synched. +pub fn state(m: &Mob) -> u8 { + m.extra.armadillo.state +} +/// `Armadillo.switchToState` and `onSyncedDataUpdated(ARMADILLO_STATE)`. +pub fn set_state(m: &mut Mob, state: u8) { + let a = &mut m.extra.armadillo; + if a.state != state { + a.state = state; + a.in_state_ticks = 0; + } +} +/// `Armadillo.canStayRolledUp`. +fn can_stay_rolled_up(m: &Mob) -> bool { + !m.ai.panicking + && !m.fluids.in_water + && !m.fluids.in_lava + && m.extra.leash.is_none() + && m.extra.mount.is_none() + && m.extra.rider.is_none() +} +/// `Entity.playSound(sound)`. +fn play(m: &Mob, events: &mut Vec, sound: &'static str) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, 1.0, 1.0)); + } +} +/// `Armadillo.rollUp`. +fn roll_up(m: &mut Mob, events: &mut Vec) { + if !scared(m) { + super::creaking::stop_in_place(m); + m.extra.in_love = 0; + if !m.silent { + m.voice("entity.armadillo.roll", events); + } + set_state(m, ROLLING); + } +} +/// `Armadillo.rollOut`. +fn roll_out(m: &mut Mob, events: &mut Vec) { + if scared(m) { + if !m.silent { + m.voice("entity.armadillo.unroll_finish", events); + } + set_state(m, IDLE); + } +} + +/// `Armadillo.hurtServer`: a ball takes half of the damage past the first +/// point. +pub fn reduce_damage(m: &Mob, amount: f32) -> f32 { + if scared(m) { + ((amount - 1.0) / 2.0).max(0.0) + } else { + amount + } +} +/// `Armadillo.actuallyHurt`: a hit by a living thing curls it up (and keeps +/// the danger in mind for 80 ticks), a hit by fire and the like unrolls it. +pub fn after_hurt(m: &mut Mob, source: &Damage) { + if m.no_ai || m.health <= 0.0 { + return; + } + let mut events = Vec::new(); + if source.attacker.is_some() { + m.extra.armadillo.danger = 80; + if can_stay_rolled_up(m) { + roll_up(m, &mut events); + } + } else if environmental(source.kind) { + roll_out(m, &mut events); + } + m.outbox.append(&mut events); +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES`. +pub fn environmental(kind: DamageKind) -> bool { + matches!( + kind, + DamageKind::Cactus | DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava + ) +} +/// The hurt sound: a ball's is muffled, and it has no ambient sound +/// (`getAmbientSound`, `getHurtSound`); empty is none. +pub fn sounds(m: &Mob) -> [&'static str; 3] { + let [ambient, hurt, death] = m.kind.sounds; + if scared(m) { + ["", "entity.armadillo.hurt_reduced", death] + } else { + [ambient, hurt, death] + } +} + +/// `EntityTypeTags.UNDEAD`. +fn undead(s: Species) -> bool { + matches!( + s, + Species::Skeleton + | Species::Stray + | Species::WitherSkeleton + | Species::SkeletonHorse + | Species::Bogged + | Species::Parched + | Species::ZombieHorse + | Species::CamelHusk + | Species::Zombie + | Species::ZombieVillager + | Species::ZombifiedPiglin + | Species::Zoglin + | Species::Drowned + | Species::Husk + | Species::ZombieNautilus + | Species::Wither + | Species::Phantom + ) +} +/// `Armadillo.isScaredBy` for the nearby living entities: within 7 blocks +/// sideways and 2 up and down, an undead mob, the last attacker, or a +/// player who sprints or rides. +fn scared_by_someone(m: &Mob, w: &MobWorld) -> bool { + let area = m.bounds().inflate(Vec3::new(7.0, 2.0, 7.0)); + let attacker = + m.ai.last_hurt_by + .filter(|_| m.age as i32 - m.ai.last_hurt_by_time <= 100); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(area) + && (attacker == Some(Who::Player) || p.sprinting || p.riding) + { + return true; + } + w.others_near(area).any(|s| { + s.id != m.id + && s.alive + && s.bounds.intersects(area) + && (undead(s.species) || attacker == Some(Who::Mob(s.id))) + }) +} + +/// `Armadillo.customServerAiStep`'s brain: memories expire, the scare +/// sensor scans every fifth tick, the core's rolling out, then the +/// `ArmadilloBallUp` behaviour of the PANIC activity. +pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) { + let events = &mut *cx.events; + let a = &mut m.extra.armadillo; + if a.danger > 0 { + a.danger -= 1; + } + a.sensor -= 1; + if a.sensor <= 0 { + a.sensor = 5; + if !can_stay_rolled_up(m) { + m.extra.armadillo.danger = 0; + } else if scared_by_someone(m, cx.w) { + m.extra.armadillo.danger = 80; + } + } + // ARMADILLO_ROLLING_OUT: no danger left in mind. + if m.extra.armadillo.danger == 0 && scared(m) { + roll_out(m, events); + } + if m.extra.armadillo.panic_activity && !m.extra.armadillo.ball_up && m.on_ground && !liquid(m) { + // ArmadilloBallUp.start. + m.extra.armadillo.ball_up = true; + roll_up(m, events); + } + if m.extra.armadillo.ball_up { + ball_up_tick(m, events); + } + let a = &mut m.extra.armadillo; + a.panic_activity = a.danger > 0 && !m.ai.panicking; +} +fn liquid(m: &Mob) -> bool { + m.fluids.in_water || m.fluids.in_lava +} +/// `ArmadilloBallUp.tickOrStop`. +fn ball_up_tick(m: &mut Mob, events: &mut Vec) { + if !scared(m) { + // canStillUse is false: stop. + m.extra.armadillo.ball_up = false; + if !can_stay_rolled_up(m) { + roll_out(m, events); + } + return; + } + let a = &mut m.extra.armadillo; + if a.next_peek > 0 { + a.next_peek -= 1; + } + if a.state == ROLLING && a.in_state_ticks > animation_duration(ROLLING) { + set_state(m, SCARED); + if m.on_ground { + play(m, events, "entity.armadillo.land"); + } + return; + } + let danger = m.extra.armadillo.danger; + let around = danger > 75; + if around != m.extra.armadillo.danger_was_around { + m.extra.armadillo.next_peek = next_peek_timer(m); + } + m.extra.armadillo.danger_was_around = around; + let state = m.extra.armadillo.state; + if state == SCARED { + if m.extra.armadillo.next_peek == 0 && m.on_ground && around { + peek(m, events); + m.extra.armadillo.next_peek = next_peek_timer(m); + } + if danger < animation_duration(UNROLLING) { + play(m, events, "entity.armadillo.unroll_start"); + set_state(m, UNROLLING); + } + } else if state == UNROLLING && danger > animation_duration(UNROLLING) { + set_state(m, SCARED); + } +} +/// `ArmadilloBallUp.pickNextPeekTimer`. +fn next_peek_timer(m: &mut Mob) -> i32 { + animation_duration(SCARED) + m.random.next_int_between_inclusive(100, 400).unwrap_or(100) +} +/// `level.broadcastEntityEvent(body, 64)`; the sound is the client's +/// `playLocalSound`, which the server plays for everyone here. +fn peek(m: &mut Mob, events: &mut Vec) { + entity_event(m, 64); + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 64, + at, + }); + events.push(MobEvent::Sound("entity.armadillo.peek", at, 1.0, 1.0)); +} +/// `Armadillo.handleEntityEvent`: 64 is a peek. +pub fn entity_event(m: &mut Mob, event: u8) { + if event == 64 { + m.extra.armadillo.peek_received = true; + } +} + +/// `Armadillo.tick`: the animation states on a client, the ball's head held +/// to its body, and `inStateTicks`. Server and client both run it. +pub fn tick(m: &mut Mob) { + animate(m); + if scared(m) { + // clampHeadRotationToBody with getMaxHeadYRot 0. + m.head_yaw += super::living::wrap(m.body_yaw - m.head_yaw); + } + m.extra.armadillo.in_state_ticks += 1; +} +/// `Armadillo.setupAnimationStates`. +fn animate(m: &mut Mob) { + let age = m.age as f32; + let a = &mut m.extra.armadillo; + let s = &mut m.anim.states; + match a.state { + ROLLING => { + s[ROLL_OUT].stop(); + s[ROLL_UP].start_if_stopped(age); + s[PEEK].stop(); + } + SCARED => { + s[ROLL_OUT].stop(); + s[ROLL_UP].stop(); + if a.peek_received { + s[PEEK].stop(); + a.peek_received = false; + } + if a.in_state_ticks == 0 { + s[PEEK].start(age); + s[PEEK].fast_forward(animation_duration(SCARED)); + } else { + s[PEEK].start_if_stopped(age); + } + } + UNROLLING => { + s[ROLL_OUT].start_if_stopped(age); + s[ROLL_UP].stop(); + s[PEEK].stop(); + } + _ => { + s[ROLL_OUT].stop(); + s[ROLL_UP].stop(); + s[PEEK].stop(); + } + } +} + +/// `ArmadilloAi.ArmadilloPanic`: it unrolls, then runs. +#[derive(Clone, Debug)] +struct ArmadilloPanic(Panic); +impl Goal for ArmadilloPanic { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + "Panic" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + roll_out(m, cx.events); + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } +} +/// The behaviours that do not run while the armadillo is a ball: its +/// `MoveToTargetSink` and the idle activity's walking and looking. +#[derive(Clone, Debug)] +struct Rolled; +impl Goal for Rolled { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + scared(m) + } +} diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index bbb44c5ab..5bb7d45f6 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -1007,7 +1007,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { p, s, &Armadillo { - hiding_in_shell: false, + hiding_in_shell: super::armadillo::hiding_in_shell(m), roll_out: st[0], roll_up: st[1], peek: st[2], diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 541398bc5..45f228ead 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -654,12 +654,15 @@ impl Goal for Float { #[derive(Clone, Debug)] pub struct Panic { pub speed: f64, + /// Only the damage of `#panic_environmental_causes` (an armadillo). + pub environmental: bool, pos: [f64; 3], } impl Panic { pub fn new(speed: f64) -> Self { Self { speed, + environmental: false, pos: [0.0; 3], } } @@ -675,7 +678,14 @@ impl Goal for Panic { MOVE } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - if !should_panic(m) { + let wanted = if self.environmental { + m.last_damage.is_some_and(|(d, t)| { + super::armadillo::environmental(d.kind) && i64::from(m.age) - t <= 40 + }) || m.fire_ticks > 0 && !m.kind.flags.fire_immune + } else { + should_panic(m) + }; + if !wanted { return false; } if m.fire_ticks > 0 { diff --git a/crates/horizon-client/src/mobs/keyframes.rs b/crates/horizon-client/src/mobs/keyframes.rs index e070210ec..edcee8835 100644 --- a/crates/horizon-client/src/mobs/keyframes.rs +++ b/crates/horizon-client/src/mobs/keyframes.rs @@ -165,6 +165,12 @@ impl AnimationState { pub fn stop(&mut self) { self.started = None; } + /// `AnimationState.fastForward`: the animation is `ticks` further on. + pub fn fast_forward(&mut self, ticks: i32) { + if let Some(s) = &mut self.started { + *s -= ticks as f32; + } + } pub fn animate_when(&mut self, condition: bool, age: f32) { if condition { self.start_if_stopped(age) diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs index d1c5b6609..7beb837bf 100644 --- a/crates/horizon-client/src/mobs/sync.rs +++ b/crates/horizon-client/src/mobs/sync.rs @@ -15,7 +15,7 @@ //! them in `entity_event`; //! - run its client side animation in `client_tick`, sharing the function //! with the server's `ai_step` where the server computes the same. -use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; +use super::{Mob, Species, armadillo, breeze, camel, shulker, sniffer, warden}; // `Pose.id` of the poses mobs take. pub const STANDING: u8 = 0; @@ -60,6 +60,7 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { Species::Breeze => breeze::ai_step(m), Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), Species::Shulker => shulker::client_tick(m), + Species::Armadillo => armadillo::tick(m), _ => {} } } @@ -67,6 +68,9 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { /// `handleEntityEvent` of the mob types that start animations by an event /// (`ClientboundEntityEventPacket` for a mob of a client). pub fn entity_event(m: &mut Mob, event: u8) { + if m.species() == Species::Armadillo { + armadillo::entity_event(m, event); + } let age = m.age as f32; if m.species() == Species::Warden { match event { From 8144385ce6e352754002857f970c988ae5b46e6d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:02:03 +0100 Subject: [PATCH 116/221] Give foxes their stalk, pounce, faceplant, shelter and perch states The fox flags were only ever set for sleeping. Add the goals that drive the rest of Fox.DATA_FLAGS_ID and show them on the client: - StalkPreyGoal, FoxPounceGoal, FaceplantGoal: creep up on a chicken or rabbit, crouch, leap with the flight tilt and bite, or end up with the nose in snow (with its block crumbs). - SeekShelterGoal and PerchAndSearchGoal. - The fox's own conditions on the shared goals (melee, look at player) and clearStates on float, breed and follow parent; FoxMoveControl and FoxLookControl waits. - The head tilt and crouch amount ease on the client from the synched flags, and the model, body tilt and sleeping, snow and baby textures follow them. --- crates/horizon-client/src/game/creatures.rs | 9 + crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/mobs.rs | 7 + crates/horizon-client/src/mobs/ai.rs | 3 + crates/horizon-client/src/mobs/body_anim.rs | 2 +- crates/horizon-client/src/mobs/control.rs | 12 +- crates/horizon-client/src/mobs/fox.rs | 504 +++++++++++++++++++- crates/horizon-client/src/mobs/goals.rs | 43 +- crates/horizon-client/src/mobs/render.rs | 19 + 9 files changed, 573 insertions(+), 30 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 38cb3a2e4..238566792 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1189,6 +1189,15 @@ impl Game<'_> { MobEvent::Vibration { from, to, ticks } => { self.mob_vibration_particle(from, to, ticks) } + MobEvent::LevelEvent { id, pos, data } => { + self.level_events + .push(horizon_world::level::LevelEvent::LevelEvent { + id, + pos: horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), + data, + }); + self.process_level_events()?; + } MobEvent::DigParticles { at } => self.warden_dig_particles(at), MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius), MobEvent::CreakingHurt { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3cfbd15e3..987eae303 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3535,6 +3535,10 @@ impl Game<'_> { m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; *steps -= 1; } + // Fox.tick: the head tilt and crouch follow the synched flags. + if m.species() == horizon_client::mobs::Species::Fox { + horizon_client::mobs::fox::client_tick(m); + } // Chicken.aiStep: the wings follow the server's on-ground flag. if m.species() == horizon_client::mobs::Species::Chicken { horizon_client::mobs::farm::chicken_flap(m); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index aa86f669e..6211891ea 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1156,6 +1156,13 @@ pub enum MobEvent { to: [f64; 3], ticks: i32, }, + /// `Level.levelEvent` from a mob (a faceplanted fox's 2001, the snow's + /// crumbs). + LevelEvent { + id: i32, + pos: [i32; 3], + data: i32, + }, /// The crumbs of the block under a digging or emerging warden. DigParticles { at: [f64; 3], diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 7bb165020..29add1d06 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -640,6 +640,9 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & .is_some_and(|t| t.position.distance_squared(m.position) > 121.0); super::witch::ai_step(m, events, far); } + if m.species() == Species::Fox { + super::fox::pre_ai_step(m); + } // AbstractHorse.aiStep: the tail swishes now and then (moveTail). if super::equine::is_equine(m.species()) { let _ = m.random.next_int_bound(200); diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index b872cbd98..fa933a17b 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -1028,7 +1028,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { a, ), Species::Rabbit => rabbit(p, s, &st[0], &st[1], a), - Species::Fox => fox(p, s, &super::fox::pose(m), a), + Species::Fox => fox(p, s, &super::fox::pose(m, s.partial), a), _ => return false, } true diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 3df557362..39325d089 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -135,6 +135,10 @@ impl Mob { if self.species() == super::Species::Rabbit { return super::rabbit::move_control(self, w); } + // Fox.FoxMoveControl.tick: still while asleep, sitting or faceplanted. + if self.species() == super::Species::Fox && !super::fox::can_move(self) { + return; + } let attr_speed = self.movement_speed(); match self.ai.mov.kind { MoveKind::Custom => super::ai::custom_move_control(self, w, events), @@ -314,6 +318,11 @@ impl Mob { /// LookControl.tick (and SmoothSwimmingLookControl). pub fn look_control_tick(&mut self) { let look = self.ai.look.clone(); + let fox = self.species() == super::Species::Fox; + // Fox.FoxLookControl: no turning in sleep. + if fox && super::fox::flag(self, super::fox::SLEEPING) { + return; + } if look.kind == LookKind::HappyGhast { return super::happy_ghast::look_control(self); } @@ -346,7 +355,8 @@ impl Mob { } } LookKind::Default | LookKind::Fixed => { - if look.kind == LookKind::Default { + // FoxLookControl.resetXRotOnTick keeps a stalking or pouncing pitch. + if look.kind == LookKind::Default && (!fox || super::fox::resets_x_rot(self)) { self.head_pitch = 0.0; } if look.cooldown > 0 { diff --git a/crates/horizon-client/src/mobs/fox.rs b/crates/horizon-client/src/mobs/fox.rs index c683eeb86..833002b46 100644 --- a/crates/horizon-client/src/mobs/fox.rs +++ b/crates/horizon-client/src/mobs/fox.rs @@ -1,16 +1,23 @@ //! Foxes (`net.minecraft.world.entity.animal.fox.Fox`): the goal list, the -//! flags byte (sleeping, ...), napping in the shade by day, eating berries -//! and the food held in the mouth. Faceplanting, stalking and pouncing, -//! picking up items, sheltering and trusting players are not ported yet. +//! flags byte (sleeping, sitting, crouching, interested, pouncing, +//! faceplanted), stalking and pouncing, napping in the shade by day, seeking +//! shelter, perching, eating berries and the food held in the mouth. +//! Picking up items, strolling through villages and trusting players (with +//! defending them) are not ported yet. use super::{ Mob, MobEvent, MobWorld, Seen, Species, goals::{ Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, JUMP, LOOK, LeapAtTarget, LookAtPlayer, MOVE, MeleeAttack, MoveToBlock, NearestTarget, Panic, Prey, Stroll, - goal_clone, reduced, + goal_clone, hide_pos, reduced, }, + living::wrap, +}; +use horizon_core::{ + geometry::{Axis, Vec3}, + jmath, + random::RandomSource, }; -use horizon_core::{geometry::Axis, random::RandomSource}; use horizon_world::registry::BlockStateId; // Fox.DATA_FLAGS_ID, kept in `extra.ints[0]` (and sent to clients as is). @@ -23,6 +30,12 @@ pub const FACEPLANTED: i32 = 64; pub const DEFENDING: i32 = 128; /// `Fox.ticksSinceEaten`. const TICKS_SINCE_EATEN: usize = 1; +/// `Fox.interestedAngle` and `crouchAmount` in `anim.v`, the previous tick's +/// values in `anim.vo`. +const INTERESTED_ANGLE: usize = 0; +const CROUCH_AMOUNT: usize = 1; +/// `Fox.MAX_CROUCH_AMOUNT`. +const MAX_CROUCH_AMOUNT: f32 = 5.0; pub fn flag(m: &Mob, f: i32) -> bool { m.extra.ints[0] & f != 0 @@ -38,15 +51,24 @@ fn set_flag(m: &mut Mob, f: i32, on: bool) { fn clear_states(m: &mut Mob) { m.extra.ints[0] = 0; } +/// `Fox.canMove`, which `FoxMoveControl` waits for. +pub fn can_move(m: &Mob) -> bool { + !flag(m, SLEEPING | SITTING | FACEPLANTED) +} +/// `FoxLookControl.resetXRotOnTick`: stalking and pouncing keep their pitch. +pub fn resets_x_rot(m: &Mob) -> bool { + !flag(m, POUNCING | CROUCHING | INTERESTED | FACEPLANTED) +} /// `Fox.registerGoals` and `setTargetGoals` (the targets wait for the variant: /// red foxes prefer chickens and rabbits, snow foxes fish). pub fn register(m: &mut Mob) { let countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0); let g = &mut m.ai.goals; - g.add(0, Float); + g.add(0, Wrap::new(Float).on_start(clear_states)); + g.add(1, Faceplant { countdown: 0 }); g.add(2, Panic::new(2.2)); - g.add(3, Breed::new(1.0)); + g.add(3, Wrap::new(Breed::new(1.0)).on_start(clear_states)); // AVOID_PLAYERS: not a sneaking player. g.add( 4, @@ -61,13 +83,29 @@ pub fn register(m: &mut Mob) { 4, AvoidEntity::new(Avoid::Species(vec![Species::PolarBear]), 8.0, 1.6, 1.4), ); - g.add(7, MeleeAttack::new(1.2, true)); + g.add(5, StalkPrey); + g.add(6, Pounce); + g.add(6, SeekShelter::new(1.25)); + g.add( + 7, + Wrap::new(MeleeAttack::new(1.2, true)) + .when( + |m| !flag(m, SITTING | SLEEPING | CROUCHING | FACEPLANTED), + false, + ) + .on_start(|m| set_flag(m, INTERESTED, false)), + ); g.add(7, Sleep { countdown }); - g.add(8, FollowParent::new(1.25)); + g.add(8, Wrap::new(FollowParent::new(1.25)).on_start(clear_states)); g.add(10, EatBerries::new()); g.add(10, LeapAtTarget::new(0.4)); g.add(11, Stroll::avoiding_water(1.0)); - g.add(12, LookAtPlayer::new(24.0)); + // FoxLookAtPlayerGoal: not with the nose in the snow or while stalking. + g.add( + 12, + Wrap::new(LookAtPlayer::new(24.0)).when(|m| !flag(m, FACEPLANTED | INTERESTED), true), + ); + g.add(13, Perch::default()); let red = |m: &Mob, _: &MobWorld| m.extra.variant == 0; let snow = |m: &Mob, _: &MobWorld| m.extra.variant != 0; let land = || NearestTarget::new(Prey::Filter(chicken_or_rabbit), false).interval(10); @@ -95,8 +133,28 @@ fn schooling_fish(s: &Seen) -> bool { ) } +/// The part of `Fox.tick` a client runs too: the head tilt eases toward the +/// interested flag and the crouch builds up to 5 while crouching. +pub fn client_tick(m: &mut Mob) { + let (interested, crouching) = (flag(m, INTERESTED), flag(m, CROUCHING)); + let v = &mut m.anim.v; + m.anim.vo[INTERESTED_ANGLE] = v[INTERESTED_ANGLE]; + v[INTERESTED_ANGLE] += (if interested { 1.0 } else { 0.0 } - v[INTERESTED_ANGLE]) * 0.4; + m.anim.vo[CROUCH_AMOUNT] = v[CROUCH_AMOUNT]; + v[CROUCH_AMOUNT] = if crouching { + (v[CROUCH_AMOUNT] + 0.2).min(MAX_CROUCH_AMOUNT) + } else { + 0.0 + }; +} +/// `Fox.isFullyCrouched`. +fn fully_crouched(m: &Mob) -> bool { + m.anim.v[CROUCH_AMOUNT] == MAX_CROUCH_AMOUNT +} + /// `Fox.tick` and the eating part of `Fox.aiStep`. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + client_tick(m); if !m.alive() { return; } @@ -121,7 +179,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Sound("entity.fox.eat", at, 1.0, 1.0)); } } - if m.ai.target.is_none() { + if !m.target_info(w).is_some_and(|t| t.alive) { set_flag(m, CROUCHING | INTERESTED, false); } let in_water = m.fluids.in_water; @@ -131,6 +189,27 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if in_water || flag(m, SLEEPING) { set_flag(m, SITTING, false); } + // Faceplanted: crumbs of the snow now and then (level event 2001). + if flag(m, FACEPLANTED) && m.random.next_float() < 0.2 { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + events.push(MobEvent::LevelEvent { + id: 2001, + pos: at, + data: w.world.block(at[0], at[1], at[2]).0 as i32, + }); + } +} +/// `Fox.aiStep` before the living step: a sleeping fox takes no input. +pub fn pre_ai_step(m: &mut Mob) { + if flag(m, SLEEPING) { + m.ai.jumping = false; + m.ai.xxa = 0.0; + m.ai.zza = 0.0; + } } /// `Fox.isConsumableFood`: the item has food and consumable components. fn eats(w: &MobWorld, item: &str) -> bool { @@ -223,6 +302,399 @@ impl Goal for Sleep { } } +/// A shared goal under the fox's own conditions and start-up: the extra +/// `canUse` of `FoxMeleeAttackGoal` and `FoxLookAtPlayerGoal` and the +/// `clearStates` or `setIsInterested(false)` its subclasses do in `start`. +#[derive(Clone, Debug)] +struct Wrap { + goal: G, + when: Option bool>, + /// The condition also applies to `canContinueToUse`. + both: bool, + on_start: Option, +} +impl Wrap { + fn new(goal: G) -> Self { + Self { + goal, + when: None, + both: false, + on_start: None, + } + } + fn when(mut self, f: fn(&Mob) -> bool, both: bool) -> Self { + (self.when, self.both) = (Some(f), both); + self + } + fn on_start(mut self, f: fn(&mut Mob)) -> Self { + self.on_start = Some(f); + self + } +} +impl Goal for Wrap { + goal_clone!(); + fn flags(&self) -> u8 { + self.goal.flags() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.when.is_none_or(|f| f(m)) && self.goal.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (!self.both || self.when.is_none_or(|f| f(m))) && self.goal.can_continue(m, cx) + } + fn interruptable(&self) -> bool { + self.goal.interruptable() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(f) = self.on_start { + f(m); + } + self.goal.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.stop(m, cx); + } + fn every_tick(&self) -> bool { + self.goal.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.tick(m, cx); + } + fn name(&self) -> &'static str { + self.goal.name() + } +} + +/// `Fox.isPathClear`: six points along the way to the target, each with +/// nothing but replaceable blocks in the three above it. +fn path_clear(m: &Mob, w: &MobWorld, to: Vec3) -> bool { + let (zdiff, xdiff) = (to.z - m.position.z, to.x - m.position.x); + let slope = zdiff / xdiff; + for i in 0..6 { + let step = f64::from(i as f32 / 6.0); + let z = if slope == 0.0 { 0.0 } else { zdiff * step }; + let x = if slope == 0.0 { + xdiff * step + } else { + z / slope + }; + for j in 1..4 { + let at = [ + (m.position.x + x).floor() as i32, + (m.position.y + f64::from(j)).floor() as i32, + (m.position.z + z).floor() as i32, + ]; + if !w.facts.get(w.world.block(at[0], at[1], at[2])).replaceable { + return false; + } + } + } + true +} +fn signum(x: f64) -> f64 { + if x > 0.0 { + 1.0 + } else if x < 0.0 { + -1.0 + } else { + 0.0 + } +} + +/// `Fox.FaceplantGoal`: stay put for 40 ticks with the nose in the snow. +#[derive(Clone, Debug)] +struct Faceplant { + countdown: i32, +} +impl Goal for Faceplant { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + flag(m, FACEPLANTED) + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + flag(m, FACEPLANTED) && self.countdown > 0 + } + fn start(&mut self, _: &mut Mob, _: &mut Cx) { + self.countdown = reduced(40); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FACEPLANTED, false); + } + fn tick(&mut self, _: &mut Mob, _: &mut Cx) { + self.countdown -= 1; + } +} + +/// `Fox.StalkPreyGoal`: creep up on a chicken or rabbit more than 6 blocks +/// away, then crouch and keep still once it is within 6. +#[derive(Clone, Debug)] +struct StalkPrey; +impl StalkPrey { + fn look(m: &mut Mob, eye: [f64; 3]) { + let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot); + m.look_at_speed(eye, y, x); + } +} +impl Goal for StalkPrey { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) { + return false; + } + let Some(t) = m.target_info(cx.w) else { + return false; + }; + let stalkable = match m.ai.target { + Some(super::Who::Mob(id)) => { + cx.w.seen(id) + .is_some_and(|s| matches!(s.species, Species::Chicken | Species::Rabbit)) + } + _ => false, + }; + t.alive + && stalkable + && m.distance_sqr(t.position) > 36.0 + && !flag(m, CROUCHING | INTERESTED) + && !m.ai.jumping + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING | FACEPLANTED, false); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + match m.target_info(cx.w) { + Some(t) if path_clear(m, cx.w, t.position) => { + set_flag(m, INTERESTED | CROUCHING, true); + m.nav_stop(); + Self::look(m, [t.position.x, t.eye_y, t.position.z]); + } + _ => set_flag(m, INTERESTED | CROUCHING, false), + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.target_info(cx.w) else { return }; + Self::look(m, [t.position.x, t.eye_y, t.position.z]); + if m.distance_sqr(t.position) <= 36.0 { + set_flag(m, INTERESTED | CROUCHING, true); + m.nav_stop(); + } else { + let at = [t.position.x, t.position.y, t.position.z]; + m.nav_move_to_entity(cx.w, at, 0, 1.5); + } + } +} + +/// `Fox.FoxPounceGoal`: once fully crouched with a clear path, leap at the +/// target, tilt with the flight and bite when within 2 blocks, or end up with +/// the nose in snow. +#[derive(Clone, Debug)] +struct Pounce; +impl Goal for Pounce { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !fully_crouched(m) { + return false; + } + let Some(t) = m.target_info(cx.w).filter(|t| t.alive) else { + return false; + }; + let clear = path_clear(m, cx.w, t.position); + if !clear { + set_flag(m, CROUCHING | INTERESTED, false); + } + clear + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.target_info(cx.w).is_some_and(|t| t.alive) { + return false; + } + let yd = m.velocity.y; + (yd * yd >= f64::from(0.05f32) || m.head_pitch.abs() >= 15.0 || !m.on_ground) + && !flag(m, FACEPLANTED) + } + fn interruptable(&self) -> bool { + false + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.ai.jumping = true; + set_flag(m, POUNCING, true); + set_flag(m, INTERESTED, false); + if let Some(t) = m.target_info(cx.w) { + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0); + let u = m.position.vector_to(t.position).normalize(); + m.velocity = m.velocity.add_vector(Vec3::new(u.x * 0.8, 0.9, u.z * 0.8)); + } + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, CROUCHING | INTERESTED | POUNCING, false); + m.anim.v[CROUCH_AMOUNT] = 0.0; + m.anim.vo[CROUCH_AMOUNT] = 0.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let target = m.target_info(cx.w); + if let Some(t) = &target { + m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0); + } + if !flag(m, FACEPLANTED) { + let v = m.velocity; + if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 { + m.head_pitch += 0.2 * wrap(-m.head_pitch); + } else { + let horizontal = v.horizontal_distance(); + let bias = if m.ai.jumping && v.y > 0.0 { 6.5 } else { 1.0 }; + let y = v.y * bias; + let len = (horizontal * horizontal + y * y).sqrt(); + if len > f64::from(1.0e-5f32) { + let pitch = signum(-y) * jmath::acos(horizontal / len) * 180.0 + / f64::from(std::f32::consts::PI); + m.head_pitch = (pitch as f32 % 360.0).clamp(-90.0, 90.0); + } + } + } + if let (Some(t), Some(who)) = (&target, m.ai.target) + && m.distance_sqr(t.position) <= 4.0 + { + super::ai::do_hurt_target(m, who, cx); + } else if m.head_pitch > 0.0 + && m.on_ground + && m.velocity.y as f32 != 0.0 + && cx.w.block_name( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ) == "minecraft:snow" + { + m.head_pitch = 60.0; + m.ai.target = None; + set_flag(m, FACEPLANTED, true); + } + } +} + +/// `Fox.SeekShelterGoal`: by day, or in a thunderstorm, leave open sky for +/// somewhere the sky does not see. Villages are not told apart yet (vanilla +/// stays put in one). +#[derive(Clone, Debug)] +struct SeekShelter { + speed: f64, + interval: i32, + wanted: [f64; 3], +} +impl SeekShelter { + fn new(speed: f64) -> Self { + Self { + speed, + interval: reduced(100), + wanted: [0.0; 3], + } + } + fn set_wanted_pos(&mut self, m: &mut Mob, w: &MobWorld) -> bool { + hide_pos(m, w).is_some_and(|at| { + self.wanted = at; + true + }) + } +} +impl Goal for SeekShelter { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if flag(m, SLEEPING) || m.ai.target.is_some() { + return false; + } + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + let sees_sky = cx.w.can_see_sky(at[0], at[1], at[2]); + if cx.w.thundering && sees_sky { + self.set_wanted_pos(m, cx.w) + } else if self.interval > 0 { + self.interval -= 1; + false + } else { + self.interval = 100; + cx.w.daylight && sees_sky && self.set_wanted_pos(m, cx.w) + } + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + !m.ai.nav.is_done() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + clear_states(m); + m.nav_move_to(cx.w, self.wanted, self.speed); + } +} + +/// `Fox.PerchAndSearchGoal`: now and then sit down and look around two to +/// four times when nothing is going on. +#[derive(Clone, Debug, Default)] +struct Perch { + rel: [f64; 2], + look_time: i32, + looks_remaining: i32, +} +impl Perch { + fn reset_look(&mut self, m: &mut Mob) { + let angle = std::f64::consts::TAU * m.random.next_double(); + self.rel = [angle.cos(), angle.sin()]; + self.look_time = reduced(80 + m.random.next_int_bound(20).unwrap_or(0)); + } +} +impl Goal for Perch { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + m.ai.last_hurt_by.is_none() + && m.random.next_float() < 0.02 + && !flag(m, SLEEPING) + && m.ai.target.is_none() + && m.ai.nav.is_done() + && !alertable(m, cx.w) + && !flag(m, POUNCING | CROUCHING) + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + self.looks_remaining > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.reset_look(m); + self.looks_remaining = 2 + m.random.next_int_bound(3).unwrap_or(0); + set_flag(m, SITTING, true); + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, SITTING, false); + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + self.look_time -= 1; + if self.look_time <= 0 { + self.looks_remaining -= 1; + self.reset_look(m); + } + let at = [ + m.position.x + self.rel[0], + m.eye_y(), + m.position.z + self.rel[1], + ]; + let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot); + m.look_at_speed(at, y, x); + } +} + /// `BlockState` with one property changed. fn with_prop(w: &MobWorld, p: [i32; 3], key: &str, value: &str) -> Option { let mut s = w.registry.state(w.world.block(p[0], p[1], p[2]))?.clone(); @@ -356,14 +828,18 @@ impl Goal for EatBerries { } } -/// `FoxModel`'s flags as the renderer reads them. -pub fn pose(m: &Mob) -> super::body_anim::Fox { +/// `FoxRenderState` as the renderer reads it: the flags, `getHeadRollAngle` +/// and `getCrouchAmount` at the partial tick. `FoxModel.legMotionPos` gains +/// 0.67 a frame; this takes 60 frames a second. +pub fn pose(m: &Mob, partial: f32) -> super::body_anim::Fox { super::body_anim::Fox { crouching: flag(m, CROUCHING), sleeping: flag(m, SLEEPING), sitting: flag(m, SITTING), pouncing: flag(m, POUNCING), faceplanted: flag(m, FACEPLANTED), - ..Default::default() + head_roll_angle: m.anim.lerp(INTERESTED_ANGLE, partial) * 0.11 * std::f32::consts::PI, + crouch_amount: m.anim.lerp(CROUCH_AMOUNT, partial), + leg_motion_pos: (m.age as f32 + partial) * 0.67 * 3.0, } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 1124414b8..324cc8702 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1964,6 +1964,30 @@ impl Goal for RestrictSun { m.ai.nav.avoid_sun = false; } } +/// `FleeSunGoal.getHidePos`: a spot within 10 blocks that the sky does not +/// see and the mob likes. +pub fn hide_pos(m: &mut Mob, w: &MobWorld) -> Option<[f64; 3]> { + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + for _ in 0..10 { + let p = [ + bx + m.random.next_int_bound(20).unwrap_or(0) - 10, + by + m.random.next_int_bound(6).unwrap_or(0) - 3, + bz + m.random.next_int_bound(20).unwrap_or(0) - 10, + ]; + if !w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(w, p) < 0.0 { + return Some([ + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ]); + } + } + None +} /// FleeSunGoal: find shade while burning. #[derive(Clone, Debug)] pub struct FleeSun { @@ -1995,22 +2019,13 @@ impl Goal for FleeSun { if !cx.w.can_see_sky(bx, by, bz) { return false; } - for _ in 0..10 { - let p = [ - bx + m.random.next_int_bound(20).unwrap_or(0) - 10, - by + m.random.next_int_bound(6).unwrap_or(0) - 3, - bz + m.random.next_int_bound(20).unwrap_or(0) - 10, - ]; - if !cx.w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(cx.w, p) < 0.0 { - self.wanted = [ - f64::from(p[0]) + 0.5, - f64::from(p[1]), - f64::from(p[2]) + 0.5, - ]; - return true; + match hide_pos(m, cx.w) { + Some(at) => { + self.wanted = at; + true } + None => false, } - false } fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { !m.ai.nav.is_done() diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..470c6db5e 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -181,6 +181,20 @@ pub fn body(m: &Mob) -> (String, String) { baby_or(m, "rabbit#main", "rabbit_baby#main"), b(&m.kind.texture), ), + // FoxRenderer.getTextureLocation: snow variant, sleeping, baby. + S::Fox => ( + baby_or(m, "fox#main", "fox_baby#main"), + format!( + "entity/fox/fox{}{}{}", + if m.extra.variant == 0 { "" } else { "_snow" }, + if super::fox::flag(m, super::fox::SLEEPING) { + "_sleep" + } else { + "" + }, + if baby { "_baby" } else { "" }, + ), + ), S::Pig => { let model = if baby { "pig_baby#main".into() @@ -855,6 +869,11 @@ fn species_rotations(m: &Mob, alpha: f32) -> glam::Mat4 { match m.species() { Species::Cat => super::tame::cat_rotations(m, alpha), Species::Shulker => super::shulker::rotations(m), + // FoxRenderer.setupRotations: the body follows a pounce's pitch. + Species::Fox if super::fox::flag(m, super::fox::POUNCING | super::fox::FACEPLANTED) => { + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + glam::Mat4::from_rotation_x((-pitch).to_radians()) + } _ => glam::Mat4::IDENTITY, } } From 5e27fd342166040e1cc464e88c059e078534f86a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:04:35 +0100 Subject: [PATCH 117/221] Use the mob level event that main already has --- crates/horizon-client/src/game/creatures.rs | 9 --------- crates/horizon-client/src/mobs.rs | 7 ------- 2 files changed, 16 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3832bab7b..14b5fdc7d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1288,15 +1288,6 @@ impl Game<'_> { MobEvent::Vibration { from, to, ticks } => { self.mob_vibration_particle(from, to, ticks) } - MobEvent::LevelEvent { id, pos, data } => { - self.level_events - .push(horizon_world::level::LevelEvent::LevelEvent { - id, - pos: horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), - data, - }); - self.process_level_events()?; - } MobEvent::DigParticles { at } => self.warden_dig_particles(at), MobEvent::BlockBreakEffect { pos, block } => { let state = self.world.block(block[0], block[1], block[2]); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 90ec10745..76843c02c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1195,13 +1195,6 @@ pub enum MobEvent { to: [f64; 3], ticks: i32, }, - /// `Level.levelEvent` from a mob (a faceplanted fox's 2001, the snow's - /// crumbs). - LevelEvent { - id: i32, - pos: [i32; 3], - data: i32, - }, /// The crumbs of the block under a digging or emerging warden. DigParticles { at: [f64; 3], From 04b0b9aed5eb24f99bf88185560238bd40330bf2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:06:30 +0100 Subject: [PATCH 118/221] Let frogs croak, shoot their tongue at small slimes and idle-swim --- crates/horizon-client/src/game/lan.rs | 9 + crates/horizon-client/src/mobs.rs | 6 + crates/horizon-client/src/mobs/ai.rs | 3 + crates/horizon-client/src/mobs/frog.rs | 301 +++++++++++++++++++++++++ crates/horizon-client/src/mobs/sync.rs | 9 +- 5 files changed, 326 insertions(+), 2 deletions(-) create mode 100644 crates/horizon-client/src/mobs/frog.rs diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6e00df8fe..01714cebc 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -399,6 +399,15 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(16))); } + // Frog.DATA_TONGUE_TARGET_ID (after the variant): the entity id plus + // one, 0 for none. + "minecraft:frog" => { + if let Some(target) = e.frog.tongue_target { + let id = i32::try_from(target).map_or(0, |t| t + 1); + meta.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(id))); + } + defaults.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(0))); + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3daeeb10a..5c32b1cd4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -31,6 +31,7 @@ pub mod enderman; pub mod equine; pub mod farm; pub mod finalize; +pub mod frog; pub mod gear; pub mod goals; pub mod golem; @@ -786,6 +787,8 @@ pub struct Extra { pub brain: Option>, /// A bee's nectar, anger, flower and hive state. pub bee: Option>, + /// A frog's brain memories and tongue target. + pub frog: frog::State, } #[derive(Clone, Debug)] pub struct Mob { @@ -1272,6 +1275,8 @@ pub struct Seen { pub target: Option, pub health: f32, pub variant: u8, + /// A slime's or magma cube's size. + pub size: i32, /// Dye colour (sheep). pub color: u8, /// A villager's claimed job site and bed. @@ -1367,6 +1372,7 @@ impl Mob { target: m.ai.target, health: m.health, variant: m.extra.variant, + size: m.extra.size, color: m.extra.color, job: villager.then_some(m.extra.home).flatten(), bed: villager.then_some(m.extra.bed).flatten(), diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 258c1ccc7..fa71568fd 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -178,6 +178,7 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + Family::Generic if m.species() == Species::Frog => super::frog::register(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { @@ -964,6 +965,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1, Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events), Species::Bee => super::bee::server_ai_step(m, cx), + Species::Frog => super::frog::server_ai_step(m, cx.w), _ => {} } } @@ -1016,6 +1018,7 @@ fn species_ai_step( } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Frog => super::frog::tick(m), Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; diff --git a/crates/horizon-client/src/mobs/frog.rs b/crates/horizon-client/src/mobs/frog.rs new file mode 100644 index 000000000..7d1e04050 --- /dev/null +++ b/crates/horizon-client/src/mobs/frog.rs @@ -0,0 +1,301 @@ +//! Frogs (`Frog`, `FrogAi`): the `Croak` and `ShootTongue` behaviours as +//! goals, the poses they set and the client's animation states. +//! AnimState states: jump, croak, tongue, swim idle. +//! +//! The brain's idle `RunOne` picks a croak three times as often as a stroll +//! (weights 3 and 1; it also holds a do-nothing option that only repeats +//! the pick), so a frog that is not walking croaks in three of four idle +//! picks: `Croak` takes those, and the frog's stroll then follows at once. +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + goals::{ + Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone, + }, + sync, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +const JUMP: usize = 0; +const CROAK: usize = 1; +const TONGUE: usize = 2; +const SWIM_IDLE: usize = 3; + +/// `Croak.CROAK_TICKS`. +const CROAK_TICKS: i32 = 60; +/// `ShootTongue`'s duration and eating distance. +const TONGUE_TIME_OUT: i32 = 100; +const EATING_DISTANCE: f64 = 1.75; +/// `FrogAttackablesSensor.TARGET_DETECTION_DISTANCE` and the sensor's scan +/// rate. +const DETECTION_DISTANCE: f64 = 10.0; +const SCAN_RATE: i32 = 20; + +/// `ShootTongue.State`. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Phase { + MoveToTarget, + CatchAnimation, + EatAnimation, + #[default] + Done, +} + +/// The frog's brain memories and `DATA_TONGUE_TARGET_ID`. +#[derive(Clone, Debug, Default)] +pub struct State { + croak: i32, + /// Ticks to the attackables sensor's next scan, and `NEAREST_ATTACKABLE`. + scan: i32, + nearest: Option, + /// `UNREACHABLE_TONGUE_TARGETS`: the mob and the ticks it stays in mind. + unreachable: Vec<(u32, i32)>, + /// `ATTACK_TARGET` while `ShootTongue` runs, and the synched tongue target. + target: Option, + pub tongue_target: Option, + phase: Phase, + eat_timer: i32, + path_counter: i32, + time: i32, +} + +pub fn register(m: &mut Mob) { + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(1, Panic::new(1.25)); + g.add(2, ShootTongue); + g.add(4, Croak); + g.add(5, Stroll::avoiding_water(1.0).interval(1)); + g.add(6, LookAtPlayer::new(6.0)); + g.add(7, RandomLookAround::default()); +} + +/// `Entity.setPose` and `Frog.onSyncedDataUpdated(DATA_POSE)`. +pub fn set_pose(m: &mut Mob, id: u8) { + let old = std::mem::replace(&mut m.extra.pose, id); + if old != id { + pose_changed(m); + } +} +/// The animation states of the pose the frog has taken. +pub fn pose_changed(m: &mut Mob) { + let age = m.age as f32; + let pose = m.extra.pose; + let states = &mut m.anim.states; + for (state, on) in [ + (JUMP, pose == sync::LONG_JUMPING), + (CROAK, pose == sync::CROAKING), + (TONGUE, pose == sync::USING_TONGUE), + ] { + if on { + states[state].start(age); + } else { + states[state].stop(); + } + } +} +/// `Frog.tick` on a client: the idle swim while it floats still. The server +/// runs it too, for a window that shows its own mobs. +pub fn tick(m: &mut Mob) { + let age = m.age as f32; + let still = m.fluids.in_water && m.limb_speed <= 1.0e-5; + m.anim.states[SWIM_IDLE].animate_when(still, age); +} + +/// `Frog.canEat`: a slime or magma cube of size 1. +fn can_eat(species: Species, size: i32) -> bool { + matches!(species, Species::Slime | Species::MagmaCube) && size == 1 +} + +/// `FrogAttackablesSensor` (every 20 ticks) and the memory timers. +pub fn server_ai_step(m: &mut Mob, w: &MobWorld) { + let f = &mut m.extra.frog; + f.unreachable.retain_mut(|(_, ttl)| { + *ttl -= 1; + *ttl > 0 + }); + f.scan -= 1; + if f.scan > 0 { + return; + } + f.scan = SCAN_RATE; + let unreachable: Vec = f.unreachable.iter().map(|u| u.0).collect(); + let eye = Vec3::new(m.position.x, m.eye_y(), m.position.z); + let nearest = w + .nearby(m.position, DETECTION_DISTANCE, |s| { + can_eat(s.species, s.size) + && !unreachable.contains(&s.id) + && w.line_of_sight(eye, Vec3::new(s.position.x, s.eye_y, s.position.z)) + }) + .find(|s| s.position.distance_squared(m.position) < DETECTION_DISTANCE * DETECTION_DISTANCE) + .map(|s| s.id); + m.extra.frog.nearest = nearest; +} + +/// `Croak`: the pose sync::CROAKING for 60 ticks (the croak is the frog's ambient +/// sound). +#[derive(Clone, Debug)] +struct Croak; +impl Goal for Croak { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + // checkExtraStartConditions (standing), no walk target, and not in + // a liquid (start does nothing there). + m.extra.pose == sync::STANDING + && m.on_ground + && !m.fluids.in_water + && !m.fluids.in_lava + && m.ai.nav.is_done() + && m.random.next_int_bound(4).unwrap_or(0) != 0 + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + m.extra.frog.croak < CROAK_TICKS + } + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.frog.croak = 0; + set_pose(m, sync::CROAKING); + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + set_pose(m, sync::STANDING); + } + fn tick(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.frog.croak += 1; + } + fn every_tick(&self) -> bool { + true + } +} + +/// `ShootTongue` with the tongue activity's `StartAttacking` and +/// `StopAttackingIfTargetInvalid`: walk up to a small slime or magma cube, +/// shoot the tongue, pull it in and eat it. +#[derive(Clone, Debug)] +struct ShootTongue; +impl Goal for ShootTongue { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some(id) = m.extra.frog.nearest else { + return false; + }; + // The start conditions: no walk target, no panic, not croaking. + if m.ai.panicking || m.extra.pose == sync::CROAKING || !m.ai.nav.is_done() { + return false; + } + let Some(t) = cx.w.seen(id).filter(|t| t.alive) else { + m.extra.frog.nearest = None; + return false; + }; + // canPathfindToTarget: a path that ends at the target. + let at = [t.position.x, t.position.y, t.position.z]; + let ends = m + .create_path_to_entity(cx.w, at, 0) + .is_some_and(|p| f64::from(p.dist_to_target) < EATING_DISTANCE); + if !ends { + // The target is forgotten and not taken for 100 ticks. + let f = &mut m.extra.frog; + f.nearest = None; + if !f.unreachable.iter().any(|u| u.0 == id) { + if f.unreachable.len() == 5 { + f.unreachable.remove(0); + } + f.unreachable.push((id, 100)); + } + return false; + } + m.extra.frog.target = Some(id); + true + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let f = &m.extra.frog; + f.phase != Phase::Done + && f.time <= TONGUE_TIME_OUT + && !m.ai.panicking + && f.target + .is_some_and(|id| cx.w.seen(id).is_some_and(|t| t.alive)) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.extra.frog.target.and_then(|id| cx.w.seen(id)) else { + return; + }; + let at = [t.position.x, t.position.y, t.position.z]; + let eye = [t.position.x, t.eye_y, t.position.z]; + m.look_at(eye); + m.extra.frog.tongue_target = m.extra.frog.target; + m.nav_move_to_entity(cx.w, at, 0, 2.0); + let f = &mut m.extra.frog; + f.path_counter = 10; + f.time = 0; + f.phase = Phase::MoveToTarget; + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + let f = &mut m.extra.frog; + f.target = None; + f.tongue_target = None; + f.phase = Phase::Done; + set_pose(m, sync::STANDING); + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(id) = m.extra.frog.target else { + return; + }; + let Some(t) = cx.w.seen(id) else { + return; + }; + let (at, pos) = ([t.position.x, t.position.y, t.position.z], t.position); + m.look_at([t.position.x, t.eye_y, t.position.z]); + m.extra.frog.tongue_target = Some(id); + m.extra.frog.time += 1; + let here = [m.position.x, m.position.y, m.position.z]; + match m.extra.frog.phase { + Phase::MoveToTarget => { + if pos.distance_squared(m.position) < EATING_DISTANCE * EATING_DISTANCE { + cx.events + .push(MobEvent::Sound("entity.frog.tongue", here, 2.0, 1.0)); + set_pose(m, sync::USING_TONGUE); + // The target is drawn in at 0.75 a tick. + let pull = m.position.subtract(pos).normalize().scale(0.75); + cx.events.push(MobEvent::Push { + target: Who::Mob(id), + velocity: [pull.x, pull.y, pull.z], + }); + let f = &mut m.extra.frog; + f.eat_timer = 0; + f.phase = Phase::CatchAnimation; + } else if m.extra.frog.path_counter <= 0 { + m.nav_move_to_entity(cx.w, at, 0, 2.0); + m.extra.frog.path_counter = 10; + } else { + m.extra.frog.path_counter -= 1; + } + } + Phase::CatchAnimation => { + let f = &mut m.extra.frog; + f.eat_timer += 1; + if f.eat_timer > 6 { + f.phase = Phase::EatAnimation; + // eatEntity. + cx.events + .push(MobEvent::Sound("entity.frog.eat", here, 2.0, 1.0)); + super::ai::do_hurt_target(m, Who::Mob(id), cx); + } + } + Phase::EatAnimation => { + let f = &mut m.extra.frog; + if f.eat_timer >= 10 { + f.phase = Phase::Done; + } else { + f.eat_timer += 1; + } + } + Phase::Done => {} + } + } +} diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs index d1c5b6609..9d50d8ac0 100644 --- a/crates/horizon-client/src/mobs/sync.rs +++ b/crates/horizon-client/src/mobs/sync.rs @@ -15,11 +15,13 @@ //! them in `entity_event`; //! - run its client side animation in `client_tick`, sharing the function //! with the server's `ai_step` where the server computes the same. -use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; +use super::{Mob, Species, breeze, camel, frog, shulker, sniffer, warden}; // `Pose.id` of the poses mobs take. pub const STANDING: u8 = 0; pub const LONG_JUMPING: u8 = 6; +pub const CROAKING: u8 = 8; +pub const USING_TONGUE: u8 = 9; pub const SITTING: u8 = 10; pub const ROARING: u8 = 11; pub const SNIFFING: u8 = 12; @@ -36,14 +38,16 @@ pub fn pose_id(m: &Mob) -> u8 { Species::Warden => warden::pose_id(m), Species::Breeze => breeze::pose_id(m), Species::Camel | Species::CamelHusk if camel::sitting(m) => SITTING, + Species::Frog => m.extra.pose, _ => STANDING, } } /// `Entity.onSyncedDataUpdated(DATA_POSE)` on a client. pub fn set_pose(m: &mut Mob, id: u8) { - m.extra.pose = id; + let old = std::mem::replace(&mut m.extra.pose, id); match m.species() { + Species::Frog if old != id => frog::pose_changed(m), Species::Warden => warden::set_pose_id(m, id), Species::Breeze => breeze::set_pose_id(m, id), _ => {} @@ -60,6 +64,7 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { Species::Breeze => breeze::ai_step(m), Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), Species::Shulker => shulker::client_tick(m), + Species::Frog => frog::tick(m), _ => {} } } From 140958fa58e766216a886730a66265f8e3dd11e2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:07:25 +0100 Subject: [PATCH 119/221] Sync the variants and looks of server mobs to the window The window's mobs are built only from SetEntityData, but mob_meta sent only some species' data and remote_mob_data decoded even less. Send and read the colour, type and state entries that the renderers draw from. --- crates/horizon-client/src/game/lan.rs | 127 +++++++++++++++++- .../src/game/remote_mob_data.rs | 103 +++++++++++++- crates/horizon-client/src/mobs/bee.rs | 11 ++ 3 files changed, 238 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index e39fa3a68..7aad08e4e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -161,6 +161,7 @@ fn mob_meta( m: &Mob, hub: &Hub, player_entity: Option, + game_time: i64, meta: &mut Vec<(u8, i32, Value)>, defaults: &mut Vec<(u8, i32, Value)>, ) { @@ -272,6 +273,14 @@ fn mob_meta( meta.push((collar, serializer::INT, Value::Int(i32::from(e.color & 15)))); } defaults.push((collar, serializer::INT, Value::Int(red))); + // Wolf.DATA_ANGER_END_TIME: the game time the anger ends, -1 when calm. + if kind == "minecraft:wolf" { + if e.anger > 0 { + let end = game_time + i64::from(e.anger); + meta.push((22, serializer::LONG, Value::Long(end))); + } + defaults.push((22, serializer::LONG, Value::Long(-1))); + } } "minecraft:horse" | "minecraft:donkey" @@ -324,6 +333,115 @@ fn mob_meta( )); } } + // Frog.DATA_VARIANT_ID, Pig's, Cow's, Chicken's and ZombieNautilus's + // (after the entries of their parents): registry holders. + "minecraft:frog" + | "minecraft:pig" + | "minecraft:cow" + | "minecraft:chicken" + | "minecraft:zombie_nautilus" => { + let (index, serializer, registry) = match kind { + "minecraft:frog" => (18, serializer::FROG_VARIANT, "minecraft:frog_variant"), + "minecraft:pig" => (19, serializer::PIG_VARIANT, "minecraft:pig_variant"), + "minecraft:cow" => (18, serializer::COW_VARIANT, "minecraft:cow_variant"), + "minecraft:chicken" => { + (18, serializer::CHICKEN_VARIANT, "minecraft:chicken_variant") + } + _ => ( + 21, + serializer::ZOMBIE_NAUTILUS_VARIANT, + "minecraft:zombie_nautilus_variant", + ), + }; + let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant); + if let Some(v) = id(registry, name.trim_start_matches("minecraft:")) { + meta.push((index, serializer, Value::Id(v))); + } + } + // Axolotl.DATA_VARIANT (after AgeableMob's two), Fox.DATA_TYPE_ID, + // Rabbit.DATA_TYPE_ID and Parrot.DATA_VARIANT_ID (after + // TamableAnimal's two and its flags and owner). + "minecraft:axolotl" | "minecraft:fox" | "minecraft:rabbit" | "minecraft:parrot" => { + let index = if kind == "minecraft:parrot" { 20 } else { 18 }; + if e.variant != 0 { + meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } + // Panda.MAIN_GENE_ID and HIDDEN_GENE_ID (after its three counters). + "minecraft:panda" => { + if e.variant != 0 { + meta.push((21, serializer::BYTE, Value::Byte(e.variant as i8))); + } + if e.variant2 != 0 { + meta.push((22, serializer::BYTE, Value::Byte(e.variant2 as i8))); + } + } + // Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and + // DATA_ANGER_END_TIME: the texture shows the nectar and the anger. + "minecraft:bee" => { + let bee = horizon_client::mobs::bee::get(m); + let flags = bee.map_or(0, |b| b.flags); + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags as i8))); + } + defaults.push((18, serializer::BYTE, Value::Byte(0))); + let anger_end = bee.map_or(-1, |b| b.anger_end); + if anger_end != -1 { + meta.push((19, serializer::LONG, Value::Long(anger_end))); + } + defaults.push((19, serializer::LONG, Value::Long(-1))); + } + // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0, + // medium 1, large 2; medium is the data's default, so always sent), + // Pufferfish.PUFF_STATE and TropicalFish.DATA_ID_TYPE_VARIANT: the + // pattern's packed id (size, then index << 8), base colour << 16 and + // pattern colour << 24. + "minecraft:salmon" => { + meta.push((17, serializer::INT, Value::Int(i32::from(e.variant.min(2))))); + } + "minecraft:pufferfish" => { + if e.size > 0 { + meta.push((17, serializer::INT, Value::Int(e.size))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } + "minecraft:tropical_fish" => { + let pattern = e.variant.min(11); + let packed = i32::from(pattern >= 6) + | i32::from(pattern % 6) << 8 + | i32::from(e.variant2 & 15) << 16 + | i32::from(e.variant3 & 15) << 24; + if packed != 0 { + meta.push((17, serializer::INT, Value::Int(packed))); + } + } + // CopperGolem.DATA_WEATHER_STATE: unaffected 0 to oxidized 3, and it + // goes back down when the golem is scraped. + "minecraft:copper_golem" => { + if e.variant != 0 { + meta.push(( + 16, + serializer::WEATHERING_COPPER_STATE, + Value::Id(i32::from(e.variant.min(3))), + )); + } + defaults.push((16, serializer::WEATHERING_COPPER_STATE, Value::Id(0))); + } + // Ghast.DATA_IS_CHARGING: the shooting texture. + "minecraft:ghast" => { + if e.flag { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + } + // WitherBoss.DATA_ID_INV (after the three head targets): the + // invulnerable ticks, the blinking texture and the growing scale. + "minecraft:wither" => { + if e.counter > 0 { + meta.push((19, serializer::INT, Value::Int(e.counter))); + } + defaults.push((19, serializer::INT, Value::Int(0))); + } // AbstractCubeMob.ID_SIZE. "minecraft:slime" | "minecraft:magma_cube" => { if e.size > 1 { @@ -877,7 +995,14 @@ impl Game<'_> { e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; - mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); + mob_meta( + m, + hub, + player_entity, + self.world.game_time, + &mut e.meta, + &mut e.defaults, + ); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); e.leash = leash; diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..f7ef94da9 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,9 +4,9 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, tame}; +use horizon_client::mobs::{Mob, Species, Who, bat, bee, finalize, tame}; use horizon_protocol::entity_data::Value; -use horizon_protocol::registry::Builtin; +use horizon_protocol::registry::{Builtin, Dynamic}; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). @@ -79,6 +79,54 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => { m.extra.size = (*size).clamp(1, 127); } + // AbstractHorse's flags take 18. Horse.DATA_ID_TYPE_VARIANT: the + // colour in the low byte, the markings in the next. + (Species::Horse, 19, Value::Int(v)) => { + m.extra.variant = (v & 0xFF).clamp(0, 6) as u8; + m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8; + } + // AbstractChestedHorse.DATA_ID_CHEST, then Llama.DATA_STRENGTH_ID + // and DATA_VARIANT_ID. + ( + Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama, + 19, + Value::Bool(chested), + ) => m.extra.chested = *chested, + (Species::Llama | Species::TraderLlama, 20, Value::Int(strength)) => { + m.extra.variant2 = (*strength).clamp(1, 5) as u8; + } + (Species::Llama | Species::TraderLlama, 21, Value::Int(variant)) => { + m.extra.variant = (*variant).clamp(0, 3) as u8; + } + // Axolotl.DATA_VARIANT (lucy 0 to blue 4), Fox.DATA_TYPE_ID (red + // 0, snow 1) and Parrot.DATA_VARIANT_ID (after TamableAnimal's + // flags and owner). + (Species::Axolotl, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, + (Species::Fox, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 1) as u8, + (Species::Parrot, 20, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, + // Rabbit.DATA_TYPE_ID: the killer bunny's 99 has no model here. + (Species::Rabbit, 18, Value::Int(t)) if (0..=5).contains(t) => { + m.extra.variant = *t as u8; + } + // Panda.MAIN_GENE_ID and HIDDEN_GENE_ID (after the three counters). + (Species::Panda, 21, Value::Byte(gene)) => m.extra.variant = (*gene).clamp(0, 6) as u8, + (Species::Panda, 22, Value::Byte(gene)) => m.extra.variant2 = (*gene).clamp(0, 6) as u8, + // Bee.DATA_FLAGS_ID and DATA_ANGER_END_TIME (after Animal's). + (Species::Bee, 18, Value::Byte(flags)) => bee::set_synced(m, Some(*flags as u8), None), + (Species::Bee, 19, Value::Long(end)) => bee::set_synced(m, None, Some(*end)), + // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0 + // to large 2), Pufferfish.PUFF_STATE and + // TropicalFish.DATA_ID_TYPE_VARIANT. + (Species::Salmon, 17, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 2) as u8, + (Species::Pufferfish, 17, Value::Int(state)) => m.extra.size = (*state).clamp(0, 2), + (Species::TropicalFish, 17, Value::Int(v)) => tropical_fish(m, *v), + // Ghast.DATA_IS_CHARGING and WitherBoss.DATA_ID_INV. + (Species::Ghast, 16, Value::Bool(charging)) => m.extra.flag = *charging, + (Species::Wither, 19, Value::Int(ticks)) => m.extra.counter = (*ticks).max(0), + // CopperGolem.DATA_WEATHER_STATE: the oxidation the texture shows. + (Species::CopperGolem, 16, Value::Id(state)) => { + m.extra.variant = (*state).clamp(0, 3) as u8; + } // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, @@ -100,6 +148,56 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } } +/// A tropical fish's packed variant: the pattern's id (the size, then the +/// index << 8), the base colour << 16 and the pattern colour << 24. Here the +/// pattern is 0 to 5 for the small ones and 6 to 11 for the large ones. +fn tropical_fish(m: &mut Mob, packed: i32) { + let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF); + // TropicalFish.Pattern.byId: an unknown id is a kob. + m.extra.variant = if size <= 1 && index < 6 { + (size * 6 + index) as u8 + } else { + 0 + }; + m.extra.variant2 = ((packed >> 16) & 0xFF) as u8 & 15; + m.extra.variant3 = ((packed >> 24) & 0xFF) as u8 & 15; +} + +/// The values of one SetEntityData packet that name an entry of a +/// synchronized registry (the variants of the cat, wolf, frog, pig, cow, +/// chicken and zombie nautilus) or count game time (a wolf's anger). +/// `game_time` is the client level's. +fn apply_registry_data( + m: &mut Mob, + values: &[(u8, i32, Value)], + registries: &Dynamic, + game_time: i64, +) { + let species = m.species(); + for (index, _, value) in values { + let registry = match (species, *index, value) { + (Species::Cat, 20, Value::Id(_)) => "minecraft:cat_variant", + (Species::Wolf, 23, Value::Id(_)) => "minecraft:wolf_variant", + (Species::Frog, 18, Value::Id(_)) => "minecraft:frog_variant", + (Species::Pig, 19, Value::Id(_)) => "minecraft:pig_variant", + (Species::Cow, 18, Value::Id(_)) => "minecraft:cow_variant", + (Species::Chicken, 18, Value::Id(_)) => "minecraft:chicken_variant", + (Species::ZombieNautilus, 21, Value::Id(_)) => "minecraft:zombie_nautilus_variant", + // Wolf.DATA_ANGER_END_TIME: the angry texture while it lies ahead. + (Species::Wolf, 22, Value::Long(end)) => { + m.extra.anger = (end - game_time).clamp(0, i64::from(i32::MAX)) as i32; + continue; + } + _ => continue, + }; + if let Value::Id(id) = value + && let Some(name) = registries.name(registry, *id) + { + m.extra.variant = finalize::variant_index(species, name); + } + } +} + /// VillagerData as the network sends it: the type and the profession by /// their built-in registry ids, then the level. fn villager_data(m: &mut Mob, data: &[i32], builtin: &Builtin) { @@ -130,6 +228,7 @@ impl Game<'_> { }; if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { apply(m, values, &r.builtin, r.entity_id); + apply_registry_data(m, values, &r.registries, self.world.game_time); } } } diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index 27d8e7c84..374bfef7e 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -103,6 +103,17 @@ pub fn has_stung(m: &Mob) -> bool { pub fn rolling(m: &Mob) -> bool { flag(m, FLAG_ROLL) } +/// A client's bee from the server's `DATA_FLAGS_ID` and `DATA_ANGER_END_TIME` +/// (the texture and the roll read them). +pub fn set_synced(m: &mut Mob, flags: Option, anger_end: Option) { + let b = st(m); + if let Some(flags) = flags { + b.flags = flags; + } + if let Some(anger_end) = anger_end { + b.anger_end = anger_end; + } +} /// `Bee.setHasNectar`: nectar resets the time without it. pub fn set_has_nectar(m: &mut Mob, value: bool) { if value { From 400d9e61157d13ca60a50847180892474ce34cc0 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:11:56 +0100 Subject: [PATCH 120/221] Show goats' lost horns and let them lower their head and ram --- crates/horizon-client/src/game/creatures.rs | 13 + crates/horizon-client/src/game/lan.rs | 10 + crates/horizon-client/src/game/lan_mobs.rs | 4 + .../src/game/remote_mob_data.rs | 4 + crates/horizon-client/src/mobs.rs | 10 + crates/horizon-client/src/mobs/ai.rs | 4 + crates/horizon-client/src/mobs/body_anim.rs | 8 +- crates/horizon-client/src/mobs/finalize.rs | 2 +- crates/horizon-client/src/mobs/goat.rs | 443 ++++++++++++++++++ crates/horizon-client/src/mobs/sync.rs | 6 +- 10 files changed, 498 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-client/src/mobs/goat.rs diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0ea8dd4d0..829f5e629 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -947,6 +947,19 @@ impl Game<'_> { } } } + MobEvent::Knockback { + target, + power, + x, + z, + } => match target { + Who::Player => self.knock_back_player(power, x, z), + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.knockback(power, x, z); + } + } + }, MobEvent::Wololo { mob } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { // DyeColor.RED. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6e00df8fe..168abc8fb 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -399,6 +399,16 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(16))); } + // Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN (after + // DATA_IS_SCREAMING_GOAT): both true by default. + "minecraft:goat" => { + for (index, lost) in [(19, e.lost_horns[0]), (20, e.lost_horns[1])] { + if lost { + meta.push((index, serializer::BOOLEAN, Value::Bool(false))); + } + defaults.push((index, serializer::BOOLEAN, Value::Bool(true))); + } + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 6527f1015..1cbed3c93 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -70,6 +70,10 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { target: Who::Player, .. } + | MobEvent::Knockback { + target: Who::Player, + .. + } | MobEvent::Ignite { target: Who::Player, .. diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index bd452ba85..5f9e8b436 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -92,6 +92,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Sniffer, 18, Value::Id(state)) => { sniffer::set_state(m, (*state).clamp(0, 6) as u8); } + // Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN: the model hides + // a horn the goat lost. + (Species::Goat, 19, Value::Bool(has)) => m.extra.lost_horns[0] = !*has, + (Species::Goat, 20, Value::Bool(has)) => m.extra.lost_horns[1] = !*has, // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID. (Species::Shulker, 16, Value::Id(face)) => m.extra.variant3 = (*face).clamp(0, 5) as u8, (Species::Shulker, 17, Value::Byte(peek)) => m.extra.counter = i32::from(*peek), diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3daeeb10a..c0797e3e2 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -33,6 +33,7 @@ pub mod farm; pub mod finalize; pub mod gear; pub mod goals; +pub mod goat; pub mod golem; pub mod guardian; pub mod happy_ghast; @@ -771,6 +772,8 @@ pub struct Extra { /// A goat's `IsScreamingGoat` and the horns it lost (left, right). pub screaming: bool, pub lost_horns: [bool; 2], + /// A goat's lowered head and ram behaviours. + pub goat: goat::State, /// Attribute bases and permanent modifiers set by `finalizeSpawn`. pub attributes: Option>, /// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry). @@ -1001,6 +1004,13 @@ pub enum MobEvent { amount: f32, source: Damage, }, + /// `LivingEntity.knockback(power, x, z)`: pushed away from the direction. + Knockback { + target: Who, + power: f64, + x: f64, + z: f64, + }, /// Set another mob's attack target (HurtByTargetGoal alerts). SetTarget { mob: u32, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 258c1ccc7..dc5593ae8 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -186,6 +186,9 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Turtle { super::turtle::register(m); } + if m.species() == Species::Goat { + super::goat::register(m); + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -1016,6 +1019,7 @@ fn species_ai_step( } Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events), + Species::Goat => super::goat::tick(m), Species::Turtle => super::turtle::ai_step(m, w, events), Species::Sheep if m.extra.anim_ticks > 0 => { m.extra.anim_ticks -= 1; diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index bbb44c5ab..8acf5a002 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -59,11 +59,11 @@ pub struct Goat { pub ramming_x_head_rot: f32, } impl Goat { - pub fn from_mob(_m: &Mob) -> Self { + pub fn from_mob(m: &Mob) -> Self { Self { - left_horn: true, - right_horn: true, - ramming_x_head_rot: 0.0, + left_horn: !m.extra.lost_horns[0], + right_horn: !m.extra.lost_horns[1], + ramming_x_head_rot: super::goat::ramming_x_head_rot(m), } } } diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 6e5daff1f..ce8ede539 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1677,7 +1677,7 @@ impl Ctx<'_, L, R> { let jump = self.uniform(600, 1200); set_memory(m, "long_jump_cooldown", i64::from(jump), i64::MAX); let ram = self.uniform(600, 6000); - set_memory(m, "ram_cooldown", i64::from(ram), i64::MAX); + m.extra.goat.ram_cooldown = ram; m.extra.screaming = self.random.next_double() < 0.02; age_boundary_reached(m); if !m.is_baby() && self.float() < 0.1 { diff --git a/crates/horizon-client/src/mobs/goat.rs b/crates/horizon-client/src/mobs/goat.rs new file mode 100644 index 000000000..647d6f789 --- /dev/null +++ b/crates/horizon-client/src/mobs/goat.rs @@ -0,0 +1,443 @@ +//! Goats (`Goat`, `GoatAi`): the lowered head (`lowerHeadTick`, entity +//! events 58 and 59) and the ram activity: `PrepareRamNearestTarget` picks +//! the nearest living thing it can see, walks to a spot four to seven +//! blocks away in a straight line and waits there 20 ticks with its head +//! down; `RamTarget` then charges at it, knocks it back, or breaks a horn +//! on a log, stone or ore. Both are one goal here. +use super::{ + Damage, Mob, MobEvent, MobWorld, Who, + goals::{Cx, Goal, LOOK, MOVE, goal_clone}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +/// `GoatAi.TIME_BETWEEN_RAMS` and `TIME_BETWEEN_RAMS_SCREAMER`. +const RAMS: (i32, i32) = (600, 6000); +const RAMS_SCREAMER: (i32, i32) = (100, 300); +const RAM_PREPARE_TIME: i64 = 20; +const MIN_RAM_DISTANCE: i32 = 4; +const MAX_RAM_DISTANCE: i32 = 7; +/// `PrepareRamNearestTarget.TIME_OUT_DURATION` and `RamTarget`'s. +const PREPARE_TIME_OUT: i32 = 160; +const RAM_TIME_OUT: i32 = 200; +/// `NEAREST_VISIBLE_LIVING_ENTITIES` reaches 16 blocks. +const SENSE_RANGE: f64 = 16.0; + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum Phase { + #[default] + Done, + Prepare, + /// `RAM_TARGET` is set; `RamTarget` starts on the next tick. + RamStart, + Ram, +} +#[derive(Clone, Copy, Debug)] +struct Candidate { + start: [i32; 3], + target_pos: [i32; 3], + target: Who, +} + +/// `RAM_COOLDOWN_TICKS`, the lowered head and the ram behaviours' state. +#[derive(Clone, Debug, Default)] +pub struct State { + /// `RAM_COOLDOWN_TICKS`: 0 when absent. + pub ram_cooldown: i32, + lower_head_tick: i32, + lowering_head: bool, + phase: Phase, + candidate: Option, + reached_at: Option, + /// `RAM_TARGET`, and the direction of the charge. + ram_target: Option, + ram_direction: Vec3, + time: i32, +} + +pub fn register(m: &mut Mob) { + m.ai.goals.add(2, Ram); +} + +/// `Goat.handleEntityEvent`: 58 lowers the head, 59 raises it. +pub fn entity_event(m: &mut Mob, event: u8) { + match event { + 58 => m.extra.goat.lowering_head = true, + 59 => m.extra.goat.lowering_head = false, + _ => {} + } +} +/// `Goat.aiStep`'s `lowerHeadTick`; a client runs it too. +pub fn tick(m: &mut Mob) { + let g = &mut m.extra.goat; + g.lower_head_tick += if g.lowering_head { 1 } else { -2 }; + g.lower_head_tick = g.lower_head_tick.clamp(0, 20); + if g.ram_cooldown > 0 { + g.ram_cooldown -= 1; + } +} +/// `Goat.getRammingXHeadRot`. +pub fn ramming_x_head_rot(m: &Mob) -> f32 { + let max = if m.is_baby() { 52.5_f32 } else { 30.0 }; + m.extra.goat.lower_head_tick as f32 / 20.0 * max * (std::f32::consts::PI / 180.0) +} +/// A server's `level.broadcastEntityEvent(goat, 58 or 59)`, sent when it +/// changes what the goat does. +fn lower_head(m: &mut Mob, events: &mut Vec, lower: bool) { + if m.extra.goat.lowering_head != lower { + let event: i8 = if lower { 58 } else { 59 }; + entity_event(m, event as u8); + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::EntityEvent { + mob: m.id, + event, + at, + }); + } +} +fn between(m: &mut Mob, (min, max): (i32, i32)) -> i32 { + m.random.next_int_between_inclusive(min, max).unwrap_or(min) +} +fn rams(m: &Mob) -> (i32, i32) { + if m.extra.screaming { + RAMS_SCREAMER + } else { + RAMS + } +} +fn block_of(p: Vec3) -> [i32; 3] { + [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] +} +fn play(m: &Mob, events: &mut Vec, sound: &'static str, pitch: f32) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, 1.0, pitch)); + } +} + +/// `PrepareRamNearestTarget.isWalkableBlock`. +fn walkable(m: &Mob, w: &MobWorld, p: [i32; 3]) -> bool { + m.stable_destination(w, p) && m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0 +} +/// `PrepareRamNearestTarget.calculateRammingStartPosition`. +fn ramming_start(m: &mut Mob, w: &MobWorld, target: [i32; 3]) -> Option<[i32; 3]> { + if !walkable(m, w, target) { + return None; + } + // Direction.Plane.HORIZONTAL: north, east, south, west. + let mut starts = Vec::new(); + for (dx, dz) in [(0, -1), (1, 0), (0, 1), (-1, 0)] { + let mut p = target; + for _ in 0..MAX_RAM_DISTANCE { + p = [p[0] + dx, p[1], p[2] + dz]; + if !walkable(m, w, p) { + p = [p[0] - dx, p[1], p[2] - dz]; + break; + } + } + let manhattan = + (p[0] - target[0]).abs() + (p[1] - target[1]).abs() + (p[2] - target[2]).abs(); + if manhattan >= MIN_RAM_DISTANCE { + starts.push(p); + } + } + let here = block_of(m.position); + let sqr = |p: &[i32; 3]| { + (0..3) + .map(|i| i64::from(p[i] - here[i]).pow(2)) + .sum::() + }; + starts.sort_by_key(sqr); + starts + .into_iter() + .find(|&p| m.create_path_to(w, p, 0).is_some_and(|path| path.reached)) +} +/// `PrepareRamNearestTarget.chooseRamPosition`. +fn choose(m: &mut Mob, w: &MobWorld, target: Who) { + let g = &mut m.extra.goat; + g.reached_at = None; + let Some(t) = w.target_info(target) else { + g.candidate = None; + return; + }; + let target_pos = block_of(t.position); + m.extra.goat.candidate = ramming_start(m, w, target_pos).map(|start| Candidate { + start, + target_pos, + target, + }); +} +/// The nearest living thing the goat sees that `RAM_TARGET_CONDITIONS` +/// allow: not a goat, a player who is not creative or a spectator. +fn nearest_target(m: &mut Mob, w: &MobWorld) -> Option { + let mut best: Option<(Who, f64)> = None; + if let Some(p) = &w.player + && p.alive + && !p.creative + && !p.spectator + && !p.allies.contains(&m.id) + && m.distance_sqr(p.position) <= SENSE_RANGE * SENSE_RANGE + && m.sees(w, Who::Player) + { + best = Some((Who::Player, m.distance_sqr(p.position))); + } + let id = m.id; + let mobs: Vec<(u32, f64)> = w + .nearby(m.position, SENSE_RANGE, |s| { + s.id != id && s.species != super::Species::Goat && !s.playing_dead + }) + .map(|s| (s.id, m.distance_sqr(s.position))) + .collect(); + for (mob, d) in mobs { + if best.is_none_or(|b| d < b.1) && m.sees(w, Who::Mob(mob)) { + best = Some((Who::Mob(mob), d)); + } + } + best.map(|b| b.0) +} + +/// `PrepareRamNearestTarget` and `RamTarget` of the ram activity. +#[derive(Clone, Debug)] +struct Ram; +impl Goal for Ram { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + // The ram activity needs the cooldown to be over (it also waits for + // no tempting player and no breed target, which goats lack here). + m.extra.goat.ram_cooldown <= 0 + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let g = &m.extra.goat; + match g.phase { + Phase::Done => false, + Phase::Prepare => { + g.time <= PREPARE_TIME_OUT + && g.candidate + .is_some_and(|c| cx.w.target_info(c.target).is_some_and(|t| t.alive)) + } + Phase::RamStart | Phase::Ram => g.ram_target.is_some() && g.time <= RAM_TIME_OUT, + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.goat.phase = Phase::Prepare; + m.extra.goat.time = 0; + m.extra.goat.reached_at = None; + m.extra.goat.candidate = None; + if let Some(target) = nearest_target(m, cx.w) { + choose(m, cx.w, target); + } + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + match m.extra.goat.phase { + // PrepareRamNearestTarget.stop: no ram target, so the head comes + // up and the cooldown starts. + Phase::Prepare => { + lower_head(m, cx.events, false); + m.extra.goat.ram_cooldown = rams(m).0; + } + // RamTarget.finishRam (also what its timeout leaves undone). + Phase::RamStart | Phase::Ram => finish_ram(m, cx.events), + Phase::Done => {} + } + m.extra.goat.phase = Phase::Done; + m.extra.goat.candidate = None; + } + fn every_tick(&self) -> bool { + true + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + m.extra.goat.time += 1; + match m.extra.goat.phase { + Phase::Prepare => prepare_tick(m, cx), + Phase::RamStart => { + // RamTarget.start: charge from here at the ram target. + let (Some(target), here) = (m.extra.goat.ram_target, block_of(m.position)) else { + return; + }; + let d = Vec3::new( + f64::from(here[0]) - target.x, + 0.0, + f64::from(here[2]) - target.z, + ); + m.extra.goat.ram_direction = d.normalize(); + m.extra.goat.phase = Phase::Ram; + m.extra.goat.time = 0; + m.nav_move_to_entity(cx.w, [target.x, target.y, target.z], 0, 3.0); + ram_tick(m, cx); + } + Phase::Ram => ram_tick(m, cx), + Phase::Done => {} + } + } +} +/// `PrepareRamNearestTarget.tick`. +fn prepare_tick(m: &mut Mob, cx: &mut Cx) { + let Some(c) = m.extra.goat.candidate else { + return; + }; + let Some(t) = cx.w.target_info(c.target) else { + return; + }; + m.look_at([t.position.x, t.eye_y, t.position.z]); + let now = m.age as i32; + let at = [ + f64::from(c.start[0]) + 0.5, + f64::from(c.start[1]), + f64::from(c.start[2]) + 0.5, + ]; + if m.ai.nav.is_done() && block_of(m.position) != c.start { + m.nav_move_to_entity(cx.w, at, 0, 1.25); + } + if block_of(t.position) != c.target_pos { + // The target moved: the head comes up and a new spot is chosen. + lower_head(m, cx.events, false); + m.nav_stop(); + choose(m, cx.w, c.target); + } else if block_of(m.position) == c.start { + lower_head(m, cx.events, true); + let since = *m.extra.goat.reached_at.get_or_insert(now); + if i64::from(now - since) >= RAM_PREPARE_TIME { + // getEdgeOfBlock. + let (x, z) = ( + f64::from(c.target_pos[0]) + + 0.5 + + 0.5 * f64::from(sign(c.target_pos[0] - c.start[0])), + f64::from(c.target_pos[2]) + + 0.5 + + 0.5 * f64::from(sign(c.target_pos[2] - c.start[2])), + ); + m.extra.goat.ram_target = Some(Vec3::new(x, f64::from(c.target_pos[1]), z)); + let sound = if m.extra.screaming { + "entity.goat.screaming.prepare_ram" + } else { + "entity.goat.prepare_ram" + }; + let pitch = m.voice_pitch(); + play(m, cx.events, sound, pitch); + m.extra.goat.candidate = None; + m.extra.goat.phase = Phase::RamStart; + } + } +} +fn sign(v: i32) -> i32 { + v.signum() +} +/// `RamTarget.tick`. +fn ram_tick(m: &mut Mob, cx: &mut Cx) { + let impact = if m.extra.screaming { + "entity.goat.screaming.ram_impact" + } else { + "entity.goat.ram_impact" + }; + let from = [m.position.x, m.position.y, m.position.z]; + if let Some(target) = rammed(m, cx.w) { + // hurtServer by `noAggroMobAttack`, then the knockback. + let amount = m.attrs.attack_damage; + match target { + Who::Player => cx.events.push(MobEvent::DamagePlayer { + amount, + from, + kind: "minecraft:mob_attack_no_aggro", + }), + Who::Mob(id) => cx.events.push(MobEvent::AttackMob { + target: id, + amount, + source: Damage::mob(m.id, from), + }), + } + let level = |effect: &str| { + m.extra + .effects + .iter() + .find(|e| e.0 == effect) + .map_or(0, |e| e.2 + 1) + }; + let boost = 0.25 * (level("minecraft:speed") - level("minecraft:slowness")) as f32; + let factor = (m.ai.speed * 1.65).clamp(0.2, 3.0) + boost; + let force = if m.is_baby() { 1.0 } else { 2.5 }; + let d = m.extra.goat.ram_direction; + cx.events.push(MobEvent::Knockback { + target, + power: f64::from(factor * force), + x: d.x, + z: d.z, + }); + finish_ram(m, cx.events); + play(m, cx.events, impact, 1.0); + } else if rammed_horn_block(m, cx.w) { + play(m, cx.events, impact, 1.0); + if drop_horn(m, cx.events) { + play(m, cx.events, "entity.goat.horn_break", 1.0); + } + finish_ram(m, cx.events); + } else if m.ai.nav.is_done() || m.extra.goat.ram_target.is_none() { + // The walk target is gone: the charge ended where it could. + finish_ram(m, cx.events); + } +} +/// The first living thing in the goat's box that `RAM_TARGET_CONDITIONS` +/// allow. +fn rammed(m: &Mob, w: &MobWorld) -> Option { + let bounds = m.bounds(); + if let Some(p) = &w.player + && p.alive + && !p.creative + && !p.spectator + && !p.allies.contains(&m.id) + && p.bounds.intersects(bounds) + { + return Some(Who::Player); + } + w.others_near(bounds) + .find(|s| { + s.id != m.id + && s.alive + && s.species != super::Species::Goat + && !s.playing_dead + && s.bounds.intersects(bounds) + }) + .map(|s| Who::Mob(s.id)) +} +/// `RamTarget.hasRammedHornBreakingBlock`: the block one step ahead, or the +/// one above it, snaps a horn. +fn rammed_horn_block(m: &Mob, w: &MobWorld) -> bool { + let ahead = Vec3::new(m.velocity.x, 0.0, m.velocity.z).normalize(); + let at = block_of(m.position.add_vector(ahead)); + let snaps = + |p: [i32; 3]| w.has_tag("minecraft:snaps_goat_horn", w.block_name(p[0], p[1], p[2])); + snaps(at) || snaps([at[0], at[1] + 1, at[2]]) +} +/// `Goat.dropHorn`: one of the horns it still has comes off and drops. +fn drop_horn(m: &mut Mob, events: &mut Vec) -> bool { + if m.is_baby() { + return false; + } + let [left_lost, right_lost] = m.extra.lost_horns; + if left_lost && right_lost { + return false; + } + let lose_left = if left_lost { + false + } else if right_lost { + true + } else { + m.random.next_boolean() + }; + m.extra.lost_horns[usize::from(!lose_left)] = true; + events.push(MobEvent::DropItem { + item: "minecraft:goat_horn".into(), + count: 1, + at: [m.position.x, m.position.y, m.position.z], + }); + true +} +/// `RamTarget.finishRam`. +fn finish_ram(m: &mut Mob, events: &mut Vec) { + lower_head(m, events, false); + let wait = rams(m); + m.extra.goat.ram_cooldown = between(m, wait); + m.extra.goat.ram_target = None; + m.extra.goat.phase = Phase::Done; +} diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs index d1c5b6609..e187ee89c 100644 --- a/crates/horizon-client/src/mobs/sync.rs +++ b/crates/horizon-client/src/mobs/sync.rs @@ -15,7 +15,7 @@ //! them in `entity_event`; //! - run its client side animation in `client_tick`, sharing the function //! with the server's `ai_step` where the server computes the same. -use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; +use super::{Mob, Species, breeze, camel, goat, shulker, sniffer, warden}; // `Pose.id` of the poses mobs take. pub const STANDING: u8 = 0; @@ -60,6 +60,7 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { Species::Breeze => breeze::ai_step(m), Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), Species::Shulker => shulker::client_tick(m), + Species::Goat => goat::tick(m), _ => {} } } @@ -67,6 +68,9 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { /// `handleEntityEvent` of the mob types that start animations by an event /// (`ClientboundEntityEventPacket` for a mob of a client). pub fn entity_event(m: &mut Mob, event: u8) { + if m.species() == Species::Goat { + goat::entity_event(m, event); + } let age = m.age as f32; if m.species() == Species::Warden { match event { From da57350af515f17fe7c17228cedae8f77e72c4f6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Mon, 26 Oct 2026 23:19:43 +0100 Subject: [PATCH 121/221] Pandas: genes, sit, roll, lie on back, sneeze and unhappy states, synced to clients A panda now has vanilla's states: it sits to eat bamboo or cake it picks up or is given, a lazy one lies on its back, a playful one or a cub rolls over, a cub sneezes, and a panda that is fed with no bamboo around sulks. A worried panda sits and shivers in a thunderstorm. The genes show in its coat, pass to its young, and are saved. The flags, counters and genes go to clients as entity data, and the model, the item in its mouth, the crumbs and the sneeze are drawn from them, in game and in a LAN guest's window. --- crates/horizon-client/src/entity_nbt.rs | 17 + crates/horizon-client/src/game.rs | 1 + .../horizon-client/src/game/client_ambient.rs | 1 + crates/horizon-client/src/game/creatures.rs | 25 +- crates/horizon-client/src/game/lan.rs | 23 + crates/horizon-client/src/game/mob_blocks.rs | 12 +- crates/horizon-client/src/game/pandas.rs | 165 +++ crates/horizon-client/src/game/remote.rs | 11 +- .../src/game/remote_mob_data.rs | 10 +- crates/horizon-client/src/mobs.rs | 7 + crates/horizon-client/src/mobs/ai.rs | 31 + crates/horizon-client/src/mobs/body_anim.rs | 2 +- crates/horizon-client/src/mobs/control.rs | 6 + crates/horizon-client/src/mobs/drops.rs | 8 +- crates/horizon-client/src/mobs/finalize.rs | 10 +- crates/horizon-client/src/mobs/goals.rs | 9 + crates/horizon-client/src/mobs/panda.rs | 1090 +++++++++++++++++ crates/horizon-client/src/mobs/render.rs | 11 + 18 files changed, 1418 insertions(+), 21 deletions(-) create mode 100644 crates/horizon-client/src/game/pandas.rs create mode 100644 crates/horizon-client/src/mobs/panda.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 161ca12e9..252eaf512 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -259,6 +259,18 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.entry("sound_variant".into()) .or_insert_with(|| string("minecraft:classic")); } + "minecraft:panda" => { + use crate::mobs::panda::GENES; + for (key, gene) in [ + ("MainGene", m.extra.variant), + ("HiddenGene", m.extra.variant2), + ] { + map.insert( + key.into(), + string(GENES[usize::from(gene).min(GENES.len() - 1)]), + ); + } + } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { map.insert( "IsImmuneToZombification".into(), @@ -808,6 +820,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - .unwrap_or(0) as u8; } } + if m.species() == crate::mobs::Species::Panda { + let gene = |key| text(tag.get(key)).map_or(0, |n| crate::mobs::panda::gene_from_name(&n)); + m.extra.variant = gene("MainGene"); + m.extra.variant2 = gene("HiddenGene"); + } if m.species() == crate::mobs::Species::Wolf { let health = m.health; m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index db49087b2..15d6ddbd9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -127,6 +127,7 @@ mod packs; mod pad; mod pad_menu; mod paintings; +mod pandas; mod passengers; mod persist; mod perspective; diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index a10c6da49..79575723f 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -33,5 +33,6 @@ impl Game<'_> { } } self.eye_particles(); + self.panda_effects(); } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index f6961ab13..2255fa2bd 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -670,6 +670,7 @@ impl Game<'_> { self.tick_projectiles()?; self.tick_fangs(); self.tick_allays(); + self.tick_pandas(); self.tick_breeze_effects(); self.tick_sniffer_effects(); self.piglin_pickups(); @@ -1331,9 +1332,14 @@ impl Game<'_> { m.ai.aggressive |= aggressive; } } + MobEvent::PandaSneezed { mob } => self.panda_sneezed(mob), MobEvent::GiftLoot { mob, table, at } => { - // Turtle.ageBoundaryReached: only with mob loot on. - if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops") + // Turtle.ageBoundaryReached and Panda.afterSneeze: only + // with mob loot on. + if matches!( + table, + "minecraft:gameplay/turtle_grow" | "minecraft:gameplay/panda_sneeze" + ) && !self.ui.rules.bool("mob_drops") { continue; } @@ -1570,6 +1576,13 @@ impl Game<'_> { self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); return; } + // Panda.getBreedOffspring: genes from both parents. + if p.species() == Species::Panda { + horizon_client::mobs::panda::inherit(child, &p, q.as_ref().unwrap_or(&p)); + let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32; + self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp); + return; + } // Nautilus.getBreedOffspring: a tame parent's baby is tame too. if p.species() == Species::Nautilus && p.extra.tame { child.extra.tame = true; @@ -2687,6 +2700,14 @@ impl Game<'_> { let creative = self.creative; // The hand's slot (Player.interactOn passes the hand). let selected = self.held_slot(); + // Panda.mobInteract: bamboo, or a click on a panda lying on its back. + if self.mobs[index].species() == Species::Panda && self.mobs[index].alive() { + let taken = self.interact_panda(index, &item); + if taken { + self.swing_arm(); + } + return Ok(taken); + } if self.interact_zombie_villager(index, &item) { return Ok(true); } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index e39fa3a68..78fa493bf 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -350,6 +350,29 @@ fn mob_meta( } defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } + // Panda: UNHAPPY_COUNTER, SNEEZE_COUNTER and EAT_COUNTER (after + // AgeableMob's two), MAIN_GENE_ID, HIDDEN_GENE_ID and DATA_ID_FLAGS; + // the client animates the states from them. + "minecraft:panda" => { + let (flags, counters) = horizon_client::mobs::panda::get(m) + .map_or((0, [0; 3]), |s| (s.flags, [s.unhappy, s.sneeze, s.eat])); + for (index, value) in (18..).zip(counters) { + if value != 0 { + meta.push((index, serializer::INT, Value::Int(value))); + } + defaults.push((index, serializer::INT, Value::Int(0))); + } + for (index, gene) in [(21, e.variant), (22, e.variant2)] { + if gene != 0 { + meta.push((index, serializer::BYTE, Value::Byte(gene as i8))); + } + defaults.push((index, serializer::BYTE, Value::Byte(0))); + } + if flags != 0 { + meta.push((23, serializer::BYTE, Value::Byte(flags as i8))); + } + defaults.push((23, serializer::BYTE, Value::Byte(0))); + } // SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose. "minecraft:evoker" | "minecraft:illusioner" => { if e.variant2 != 0 { diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 083c96a66..f0a485eb6 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -312,13 +312,15 @@ impl Game<'_> { owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item; owner.crossbow_charge_duration = 25; } - let context = if left { - horizon_assets::item_model::DisplayContext::ThirdPersonLeftHand - } else { - horizon_assets::item_model::DisplayContext::ThirdPersonRightHand + use horizon_assets::item_model::DisplayContext as Context; + // PandaHoldsItemLayer shows the item as it lies on the ground. + let (context, ordinal) = match (mob.species(), left) { + (Species::Panda, _) => (Context::Ground, 7), + (_, true) => (Context::ThirdPersonLeftHand, 1), + (_, false) => (Context::ThirdPersonRightHand, 2), }; // `updateForLiving`: seeded by the entity id plus the context ordinal. - let seed = mob.id as i32 + if left { 1 } else { 2 }; + let seed = mob.id as i32 + ordinal; let state = self.resolve_item(&stack, context, Some(&owner), seed); if lit { self.submit_item_world(&state, t, light, out); diff --git a/crates/horizon-client/src/game/pandas.rs b/crates/horizon-client/src/game/pandas.rs new file mode 100644 index 000000000..f89feca05 --- /dev/null +++ b/crates/horizon-client/src/game/pandas.rs @@ -0,0 +1,165 @@ +//! Pandas on the game side: the food they find on the ground and pick up +//! (`Mob.aiStep`, `Panda.pickUpItem`), the bamboo a player gives them +//! (`Panda.mobInteract`), the start a sneeze gives the grown pandas about, +//! and the crumbs and the sneeze a window draws. +use super::{ + Game, + pickups::{Collector, Taken}, +}; +use horizon_client::{ + items::ItemStack, + mobs::{Species, panda}, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::geometry::Vec3; + +impl Game<'_> { + /// `Panda.canPickUpAndEat`'s tag. + fn panda_eats_from_ground(&self, item: &str) -> bool { + self.res + .items() + .item_tags + .get("minecraft:panda_eats_from_ground") + .is_some_and(|tag| tag.contains(item)) + } + /// A panda takes what lies at its feet when its mouth is free, and + /// looks for food within 6 and 8 blocks for `PandaSitGoal`. + pub(super) fn tick_pandas(&mut self) { + let griefing = self.ui.rules.bool("mob_griefing"); + for i in 0..self.mobs.len() { + let m = &self.mobs[i]; + if m.species() != Species::Panda || !m.alive() { + continue; + } + let id = m.id; + let wants = |g: &Self, e: &horizon_client::entities::ItemEntity| { + e.pickup_delay == 0 && g.panda_eats_from_ground(&e.stack.item) + }; + // Mob.aiStep: the items within the box grown by (1, 0, 1). + if griefing && m.can_pick_up_loot() && m.extra.main_hand.is_none() { + let reach = m.bounds().inflate(Vec3::new(1.0, 0.0, 1.0)); + let taken = self + .dropped + .iter() + .position(|e| wants(self, e) && reach.intersects(e.bounds())); + if let Some(j) = taken { + let e = self.dropped.remove(j); + self.add_pickup(Taken::Item(Box::new(e.clone())), Collector::Mob(id)); + panda::hold(&mut self.mobs[i], &e.stack.item, e.stack.count, true); + } + } + let m = &self.mobs[i]; + let area = |r: f64| m.bounds().inflate(Vec3::new(r, r, r)); + let (near, wide) = (area(6.0), area(8.0)); + let food_near = self + .dropped + .iter() + .any(|e| wants(self, e) && near.intersects(e.bounds())); + let food_at = self + .dropped + .iter() + .find(|e| wants(self, e) && wide.intersects(e.bounds())) + .map(|e| [e.position.x, e.position.y, e.position.z]); + panda::set_food(&mut self.mobs[i], food_near, food_at); + } + } + /// `Panda.mobInteract` for a click with `item`; whether the click is taken. + pub(super) fn interact_panda(&mut self, index: usize, item: &str) -> bool { + let creative = self.creative; + let m = &mut self.mobs[index]; + if panda::scared(m) { + return false; + } + if panda::get_up(m) { + return true; + } + if !m.kind.food.iter().any(|f| f == item) { + return false; + } + if m.ai.target.is_some() { + panda::got_bamboo(m); + } + let at = [m.position.x, m.position.y, m.position.z]; + let mut dropped = None; + if m.is_baby() { + // ageUp((int) (-getAge() / 20 * 0.1F), true). + let seconds = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, seconds, true); + } else if m.extra.age == 0 && m.extra.in_love <= 0 { + m.extra.in_love = 600; + m.extra.love_player = true; + } else { + if panda::is_sitting(m) || m.fluids.in_water { + return false; + } + panda::try_to_sit(m); + panda::start_eating(m); + // What it held falls, unless the player has infinite materials. + if let Some(held) = m.extra.main_hand.clone() + && !creative + { + dropped = Some(ItemStack::new(&held, panda::held_count(m))); + } + panda::hold(m, item, 1, false); + } + self.consume_held(); + if let Some(stack) = dropped { + self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10); + } + true + } + /// `Panda.afterSneeze`: the grown pandas within 10 blocks of a cub jump. + pub(super) fn panda_sneezed(&mut self, id: u32) { + let Some(area) = self + .mobs + .iter() + .find(|m| m.id == id) + .map(|m| m.bounds().inflate(Vec3::new(10.0, 10.0, 10.0))) + else { + return; + }; + for m in &mut self.mobs { + if m.species() == Species::Panda + && !m.is_baby() + && m.on_ground + && !m.fluids.in_water + && panda::can_perform_action(m, panda::scared(m)) + && area.intersects(m.bounds()) + { + // LivingEntity.jumpFromGround. + m.needs_sync = true; + let power = f64::from(m.jump_power()); + if power > 1.0e-5 { + m.velocity.y = power.max(m.velocity.y); + } + } + } + } + /// What a window draws of its pandas: the crumbs of a bite + /// (`addEatingParticles`) and the sneeze's particle. + pub(super) fn panda_effects(&mut self) { + let mut bites = Vec::new(); + let mut sneezes = Vec::new(); + for m in self + .mobs + .iter_mut() + .filter(|m| m.species() == Species::Panda) + { + let (crumbs, sneeze) = panda::effects(m); + if let (Some(crumbs), Some(item)) = (crumbs, m.extra.main_hand.clone()) { + bites.push((item, crumbs)); + } + sneezes.extend(sneeze); + } + for (item, crumbs) in bites { + let options = self.item_particle(&ItemStack::new(&item, 1)); + for (at, velocity) in crumbs { + self.particles.add(&options, at, velocity); + } + } + let options = ParticleOptions::simple(ParticleType::Sneeze); + for (at, velocity) in sneezes { + self.particles.add(&options, at, velocity); + } + } +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 945af4585..0d1277b10 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3468,16 +3468,18 @@ impl Game<'_> { // server never sends the fluid contact, and the renderers read it (cod, salmon and // tropical fish lie on their side without `in_water`, #1591). // A frozen level ticks only the players, as below. - let fluids: Vec<_> = { + let (fluids, thundering): (Vec<_>, bool) = { let w = self.mob_world_base(&[]); let players = self.remote.as_ref().map(|r| &r.level_players); - self.mobs + let fluids = self + .mobs .iter() .map(|m| { (running || players.is_some_and(|p| p.contains_key(&(m.id as i32)))) .then(|| w.fluids(m.bounds(), m.eye_y())) }) - .collect() + .collect(); + (fluids, w.thundering) }; for (m, fluids) in self.mobs.iter_mut().zip(fluids) { if let Some(fluids) = fluids { @@ -3589,6 +3591,9 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Bat { horizon_client::mobs::bat::setup_animation_states(m); } + if m.species() == horizon_client::mobs::Species::Panda { + horizon_client::mobs::panda::client_tick(m, thundering); + } } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index c6702dfb6..18146ccdc 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,7 +4,7 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, tame}; +use horizon_client::mobs::{Mob, Species, Who, bat, panda, tame}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; @@ -59,6 +59,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti Who::Mob(*target as u32) }); } + // Panda: the counters, the two genes and DATA_ID_FLAGS (after + // AgeableMob's two entries). + (Species::Panda, 18, Value::Int(n)) => panda::set_unhappy(m, *n), + (Species::Panda, 19, Value::Int(n)) => panda::set_sneeze(m, *n), + (Species::Panda, 20, Value::Int(n)) => panda::set_eat(m, *n), + (Species::Panda, 21, Value::Byte(gene)) => m.extra.variant = (*gene).clamp(0, 6) as u8, + (Species::Panda, 22, Value::Byte(gene)) => m.extra.variant2 = (*gene).clamp(0, 6) as u8, + (Species::Panda, 23, Value::Byte(flags)) => panda::set_flags(m, *flags as u8), // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f4086216d..087650c70 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -47,6 +47,7 @@ pub mod monster_brain; pub mod nautilus; pub mod nav; pub mod nether; +pub mod panda; pub mod path; pub mod phantom; pub mod piglin; @@ -783,6 +784,8 @@ pub struct Extra { pub brain: Option>, /// A bee's nectar, anger, flower and hive state. pub bee: Option>, + /// A panda's flags, counters and amounts. + pub panda: Option>, } #[derive(Clone, Debug)] pub struct Mob { @@ -1226,6 +1229,10 @@ pub enum MobEvent { center: [f64; 3], spread: [f64; 3], }, + /// `Panda.afterSneeze`: the grown pandas within 10 blocks start. + PandaSneezed { + mob: u32, + }, } /// How a spawned-by-kind mob should be set up. #[derive(Clone, Debug, Default)] diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 258c1ccc7..6ce808257 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -106,6 +106,7 @@ pub enum Family { Strider, Bat, Bee, + Panda, } pub fn family(s: Species) -> Family { use Species as S; @@ -167,6 +168,7 @@ pub fn family(s: Species) -> Family { S::Strider => Family::Strider, S::Bat => Family::Bat, S::Bee => Family::Bee, + S::Panda => Family::Panda, _ => Family::Generic, } } @@ -227,6 +229,7 @@ pub fn register(m: &mut Mob) { Family::Strider => super::strider::register(m), Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), + Family::Panda => super::panda::register(m), } // FloatGoal's constructor lets the navigation float, as do the // constructors of these brain-driven and flying mobs. A floater rises @@ -429,6 +432,9 @@ pub fn tick( if m.species() == Species::Bee { super::bee::tick(m, level_random); } + if m.species() == Species::Panda { + super::panda::tick(m, w, events); + } true } /// LivingEntity.updateSwingTime (6-tick swing duration). @@ -1126,6 +1132,17 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] { match m.species() { Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m), Species::SulfurCube => super::sulfur_cube::sounds(m), + // Panda.getAmbientSound. + Species::Panda => { + let ambient = if super::panda::is_aggressive(m) { + "entity.panda.aggressive_ambient" + } else if super::panda::is_worried(m) { + "entity.panda.worried_ambient" + } else { + m.kind.sounds[0] + }; + [ambient, m.kind.sounds[1], m.kind.sounds[2]] + } // The sound variant's baby_sounds (classic sets, like the rest here). Species::Pig if m.is_baby() => [ "entity.baby_pig.ambient", @@ -1324,6 +1341,11 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool { super::bee::hurt(m); true } + // Panda.hurtServer: up first, whatever the damage. + Species::Panda => { + super::panda::hurt(m); + true + } Species::Enderman => super::enderman::on_damage(m, source), Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider if source.is_fire() => @@ -1375,6 +1397,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if m.species() == Species::Ravager { super::ravager::on_attack(m, cx.events); } + if m.species() == Species::Panda { + super::panda::bit(m); + } if super::creaking::is_creaking(m) { super::creaking::on_attack(m, cx.events); } @@ -1453,6 +1478,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if super::creaking::is_creaking(m) { m.voice("entity.creaking.attack", cx.events); } + // Panda.playAttackSound: playSound(PANDA_BITE, 1.0, 1.0). + if m.species() == Species::Panda && !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.panda.bite", at, 1.0, 1.0)); + } // Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0). if m.species() == Species::Axolotl { let at = [m.position.x, m.position.y, m.position.z]; diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index bbb44c5ab..edc7b4582 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -960,7 +960,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { match m.species() { Species::Goat => goat(p, s, &Goat::from_mob(m)), Species::PolarBear => polar_bear(p, s, 0.0), - Species::Panda => panda(p, s, &Panda::default()), + Species::Panda => panda(p, s, &super::panda::pose(m, s.partial)), Species::Llama | Species::TraderLlama => { llama(p, s, m.extra.chested && !s.baby); } diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 3df557362..5713ac38b 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -135,6 +135,12 @@ impl Mob { if self.species() == super::Species::Rabbit { return super::rabbit::move_control(self, w); } + // Panda.PandaMoveControl: only while it can act. + if self.species() == super::Species::Panda + && !super::panda::can_perform_action(self, w.thundering) + { + return; + } let attr_speed = self.movement_speed(); match self.ai.mov.kind { MoveKind::Custom => super::ai::custom_move_control(self, w, events), diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 064cf0583..f9bb1767a 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -244,7 +244,13 @@ pub fn slot_item(m: &Mob, slot: &str) -> Option { } _ => (None, None), }; - let mut stack = loot_stack(item?, 1); + // A panda keeps the whole stack it picked up in its mouth. + let count = if slot == "mainhand" && m.species() == Species::Panda { + super::panda::held_count(m) + } else { + 1 + }; + let mut stack = loot_stack(item?, count as i32); if let (Some(index), Some(g)) = (index, gear::gear(m)) { for (e, l) in &g.slots[index] { stack.enchantments.push((e.to_string(), *l as i32)); diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 6e5daff1f..158ee3c69 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1691,13 +1691,7 @@ impl Ctx<'_, L, R> { let hidden = panda_gene(self.int(16)); m.extra.variant = main; m.extra.variant2 = hidden; - let shown = panda_variant(main, hidden); - if shown == 5 { - set_base(m, Attr::MaxHealth, 10.0); - } - if shown == 1 { - set_base(m, Attr::MovementSpeed, f64::from(0.07f32)); - } + super::panda::set_attributes(m); self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.2))))) } S::PolarBear | S::Ocelot => { @@ -1950,7 +1944,7 @@ fn set_memory(m: &mut Mob, name: &'static str, value: i64, ttl: i64) { } /// `Panda.Gene.getRandom` (enum order: normal, lazy, worried, playful, /// brown, weak, aggressive). -fn panda_gene(roll: i32) -> u8 { +pub fn panda_gene(roll: i32) -> u8 { match roll { 0 => 1, 1 => 2, diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 541398bc5..2e3c03296 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1422,6 +1422,9 @@ pub struct HurtByTarget { /// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others /// only when the attacker is in sight. pub bee: bool, + /// Whom `alertOther` calls: a filter on the mob (`PandaHurtByTargetGoal` + /// calls aggressive pandas only). + pub alert_if: Option bool>, timestamp: i32, st: TargetState, } @@ -1432,6 +1435,7 @@ impl HurtByTarget { alert_except: vec![], ignore: vec![], bee: false, + alert_if: None, timestamp: 0, st: TargetState { unseen_memory: 300, @@ -1451,6 +1455,10 @@ impl HurtByTarget { self.bee = true; self } + pub fn alert_if(mut self, f: fn(&Seen) -> bool) -> Self { + self.alert_if = Some(f); + self + } } impl Default for HurtByTarget { fn default() -> Self { @@ -1520,6 +1528,7 @@ impl Goal for HurtByTarget { && (s.position.z - pos.z).abs() <= range + 1.0 }) .filter(|s| !self.alert_except.contains(&s.species)) + .filter(|s| self.alert_if.is_none_or(|f| f(s))) .filter(|s| Who::Mob(s.id) != by) .map(|s| s.id) .collect(); diff --git a/crates/horizon-client/src/mobs/panda.rs b/crates/horizon-client/src/mobs/panda.rs new file mode 100644 index 000000000..a5b8e2944 --- /dev/null +++ b/crates/horizon-client/src/mobs/panda.rs @@ -0,0 +1,1090 @@ +//! Pandas (`Panda`): the genes and what they show, the sit, lie-on-back, roll +//! and sneeze states with their goals, the unhappy and eat counters, and the +//! client side of the three amounts `PandaModel.setupAnim` reads. +//! +//! `extra.variant` and `extra.variant2` are the main and the hidden gene +//! (`MAIN_GENE_ID`, `HIDDEN_GENE_ID`); the rest is [`State`], whose `flags`, +//! `unhappy`, `sneeze` and `eat` are the synched data a server sends. +use super::{ + DamageKind, Mob, MobEvent, MobWorld, Species, Who, + body_anim::Panda as Pose, + finalize::{self, Attr}, + goals::{ + Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, HurtByTarget, JUMP, LOOK, MOVE, + MeleeAttack, Panic, RandomLookAround, Stroll, Tempt, goal_clone, reduced, + }, +}; +use horizon_core::{ + geometry::{ + Vec3, + trig::{DEG_TO_RAD, Mth}, + }, + jmath, + random::{LegacyRandom, RandomSource}, +}; + +/// `Panda.Gene` ids (the order of `Gene.values()`). +pub const LAZY: u8 = 1; +pub const WORRIED: u8 = 2; +pub const PLAYFUL: u8 = 3; +pub const WEAK: u8 = 5; +pub const AGGRESSIVE: u8 = 6; +/// `Gene.getSerializedName`, by id. +pub const GENES: [&str; 7] = [ + "normal", + "lazy", + "worried", + "playful", + "brown", + "weak", + "aggressive", +]; + +/// `DATA_ID_FLAGS`. +pub const FLAG_SNEEZE: u8 = 2; +pub const FLAG_ROLL: u8 = 4; +pub const FLAG_SIT: u8 = 8; +pub const FLAG_ON_BACK: u8 = 16; + +/// The crumbs of one bite: where and how fast each one flies. +pub type Crumbs = Vec<([f64; 3], [f64; 3])>; + +#[derive(Clone, Debug, Default)] +pub struct State { + /// `DATA_ID_FLAGS` (sneezing, rolling, sitting, on its back). + pub flags: u8, + /// `UNHAPPY_COUNTER`, `SNEEZE_COUNTER` and `EAT_COUNTER`. + pub unhappy: i32, + pub sneeze: i32, + pub eat: i32, + got_bamboo: bool, + did_bite: bool, + /// `rollCounter`, which a client counts for itself. + pub roll_counter: i32, + roll_delta: [f64; 2], + /// `sitAmount`, `onBackAmount` and `rollAmount` with the tick before. + sit_amount: [f32; 2], + on_back_amount: [f32; 2], + roll_amount: [f32; 2], + /// `isScared` as of the last tick (the model and the item layer read it). + scared: bool, + /// `PandaLookAtPlayerGoal.lookAt`, which the breed goal can set. + look_at: Option, + /// What the game saw on the ground: any food within 6 blocks, and the + /// first within 8. + pub food_near: bool, + pub food_at: Option<[f64; 3]>, + /// The size of the stack in its mouth (the mob holds one item id). + pub held_count: u32, + /// What a window draws of the last bite and sneeze, taken by `effects`. + crumbs: Option, + sneezed: Option<([f64; 3], [f64; 3])>, +} + +fn st(m: &mut Mob) -> &mut State { + m.extra.panda.get_or_insert_with(Default::default) +} +pub fn get(m: &Mob) -> Option<&State> { + m.extra.panda.as_deref() +} +fn flag(m: &Mob, f: u8) -> bool { + get(m).is_some_and(|s| s.flags & f != 0) +} +fn set_flag(m: &mut Mob, f: u8, on: bool) { + let s = st(m); + if on { + s.flags |= f; + } else { + s.flags &= !f; + } +} + +// ---- genes ---------------------------------------------------------------- + +/// `Panda.getVariant`: the gene a panda shows. +pub fn variant(m: &Mob) -> u8 { + finalize::panda_variant(m.extra.variant, m.extra.variant2) +} +pub fn is_lazy(m: &Mob) -> bool { + variant(m) == LAZY +} +pub fn is_worried(m: &Mob) -> bool { + variant(m) == WORRIED +} +pub fn is_playful(m: &Mob) -> bool { + variant(m) == PLAYFUL +} +pub fn is_weak(m: &Mob) -> bool { + variant(m) == WEAK +} +/// `Panda.isAggressive`: the gene, not the mob flag. +pub fn is_aggressive(m: &Mob) -> bool { + variant(m) == AGGRESSIVE +} +/// `Panda.Gene.getRandom`. +fn random_gene(random: &mut impl RandomSource) -> u8 { + finalize::panda_gene(random.next_int_bound(16).unwrap_or(0)) +} +/// `Panda.setAttributes`: a weak panda has 10 health, a lazy one is slow. +pub fn set_attributes(m: &mut Mob) { + if is_weak(m) { + finalize::set_base(m, Attr::MaxHealth, 10.0); + } + if is_lazy(m) { + finalize::set_base(m, Attr::MovementSpeed, f64::from(0.07_f32)); + } +} +/// `Panda.getBreedOffspring`: `setGeneFromParents`, then `setAttributes`, on +/// a baby the game made (its attributes go back to the type's first). +pub fn inherit(child: &mut Mob, parent: &Mob, partner: &Mob) { + let r = &mut child.random; + let one_of = |p: &Mob, r: &mut LegacyRandom| { + if r.next_boolean() { + p.extra.variant + } else { + p.extra.variant2 + } + }; + let (mut main, mut hidden) = if r.next_boolean() { + let main = one_of(parent, r); + (main, one_of(partner, r)) + } else { + let main = one_of(partner, r); + (main, one_of(parent, r)) + }; + if r.next_int_bound(32).unwrap_or(1) == 0 { + main = random_gene(r); + } + if r.next_int_bound(32).unwrap_or(1) == 0 { + hidden = random_gene(r); + } + child.extra.variant = main; + child.extra.variant2 = hidden; + for a in [Attr::MaxHealth, Attr::MovementSpeed] { + if let Some(value) = finalize::default_value(child, a) { + finalize::set_base(child, a, value); + } + } + set_attributes(child); + child.health = finalize::max_health(child); +} +/// `Panda.Gene.CODEC` for `MainGene` and `HiddenGene`. +pub fn gene_from_name(name: &str) -> u8 { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + GENES.iter().position(|g| *g == name).unwrap_or(0) as u8 +} + +// ---- state ---------------------------------------------------------------- + +pub fn is_sitting(m: &Mob) -> bool { + flag(m, FLAG_SIT) +} +fn is_rolling(m: &Mob) -> bool { + flag(m, FLAG_ROLL) +} +fn is_on_back(m: &Mob) -> bool { + flag(m, FLAG_ON_BACK) +} +fn is_eating(m: &Mob) -> bool { + get(m).is_some_and(|s| s.eat > 0) +} +/// `Panda.isScared`: a worried panda in a thunderstorm. +fn is_scared(m: &Mob, thundering: bool) -> bool { + is_worried(m) && thundering +} +/// `Panda.canPerformAction`. +pub fn can_perform_action(m: &Mob, thundering: bool) -> bool { + !is_on_back(m) && !is_scared(m, thundering) && !is_eating(m) && !is_rolling(m) && !is_sitting(m) +} +fn sit(m: &mut Mob, on: bool) { + set_flag(m, FLAG_SIT, on); +} +fn eat(m: &mut Mob, on: bool) { + st(m).eat = i32::from(on); +} +/// `Panda.sneeze`: ending it resets the counter. +fn sneeze(m: &mut Mob, on: bool) { + set_flag(m, FLAG_SNEEZE, on); + if !on { + st(m).sneeze = 0; + } +} +/// `Panda.tryToSit`. +pub fn try_to_sit(m: &mut Mob) { + if !m.fluids.in_water { + m.ai.zza = 0.0; + m.nav_stop(); + sit(m, true); + } +} +/// `Panda.mobInteract` with bamboo in hand while it has a target. +pub fn got_bamboo(m: &mut Mob) { + st(m).got_bamboo = true; +} +/// `Panda.hurtServer`: any hurt gets it up. +pub fn hurt(m: &mut Mob) { + sit(m, false); +} +/// `Panda.doHurtTarget`: a bite that is not an aggressive panda's. +pub fn bit(m: &mut Mob) { + if !is_aggressive(m) { + st(m).did_bite = true; + } +} +/// `Panda.setOnBack(false)` from a click on a panda on its back. +pub fn get_up(m: &mut Mob) -> bool { + let was = is_on_back(m); + if was { + set_flag(m, FLAG_ON_BACK, false); + } + was +} +/// `Panda.eat(true)` at the first bite of what a player gave it. +pub fn start_eating(m: &mut Mob) { + eat(m, true); +} +/// `isScared` as of its last tick, for a click or a sneeze. +pub fn scared(m: &Mob) -> bool { + get(m).is_some_and(|s| s.scared) +} +/// `setItemSlot(MAINHAND, stack)` and `setGuaranteedDrop`, or just the size +/// of a stack it was given. +pub fn hold(m: &mut Mob, item: &str, count: u32, guaranteed: bool) { + finalize::set_item(m, super::gear::MAIN, item); + if guaranteed { + finalize::set_drop_chance(m, super::gear::MAIN, 2.0); + } + st(m).held_count = count; +} +/// What its goals look for on the ground, found by the game each tick. +pub fn set_food(m: &mut Mob, near: bool, at: Option<[f64; 3]>) { + let s = st(m); + s.food_near = near; + s.food_at = at; +} +/// The size of the stack in its mouth, for what it drops. +pub fn held_count(m: &Mob) -> u32 { + get(m).map_or(1, |s| s.held_count.max(1)) +} + +// ---- synched data --------------------------------------------------------- + +/// `DATA_ID_FLAGS` from a server: a sneeze that ends is a sneeze that was +/// done (`afterSneeze`'s particle). +pub fn set_flags(m: &mut Mob, flags: u8) { + if flag(m, FLAG_SNEEZE) && flags & FLAG_SNEEZE == 0 { + let at = [m.position.x, m.position.y, m.position.z]; + let particle = sneeze_particle(at, m.width(), m.body_yaw, m.eye_y(), m.velocity); + st(m).sneezed = Some(particle); + } + st(m).flags = flags; +} +/// `UNHAPPY_COUNTER` and `SNEEZE_COUNTER` from a server. +pub fn set_unhappy(m: &mut Mob, unhappy: i32) { + st(m).unhappy = unhappy; +} +pub fn set_sneeze(m: &mut Mob, sneeze: i32) { + st(m).sneeze = sneeze; +} +/// `EAT_COUNTER` from a server: a bite every five. +pub fn set_eat(m: &mut Mob, eat: i32) { + let bite = eat > 0 && eat % 5 == 0 && st(m).eat != eat && m.extra.main_hand.is_some(); + st(m).eat = eat; + if bite { + let crumbs = crumbs(m); + st(m).crumbs = Some(crumbs); + } +} +/// What the window draws since the last call: the crumbs of a bite and the +/// sneeze's particle (position, velocity). +pub fn effects(m: &mut Mob) -> (Option, Option<([f64; 3], [f64; 3])>) { + match m.extra.panda.as_deref_mut() { + Some(s) => (s.crumbs.take(), s.sneezed.take()), + None => (None, None), + } +} + +// ---- the tick -------------------------------------------------------------- + +/// `Entity.playSound`: at the feet, never from a silent mob. +fn play(m: &Mob, sound: &'static str, volume: f32, pitch: f32, events: &mut Vec) { + if !m.silent { + let at = [m.position.x, m.position.y, m.position.z]; + events.push(MobEvent::Sound(sound, at, volume, pitch)); + } +} +fn lerp(a: f32, o: f32, n: f32) -> f32 { + o + a * (n - o) +} +/// `updateSitAmount`, `updateOnBackAnimation` and `updateRollAmount`. +fn step_amount(amount: &mut [f32; 2], on: bool) { + amount[0] = amount[1]; + amount[1] = if on { + (amount[1] + 0.15).min(1.0) + } else { + (amount[1] - 0.19).max(0.0) + }; +} +fn update_amounts(m: &mut Mob) { + let (sit, back, roll) = (is_sitting(m), is_on_back(m), is_rolling(m)); + let s = st(m); + step_amount(&mut s.sit_amount, sit); + step_amount(&mut s.on_back_amount, back); + step_amount(&mut s.roll_amount, roll); +} +/// `Panda.handleRoll`; a client counts the roll and leaves the motion to the +/// server. +fn handle_roll(m: &mut Mob, server: bool) { + let counter = { + let s = st(m); + s.roll_counter += 1; + s.roll_counter + }; + if counter > 32 { + set_flag(m, FLAG_ROLL, false); + } else if server { + let movement = m.velocity; + if counter == 1 { + let angle = m.yaw * DEG_TO_RAD; + let multiplier = if m.is_baby() { 0.1_f32 } else { 0.2_f32 }; + let delta = [ + movement.x + f64::from(-angle.msin() * multiplier), + movement.z + f64::from(angle.mcos() * multiplier), + ]; + st(m).roll_delta = delta; + m.velocity = Vec3::new(delta[0], 0.27, delta[1]); + } else if counter != 7 && counter != 15 && counter != 23 { + let [x, z] = st(m).roll_delta; + m.velocity = Vec3::new(x, movement.y, z); + } else { + let y = if m.on_ground { 0.27 } else { movement.y }; + m.velocity = Vec3::new(0.0, y, 0.0); + } + } +} +fn rnd(m: &mut Mob, bound: i32) -> i32 { + m.random.next_int_bound(bound).unwrap_or(0) +} +/// `Panda.handleEating`: the bite's sound and crumbs, and the end of a meal. +fn handle_eating(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let holds = m.extra.main_hand.is_some(); + if !is_eating(m) && is_sitting(m) && !is_scared(m, w.thundering) && holds && rnd(m, 80) == 1 { + eat(m, true); + } else if !holds || !is_sitting(m) { + eat(m, false); + } + if !is_eating(m) { + return; + } + // addEatingParticles + if st(m).eat % 5 == 0 { + let volume = 0.5 + 0.5 * rnd(m, 2) as f32; + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + play(m, "entity.panda.eat", volume, pitch, events); + if holds { + let crumbs = crumbs(m); + st(m).crumbs = Some(crumbs); + } + } + let count = st(m).eat; + if count > 80 && rnd(m, 20) == 1 { + let eats_from_ground = m.extra.main_hand.as_deref().is_some_and(|item| { + w.items + .and_then(|i| i.item_tags.get("minecraft:panda_eats_from_ground")) + .is_some_and(|tag| tag.contains(item)) + }); + if count > 100 && eats_from_ground { + super::drops::clear_slot(m, "mainhand"); + sit(m, false); + } + eat(m, false); + return; + } + st(m).eat += 1; +} +/// The six crumbs of `addEatingParticles`, drawn as the server draws them. +fn crumbs(m: &mut Mob) -> Crumbs { + let (x_rot, y_rot) = (-m.head_pitch * DEG_TO_RAD, -m.yaw * DEG_TO_RAD); + let body = -m.body_yaw * DEG_TO_RAD; + let (x, y, z) = (m.position.x, m.eye_y() + 1.0, m.position.z); + (0..6) + .map(|_| { + let r = &mut m.random; + let mut f = || f64::from(r.next_float()); + let v = Vec3::new((f() - 0.5) * 0.1, f() * 0.1 + 0.1, (f() - 0.5) * 0.1) + .rotate_x(x_rot) + .rotate_y(y_rot); + let p = Vec3::new((f() - 0.5) * 0.8, -f() * 0.6 - 0.3, 1.0 + (f() - 0.5) * 0.4) + .rotate_y(body); + ([p.x + x, p.y + y, p.z + z], [v.x, v.y + 0.05, v.z]) + }) + .collect() +} +/// `afterSneeze`'s particle, from the nose. +fn sneeze_particle( + at: [f64; 3], + width: f32, + body_yaw: f32, + eye: f64, + movement: Vec3, +) -> ([f64; 3], [f64; 3]) { + let reach = f64::from(width + 1.0) * 0.5; + let angle = body_yaw * DEG_TO_RAD; + ( + [ + at[0] - reach * f64::from(angle.msin()), + eye - f64::from(0.1_f32), + at[2] + reach * f64::from(angle.mcos()), + ], + [movement.x, 0.0, movement.z], + ) +} +/// `Panda.afterSneeze`: the particle, the sound, a start for the grown pandas +/// about, and a slime ball one sneeze in 700. +fn after_sneeze(m: &mut Mob, events: &mut Vec) { + let at = [m.position.x, m.position.y, m.position.z]; + let particle = sneeze_particle(at, m.width(), m.body_yaw, m.eye_y(), m.velocity); + st(m).sneezed = Some(particle); + play(m, "entity.panda.sneeze", 1.0, 1.0, events); + events.push(MobEvent::PandaSneezed { mob: m.id }); + events.push(MobEvent::GiftLoot { + mob: m.id, + table: "minecraft:gameplay/panda_sneeze", + at, + }); +} +/// `Panda.tick` after `super.tick()`. +pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + let thundering = w.thundering; + if is_worried(m) { + if thundering && !m.fluids.in_water { + sit(m, true); + eat(m, false); + } else if !is_eating(m) { + sit(m, false); + } + } + if m.ai.target.is_none() { + let s = st(m); + s.got_bamboo = false; + s.did_bite = false; + } + let unhappy = st(m).unhappy; + if unhappy > 0 { + if let Some(t) = m.target_info(w) { + m.turn_to([t.position.x, t.eye_y, t.position.z], 90.0, 90.0); + } + if unhappy == 29 || unhappy == 14 { + play(m, "entity.panda.cant_breed", 1.0, 1.0, events); + } + st(m).unhappy -= 1; + } + if flag(m, FLAG_SNEEZE) { + let count = { + let s = st(m); + s.sneeze += 1; + s.sneeze + }; + if count > 20 { + sneeze(m, false); + after_sneeze(m, events); + } else if count == 1 { + play(m, "entity.panda.pre_sneeze", 1.0, 1.0, events); + } + } + if is_rolling(m) { + handle_roll(m, true); + } else { + st(m).roll_counter = 0; + } + if is_sitting(m) { + m.head_pitch = 0.0; + } + st(m).scared = is_scared(m, thundering); + update_amounts(m); + handle_eating(m, w, events); + // updateOnBackAnimation and updateRollAmount ran with the others. +} +/// `Panda.tick` for a panda a client only displays: the flags and counters +/// are the server's; the amounts and the roll count are the client's own. +pub fn client_tick(m: &mut Mob, thundering: bool) { + if is_rolling(m) { + handle_roll(m, false); + } else { + st(m).roll_counter = 0; + } + if is_sitting(m) { + m.head_pitch = 0.0; + } + st(m).scared = is_scared(m, thundering); + update_amounts(m); +} + +// ---- drawing --------------------------------------------------------------- + +/// `PandaRenderer.getTextureLocation`. +pub fn texture(m: &Mob) -> String { + let v = usize::from(variant(m)).min(GENES.len() - 1); + let gene = GENES[v]; + match (m.is_baby(), gene) { + (false, "normal") => "entity/panda/panda".into(), + (false, g) => format!("entity/panda/panda_{g}"), + (true, "normal") => "entity/panda/panda_baby".into(), + (true, g) => format!("entity/panda/{g}_panda_baby"), + } +} +/// What `PandaRenderState` gives `PandaModel.setupAnim`. +pub fn pose(m: &Mob, partial: f32) -> Pose { + let Some(s) = get(m) else { + return Pose::default(); + }; + let amount = |a: &[f32; 2]| lerp(partial, a[0], a[1]); + Pose { + unhappy: s.unhappy > 0, + sneezing: s.flags & FLAG_SNEEZE != 0, + sneeze_time: s.sneeze, + eating: s.eat > 0, + scared: s.scared, + sit_amount: amount(&s.sit_amount), + lie_on_back_amount: amount(&s.on_back_amount), + roll_amount: if m.is_baby() { + 0.0 + } else { + amount(&s.roll_amount) + }, + } +} +/// `PandaRenderer.setupRotations` after the common ones: the roll over, the +/// sit up and the lie on its back, and a scared panda's shiver. +pub fn rotations(m: &Mob, partial: f32) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + let Some(s) = get(m) else { + return Mat4::IDENTITY; + }; + let baby = m.is_baby(); + let x_rot = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * partial; + let mut t = Mat4::IDENTITY; + let translate = |y: f32| Mat4::from_translation(Vec3::new(0.0, y, 0.0)); + let tilt = |degrees: f32| Mat4::from_rotation_x(degrees.to_radians()); + if s.roll_counter > 0 { + let time = s.roll_counter as f32 + partial; + let (pos, frac) = (time.floor() as i32, time.fract()); + let next = pos + 1; + let y = if baby { 0.3 } else { 0.8 }; + // getAngle: the angle between this step and the next, except in the + // last step of a quarter. + let angle = |this: f32, next_angle: f32, threshold: i32| { + if next < threshold { + lerp(frac, this, next_angle) + } else { + this + } + }; + let quarter = pos / 8; + if (0..4).contains(&quarter) { + let base = 90.0 * quarter as f32; + let step = |p: i32| base + 90.0 * (p - quarter * 8) as f32 / 7.0; + let a = angle(step(pos), step(next), (quarter + 1) * 8); + let lift = match quarter { + 0 => (y + 0.2) * (a / 90.0), + 1 => y + 0.2 + (y - 0.2) * (a - 90.0) / 90.0, + 2 => y + y * (270.0 - a) / 90.0, + _ => y * ((360.0 - a) / 90.0), + }; + t = t * translate(lift) * tilt(-a); + } + } + let sit = s.sit_amount; + let sit = lerp(partial, sit[0], sit[1]); + if sit > 0.0 { + t = t * translate(0.8 * sit) * tilt(lerp(sit, x_rot, x_rot + 90.0)) * translate(-sit); + if s.scared { + let age = m.age as f32 + partial; + let shake = (jmath::cos(f64::from(age * 1.25)) + * std::f64::consts::PI + * f64::from(0.05_f32)) as f32; + t *= Mat4::from_rotation_y(shake.to_radians()); + if baby { + t *= Mat4::from_translation(Vec3::new(0.0, 0.8, 0.55)); + } + } + } + let back = lerp(partial, s.on_back_amount[0], s.on_back_amount[1]); + if back > 0.0 { + let y = if baby { 0.5 } else { 1.3 }; + t = t * translate(y * back) * tilt(lerp(back, x_rot, x_rot + 180.0)); + } + t +} +/// `PandaHoldsItemLayer`: where the item in its mouth sits, in the model's +/// space, while it sits and eats. +pub fn item_offset(m: &Mob, partial: f32) -> Option { + let s = get(m)?; + if m.extra.main_hand.is_none() || s.flags & FLAG_SIT == 0 || s.scared { + return None; + } + let (mut y, mut z) = (1.4_f32, -0.6_f32); + if s.eat > 0 { + let bite = ((m.age as f32 + partial) * 0.6).msin(); + z -= 0.2 * bite + 0.2; + y -= 0.09 * bite; + } + Some(glam::Mat4::from_translation(glam::Vec3::new(0.1, y, z))) +} + +// ---- goals ----------------------------------------------------------------- + +/// A goal that starts only when `when` allows it (`PandaAttackGoal`, +/// `PandaAvoidGoal`). +#[derive(Clone, Debug)] +struct When { + goal: G, + when: fn(&Mob, &MobWorld) -> bool, +} +impl Goal for When { + goal_clone!(); + fn flags(&self) -> u8 { + self.goal.flags() + } + fn name(&self) -> &'static str { + self.goal.name() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + (self.when)(m, cx.w) && self.goal.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.goal.can_continue(m, cx) + } + fn interruptable(&self) -> bool { + self.goal.interruptable() + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.stop(m, cx) + } + fn every_tick(&self) -> bool { + self.goal.every_tick() + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.goal.tick(m, cx) + } +} +fn acts(m: &Mob, w: &MobWorld) -> bool { + can_perform_action(m, w.thundering) +} +fn avoids(m: &Mob, w: &MobWorld) -> bool { + is_worried(m) && acts(m, w) +} + +/// `PandaPanicGoal`: panics at the environment only, and not while sitting. +#[derive(Clone, Debug)] +struct PandaPanic(Panic); +impl Goal for PandaPanic { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn name(&self) -> &'static str { + "Panic" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + environmental(m) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if is_sitting(m) { + m.nav_stop(); + false + } else { + self.0.can_continue(m, cx) + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} +/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES`, or burning. +fn environmental(m: &Mob) -> bool { + m.fire_ticks > 0 && !m.kind.flags.fire_immune + || m.last_damage.is_some_and(|(d, t)| { + matches!( + d.kind, + DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Cactus + ) && i64::from(m.age) - t <= 40 + }) +} + +/// `PandaBreedGoal`: a panda in love finds no mate happy unless there is +/// bamboo about. +#[derive(Clone, Debug)] +struct PandaBreed { + breed: Breed, + unhappy_cooldown: i64, +} +impl PandaBreed { + /// `canFindBamboo`: any bamboo within 7 blocks and 2 up. + fn can_find_bamboo(m: &Mob, w: &MobWorld) -> bool { + let at = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + (0..3).any(|y| { + (-7..=7).any(|x| { + (-7..=7) + .any(|z| w.block_name(at[0] + x, at[1] + y, at[2] + z) == "minecraft:bamboo") + }) + }) + } +} +impl Goal for PandaBreed { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn name(&self) -> &'static str { + "Breed" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !self.breed.can_use(m, cx) || st(m).unhappy != 0 { + return false; + } + if Self::can_find_bamboo(m, cx.w) { + return true; + } + if self.unhappy_cooldown <= i64::from(m.age) { + st(m).unhappy = 32; + self.unhappy_cooldown = i64::from(m.age) + 600; + // The nearest player it looks at while it sulks. + let seen = m.can_see_player(cx.w, 8.0); + st(m).look_at = seen.then_some(Who::Player); + } + false + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.breed.can_continue(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.breed.stop(m, cx) + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + self.breed.tick(m, cx) + } +} + +/// `PandaHurtByTargetGoal`: a panda that was fed bamboo or bit lets go. +#[derive(Clone, Debug)] +struct PandaHurtBy(HurtByTarget); +impl Goal for PandaHurtBy { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + self.0.name() + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let s = st(m); + if s.got_bamboo || s.did_bite { + m.ai.target = None; + false + } else { + self.0.can_continue(m, cx) + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx) + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx) + } +} + +/// What `PandaSitGoal` and `PandaLieOnBackGoal` ask each tick of their run. +fn rest_goes_on(m: &mut Mob) -> bool { + if !m.fluids.in_water && (is_lazy(m) || rnd(m, reduced(600)) != 1) { + rnd(m, reduced(2000)) != 1 + } else { + false + } +} + +/// `PandaSitGoal`: sit down with bamboo or cake in the mouth, or go to get +/// some from the ground. +#[derive(Clone, Debug, Default)] +struct PandaSit { + cooldown: i64, +} +impl Goal for PandaSit { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if self.cooldown > i64::from(m.age) + || m.is_baby() + || m.fluids.in_water + || !acts(m, cx.w) + || st(m).unhappy > 0 + { + return false; + } + m.extra.main_hand.is_some() || st(m).food_near + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + rest_goes_on(m) + } + fn tick(&mut self, m: &mut Mob, _: &mut Cx) { + if !is_sitting(m) && m.extra.main_hand.is_some() { + try_to_sit(m); + } + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + if m.extra.main_hand.is_none() { + if let Some(at) = st(m).food_at { + m.nav_move_to_entity(cx.w, at, 0, f64::from(1.2_f32)); + } + } else { + try_to_sit(m); + } + self.cooldown = 0; + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some(item) = m.extra.main_hand.clone() { + let count = held_count(m); + cx.events.push(MobEvent::DropItem { + item, + count, + at: [m.position.x, m.position.y, m.position.z], + }); + super::drops::clear_slot(m, "mainhand"); + let wait = if is_lazy(m) { + rnd(m, 50) + 10 + } else { + rnd(m, 150) + 10 + }; + self.cooldown = i64::from(m.age) + i64::from(wait) * 20; + } + sit(m, false); + } +} + +/// `PandaLieOnBackGoal`: a lazy panda now and then lies down. +#[derive(Clone, Debug, Default)] +struct PandaLieOnBack { + cooldown: i64, +} +impl Goal for PandaLieOnBack { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.cooldown < i64::from(m.age) && is_lazy(m) && acts(m, cx.w) && rnd(m, reduced(400)) == 1 + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + rest_goes_on(m) + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ON_BACK, true); + self.cooldown = 0; + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ON_BACK, false); + self.cooldown = i64::from(m.age) + 200; + } +} + +/// `PandaSneezeGoal`: a cub sneezes now and then, a weak one more. +#[derive(Clone, Debug)] +struct PandaSneeze; +impl Goal for PandaSneeze { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !(m.is_baby() && acts(m, cx.w)) { + return false; + } + if is_weak(m) && rnd(m, reduced(500)) == 1 { + true + } else { + rnd(m, reduced(6000)) == 1 + } + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + sneeze(m, true); + } +} + +/// `PandaLookAtPlayerGoal`: looks at the nearest player, or at the one the +/// breed goal sulks at. +#[derive(Clone, Debug, Default)] +struct PandaLook { + look_time: i32, +} +impl PandaLook { + fn target(m: &Mob, cx: &Cx) -> Option<(Vec3, f64)> { + match get(m)?.look_at? { + Who::Player => { + cx.w.player + .as_ref() + .filter(|p| p.alive) + .map(|p| (p.position, p.eye[1])) + } + Who::Mob(id) => { + cx.w.seen(id) + .filter(|s| s.alive) + .map(|s| (s.position, s.eye_y)) + } + } + } +} +impl Goal for PandaLook { + goal_clone!(); + fn flags(&self) -> u8 { + LOOK + } + fn name(&self) -> &'static str { + "LookAtPlayer" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.random.next_float() >= 0.02 { + return false; + } + if st(m).look_at.is_none() { + let seen = m.can_see_player(cx.w, 6.0); + st(m).look_at = seen.then_some(Who::Player); + } + acts(m, cx.w) && st(m).look_at.is_some() + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let Some((at, _)) = Self::target(m, cx) else { + return false; + }; + m.distance_sqr(at) <= 36.0 && self.look_time > 0 + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + self.look_time = reduced(40 + rnd(m, 40)); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + st(m).look_at = None; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + if let Some((at, eye)) = Self::target(m, cx) { + m.look_at([at.x, eye, at.z]); + self.look_time -= 1; + } + } +} + +/// `PandaRollGoal`: a cub, or a playful panda, rolls over when it faces a +/// drop and now and then at random. +#[derive(Clone, Debug)] +struct PandaRoll; +impl Goal for PandaRoll { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK | JUMP + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !((m.is_baby() || is_playful(m)) && m.on_ground) || !acts(m, cx.w) { + return false; + } + let angle = m.yaw * DEG_TO_RAD; + let (x_dir, z_dir) = (-angle.msin(), angle.mcos()); + let step = |d: f32| if d.abs() > 0.5 { d.signum() as i32 } else { 0 }; + let (x, z) = ( + m.position.x.floor() as i32 + step(x_dir), + m.position.z.floor() as i32 + step(z_dir), + ); + let below = m.position.y.floor() as i32 - 1; + if cx.w.facts.is_air(cx.w.world.block(x, below, z)) { + return true; + } + if is_playful(m) && rnd(m, reduced(60)) == 1 { + true + } else { + rnd(m, reduced(500)) == 1 + } + } + fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool { + false + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + set_flag(m, FLAG_ROLL, true); + } + fn interruptable(&self) -> bool { + false + } +} + +/// `Panda.registerGoals`. +pub fn register(m: &mut Mob) { + let food = m.kind.food.clone(); + let monsters = super::species::ALL + .iter() + .map(|d| d.species) + .filter(|s| super::ai::is_monster(*s)) + .collect::>(); + let g = &mut m.ai.goals; + g.add(0, Float); + g.add(2, PandaPanic(Panic::new(2.0))); + g.add( + 2, + PandaBreed { + breed: Breed::new(1.0), + unhappy_cooldown: 0, + }, + ); + g.add( + 3, + When { + goal: MeleeAttack::new(f64::from(1.2_f32), true), + when: acts, + }, + ); + g.add(4, Tempt::new(1.0, food, false)); + g.add( + 6, + When { + goal: AvoidEntity::new(Avoid::Player, 8.0, 2.0, 2.0), + when: avoids, + }, + ); + g.add( + 6, + When { + goal: AvoidEntity::new(Avoid::Species(monsters), 4.0, 2.0, 2.0), + when: avoids, + }, + ); + g.add(7, PandaSit::default()); + g.add(8, PandaLieOnBack::default()); + g.add(8, PandaSneeze); + g.add(9, PandaLook::default()); + g.add(10, RandomLookAround::default()); + g.add(12, PandaRoll); + g.add(13, FollowParent::new(1.25)); + g.add(14, Stroll::avoiding_water(1.0)); + // alertOther: only an aggressive panda joins in. + m.ai.targets.add( + 1, + PandaHurtBy( + HurtByTarget::new() + .alert() + .alert_if(|s| s.species == Species::Panda && s.variant == AGGRESSIVE), + ), + ); +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..305b7ce5f 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -137,6 +137,10 @@ pub fn body(m: &Mob) -> (String, String) { baby_or(m, "wolf#main", "wolf_baby#main"), super::tame::texture(m), ), + S::Panda => ( + baby_or(m, "panda#main", "panda_baby#main"), + super::panda::texture(m), + ), S::HappyGhast => ( baby_or(m, "happy_ghast#main", "happy_ghast_baby#main"), if baby { @@ -854,6 +858,7 @@ fn flip_degrees(m: &Mob) -> f32 { fn species_rotations(m: &Mob, alpha: f32) -> glam::Mat4 { match m.species() { Species::Cat => super::tame::cat_rotations(m, alpha), + Species::Panda => super::panda::rotations(m, alpha), Species::Shulker => super::shulker::rotations(m), _ => glam::Mat4::IDENTITY, } @@ -1279,6 +1284,12 @@ pub fn held_item_transform( data: &MobData, left: bool, ) -> Option { + // PandaHoldsItemLayer: the main hand's item in its mouth. + if m.species() == Species::Panda { + return super::panda::item_offset(m, alpha) + .filter(|_| !left) + .map(|offset| base_transform(m, alpha, camera) * offset); + } if !super::illager::shows_item(m) { return None; } From ac33fb74ece1bc40ac7c6e28fc69acfdd20ef023 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 04:57:27 +0500 Subject: [PATCH 122/221] Add the decorated pot's back-face culling regression test `DecoratedPotRenderer` submits every part with `RenderTypes.entitySolid`, whose pipeline culls back faces. The pot's `top` and `bottom` are flat boxes, so without that cull both sides of each plane are drawn and they z-fight: the pot renders wrong (kacpherek's #2099 draws the cull). The test renders a plain pot and checks that all of vanilla's 28 submitted quads are kept and that every one of them is marked for the cull, so the behaviour cannot silently regress. It fails without the cull. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- .../horizon-client/src/block_entity_render.rs | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index e8447ecf3..3e4e2790d 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -2118,4 +2118,70 @@ mod tests { assert_eq!(first_line("\u{6771}", 3.0, &advance), "\u{6771}"); assert_eq!(first_line("ab\ncd", 100.0, &advance), "ab"); } + /// `DecoratedPotRenderer` submits every part with `RenderTypes.entitySolid`, + /// whose pipeline culls back faces. The pot's `top` and `bottom` are flat + /// boxes, so without that cull both sides of each plane are drawn and they + /// z-fight: the pot renders wrong. + #[test] + fn the_decorated_pot_culls_its_back_faces() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("entity-models.json").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let registry = assets.registry; + let renderer = BlockEntityRenderer::load(&root, ®istry).unwrap(); + let state = registry.default_state("minecraft:decorated_pot").unwrap(); + let sprites: HashMap = [ + "entity/decorated_pot/decorated_pot_base", + "entity/decorated_pot/decorated_pot_side", + ] + .into_iter() + .map(|name| { + ( + name.to_owned(), + Rect { + u0: 0.25, + v0: 0.125, + u1: 0.375, + v1: 0.25, + w: 16, + h: 16, + }, + ) + }) + .collect(); + let world = World::new(BlockStateId(0), 1); + let scene = Scene { + camera: DVec3::ZERO, + orientation: Quat::IDENTITY, + anim: &|_| BlockAnim::default(), + texts: None, + partial: 0.5, + game_time: 0, + max_y: 320, + world: &world, + sprites: &sprites, + nether: false, + lid: &|_| 0.0, + sign: &|_| None, + banner: &|_| Vec::new(), + skull: &|_| None, + glyph: &|_| (None, 0.0), + }; + let mut verts = Vec::new(); + renderer.render_block(&scene, [0; 3], state.0, Mat4::IDENTITY, 0xff, &mut verts); + // Vanilla submits 28 quads for a plain pot, and the cull keeps them all. + assert_eq!( + verts.len() / 4, + 28, + "the pot submits all of vanilla's quads" + ); + assert!( + verts.iter().all(|v| v.normal == CULL_BACK), + "entitySolid culls the pot's back faces" + ); + } } From 7250944a7c79b8c2371fafeb7714b9841ddf3e59 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 05:06:20 +0500 Subject: [PATCH 123/221] Test the decorated pot item's back-face culling too The pot in the hand and dropped on the ground is drawn by the same `DecoratedPotRenderer` model, through the item path, so its quads carry the cull as well. The test fails without it. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- .../horizon-client/src/item_render/special.rs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index 8a54f49bb..f93a4c6d9 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -686,4 +686,51 @@ mod tests { ); } } + /// `DecoratedPotRenderer` draws every part with `RenderTypes.entitySolid`, + /// whose pipeline culls back faces: the pot's flat `top` and `bottom` + /// planes would otherwise show both sides and z-fight in the hand too. + #[test] + fn the_decorated_pot_item_culls_its_back_faces() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("entity-models.json").exists() { + return; + } + let renderer = ItemRenderer::load(&root).unwrap(); + let sprite = Rect { + u0: 0.25, + v0: 0.125, + u1: 0.375, + v1: 0.25, + w: 16, + h: 16, + }; + let sprites: HashMap = [ + "entity/decorated_pot/decorated_pot_base", + "entity/decorated_pot/decorated_pot_side", + ] + .into_iter() + .map(|name| (name.to_owned(), sprite)) + .collect(); + let model = SpecialModel { + kind: SpecialKind::DecoratedPot, + }; + let mut quads: Vec = Vec::new(); + submit( + &renderer, + &model, + &Value::Null, + false, + Mat4::IDENTITY, + &sprites, + &super::super::NoHost, + &mut quads, + ); + assert!(!quads.is_empty(), "the pot item draws its parts"); + assert!( + quads.iter().all(|q| q.cull_back), + "entitySolid culls the pot's back faces" + ); + } } From 80e28dfe634a8c501c35c28d2ce27ab31d8adf81 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 03:49:17 +0100 Subject: [PATCH 124/221] creative_mining harness: items.rs now lives in horizon-items Co-Authored-By: Claude Opus 5.5 --- tools/test_creative_mining_parity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_creative_mining_parity.py b/tools/test_creative_mining_parity.py index 3e6bfed1a..03a3de34e 100644 --- a/tools/test_creative_mining_parity.py +++ b/tools/test_creative_mining_parity.py @@ -28,7 +28,7 @@ def main(): 'Item.canDestroyBlock with each vanilla item, empty stacks, Survival/Creative ' 'abilities, and explicit/implicit tool overrides. Block destruction and network ' 'prediction call this predicate; end-to-end packet handling is not covered here.', - sources=[lab.ROOT / 'crates/horizon-client/src/items.rs']) + sources=[lab.ROOT / 'crates/horizon-items/src/items.rs']) if __name__ == '__main__': From 18b544770fa39df42ccd6c708f4b70d417c2cbff Mon Sep 17 00:00:00 2001 From: masa-masa-0314 <348336850+masa-masa-0314@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:17:54 +0800 Subject: [PATCH 125/221] Inventory: frame strips by the mcmeta's frame size `decode_one` cropped an animated block or item strip as `h > w -> w x w`, ignoring the mcmeta's `animation.width`/`height`: a pack texture that names its frame dimensions, or lays its frames along a row, packed the whole image as "frame 0" and was then drawn as a square frame over a rect sized for the image. The first frame now comes from `AnimationMetadataSection.frameSize`, resampled to its longer side the way the world's sprite arrays keep a frame square, and the sprite's GUI size is that square too. The atlas also gains the regression test the review asked for: a synthetic two-frame block strip whose mcmeta starts on the second frame registers in `sprite_animations`, and the atlas holds that frame at the sprite's rect; a row strip with explicit frame dimensions packs only its left frame. Co-Authored-By: ZCode --- crates/horizon-client/src/hud.rs | 136 ++++++++++++++++++++++++++++--- 1 file changed, 123 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index d2bef127e..2abed308e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -2,6 +2,7 @@ //! textures, and a batch of textured quads in GUI pixels (vanilla's automatic //! GUI scale is applied when drawing). use crate::Result; +use horizon_assets::animation::AnimationMetadata; use std::{ collections::{HashMap, HashSet}, fs, @@ -145,6 +146,21 @@ fn walk(dir: &Path, out: &mut Vec) { } /// A packed atlas image: sprite name, size and RGBA pixels. type PackedImage = (String, u32, u32, Vec); +/// A frame of an animated strip at `x, y`, nearest-resampled to the longer +/// side of the frame: array layers are square, as `Sprites::load` keeps them +/// for the world's sprite arrays. +fn strip_frame(pixels: &[u8], stride: u32, x: u32, y: u32, w: u32, h: u32) -> Vec { + let side = w.max(h); + let mut out = Vec::with_capacity((side * side * 4) as usize); + for row in 0..side { + let source_row = y + row * h / side; + for column in 0..side { + let at = ((source_row * stride + x + column * w / side) * 4) as usize; + out.extend_from_slice(&pixels[at..at + 4]); + } + } + out +} /// `image` inside a one-texel border copied from its opposite edges, the /// texels repeat addressing reads past each edge. fn wrap_border((name, w, h, data): &PackedImage) -> PackedImage { @@ -384,12 +400,35 @@ impl HudAtlas { .with_extension("") .to_string_lossy() .replace('\\', "/"); - let (w, mut h, pixels) = decode(path).ok()?; - // Animated strips keep their first frame. + let (mut w, mut h, pixels) = decode(path).ok()?; + let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); + let animation = mcmeta + .as_deref() + .and_then(|json| serde_json::from_str::(json).ok()) + .and_then(|meta| { + meta.get("animation") + .and_then(|section| AnimationMetadata::from_json(§ion.to_string()).ok()) + }); + // An animated strip keeps its first frame: the region the mcmeta's + // frame size picks (`AnimationMetadataSection.frameSize`), which is + // the top-left square unless it names other dimensions or the + // frames run along a row. let frames = name.starts_with("block/") || name.starts_with("item/"); - let pixels = if frames && h > w { - h = w; - pixels[..(w * w * 4) as usize].to_vec() + let pixels = if frames { + let stride = w; + let [fw, fh] = animation.as_ref().map_or([w.min(h) as i32; 2], |meta| { + meta.frame_size(w as i32, h as i32) + }); + match (u32::try_from(fw), u32::try_from(fh)) { + (Ok(fw), Ok(fh)) + if fw > 0 && fh > 0 && w % fw == 0 && h % fh == 0 && (fw, fh) != (w, h) => + { + let side = fw.max(fh); + (w, h) = (side, side); + strip_frame(&pixels, stride, 0, 0, fw, fh) + } + _ => pixels, + } } else { pixels }; @@ -397,16 +436,13 @@ impl HudAtlas { let gui_size = default_textures .as_ref() .and_then(|d| png_size(&d.join(format!("{name}.png")))) - .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .map(|(dw, dh)| { + let side = dw.min(dh); + if frames { (side, side) } else { (dw, dh) } + }) .filter(|&size| size != (w, h)); - let mcmeta = fs::read_to_string(path.with_extension("png.mcmeta")).ok(); let flags = mcmeta.as_deref().and_then(TextureFlags::from_mcmeta); - let animated = frames - && mcmeta.as_deref().is_some_and(|json| { - serde_json::from_str::(json) - .ok() - .is_some_and(|meta| meta.get("animation").is_some()) - }); + let animated = frames && animation.is_some(); let (gw, gh) = gui_size.unwrap_or((w, h)); (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( (name, w, h, pixels), @@ -1469,6 +1505,80 @@ impl HudRenderer { mod tests { use super::*; + /// Write a PNG `width x height` whose `frames` stacked rows are solid + /// colours, then its mcmeta beside it. + fn write_strip(path: &Path, width: u32, height: u32, frames: &[[u8; 4]], mcmeta: Option<&str>) { + let file = std::io::BufWriter::new(fs::File::create(path).unwrap()); + let mut encoder = png::Encoder::new(file, width, height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().unwrap(); + let mut pixels = Vec::with_capacity((width * height * 4) as usize); + for frame in frames { + let rows = height / frames.len() as u32; + pixels.extend((0..width * rows).flat_map(|_| *frame)); + } + writer.write_image_data(&pixels).unwrap(); + writer.finish().unwrap(); + if let Some(mcmeta) = mcmeta { + let meta = path.with_extension("png.mcmeta"); + fs::write(meta, mcmeta).unwrap(); + } + } + /// A resource root holding one animated block texture: a strip of two + /// 16x16 frames, red then blue, whose mcmeta starts on the blue one. + fn animated_root() -> PathBuf { + let root = std::env::temp_dir().join(format!("horizon-atlas-anim-{}", std::process::id())); + let block = root.join("assets/minecraft/textures/block"); + fs::create_dir_all(&block).unwrap(); + write_strip( + &block.join("test_anim.png"), + 16, + 32, + &[[255, 0, 0, 255], [0, 0, 255, 255]], + Some(r#"{"animation": {"frames": [1, 0]}}"#), + ); + root + } + fn texel_at(atlas: &HudAtlas, rect: Rect, x: u32, y: u32) -> [u8; 4] { + let px = (rect.u0 * atlas.width as f32).round() as u32 + x; + let py = (rect.v0 * atlas.height as f32).round() as u32 + y; + let at = ((py * atlas.width + px) * 4) as usize; + atlas.pixels[at..at + 4].try_into().unwrap() + } + #[test] + fn animated_block_sprites_register_and_pack_their_first_mcmeta_frame() { + let root = animated_root(); + let atlas = HudAtlas::build(&root).unwrap(); + let (rect, animation) = atlas + .sprite_animations + .iter() + .find(|(_, animation)| animation.frame_count() == 2) + .expect("the animated block sprite"); + // The mcmeta's list starts on the strip's second (blue) frame. + assert_eq!(animation.frame(0), 1); + assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16)); + assert_eq!(texel_at(&atlas, *rect, 0, 0), [0, 0, 255, 255]); + assert_eq!(texel_at(&atlas, *rect, 15, 15), [0, 0, 255, 255]); + } + #[test] + fn a_strip_frames_size_comes_from_its_mcmeta() { + let root = animated_root(); + let block = root.join("assets/minecraft/textures/block"); + // A row of two frames with the animation's own frame size. + write_strip( + &block.join("test_row.png"), + 32, + 16, + &[[0, 255, 0, 255], [255, 255, 0, 255]], + Some(r#"{"animation": {"width": 16, "height": 16}}"#), + ); + let atlas = HudAtlas::build(&root).unwrap(); + let rect = atlas.sprites["block/test_row"]; + // The first frame is the left 16x16, not the whole row. + assert_eq!(rect.texels((atlas.width, atlas.height)), (16, 16)); + assert_eq!(texel_at(&atlas, rect, 0, 0), [0, 255, 0, 255]); + } /// `count` images of `w x h`; layout reads only their sizes. fn sized(count: usize, w: u32, h: u32) -> Vec { (0..count) From b7749dd0d2b87b29ca01bbf40990cbc467bc34e8 Mon Sep 17 00:00:00 2001 From: levzzz <86072227+levzzz5154@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:38:03 +0500 Subject: [PATCH 126/221] Fix a needless borrow in the decorated pot's test Clippy's needless_borrow: the registry is already a reference, so the extra & is dereferenced right away. Co-Authored-By: minimax-m3.1-flash (Claude Code) --- crates/horizon-client/src/block_entity_render.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 3e4e2790d..c7ae80b22 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -2132,7 +2132,7 @@ mod tests { } let assets = crate::assets::Assets::load(&root).unwrap(); let registry = assets.registry; - let renderer = BlockEntityRenderer::load(&root, ®istry).unwrap(); + let renderer = BlockEntityRenderer::load(&root, registry).unwrap(); let state = registry.default_state("minecraft:decorated_pot").unwrap(); let sprites: HashMap = [ "entity/decorated_pot/decorated_pot_base", From 0c9bddecda77f837232ff424c9924af62bc42421 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:11:01 +0100 Subject: [PATCH 127/221] Let block hoppers move items into and out of minecart containers --- crates/horizon-client/src/game/machines.rs | 197 ++++++++++++++++----- 1 file changed, 153 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 0562af8cd..01e9e3acf 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -593,27 +593,41 @@ impl Game<'_> { self.container_changed(pos); } } - /// `HopperBlockEntity.ejectItems`. + /// `HopperBlockEntity.ejectItems`: into the block container in front, else + /// a container entity there (`getContainerAt`). fn hopper_eject(&mut self, pos: Pos, hopper: &View) -> bool { let state = self.world.block(pos.0, pos.1, pos.2); let c = self.containers(); let Some(facing) = c.prop(state, "facing").and_then(dir_from_name) else { return false; }; - let Some(target) = c.view(offset(pos, facing), false) else { + let front = offset(pos, facing); + let face = facing.opposite(); + if let Some(target) = c.view(front, false) { + return self.eject_into(pos, hopper, &target, face); + } + let Some(id) = self.entity_container_at([ + f64::from(front.0) + 0.5, + f64::from(front.1) + 0.5, + f64::from(front.2) + 0.5, + ]) else { return false; }; - let face = facing.opposite(); - if c.is_full(&target, face) { + self.with_entity_container(id, |g, target| g.eject_into(pos, hopper, target, face)) + .unwrap_or(false) + } + /// The rest of `HopperBlockEntity.ejectItems`: one item into `target`. + fn eject_into(&mut self, pos: Pos, hopper: &View, target: &View, face: Direction) -> bool { + if self.containers().is_full(target, face) { return false; } for slot in 0..hopper.len() { let Some(one) = self.take_one(hopper, slot) else { continue; }; - match self.add_item(Some(pos), &target, one, Some(face)) { + match self.add_item(Some(pos), target, one, Some(face)) { None => { - self.view_changed(&target); + self.view_changed(target); return true; } Some(rest) => self.put_back(hopper, slot, rest), @@ -624,7 +638,12 @@ impl Game<'_> { /// `HopperBlockEntity.suckInItems`: from the container above, or item entities. fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool { let above = (pos.0, pos.1 + 1, pos.2); - if let Some(took) = self.suck_from_container(above, hopper) { + let at = [ + f64::from(pos.0) + 0.5, + f64::from(pos.1) + 1.5, + f64::from(pos.2) + 0.5, + ]; + if let Some(took) = self.suck_from_container(above, at, hopper) { return took; } let above_state = self.world.block(above.0, above.1, above.2); @@ -658,11 +677,16 @@ impl Game<'_> { self.suck_item_entities(hopper, min, max) } /// The container half of `HopperBlockEntity.suckInItems`: one item from the - /// container at `above`, through its bottom face. `None` when there is no - /// container there. - fn suck_from_container(&mut self, above: Pos, hopper: &View) -> Option { + /// container at `above`, through its bottom face; with no block container + /// there, from a container entity whose box meets the one around `at` + /// (`getSourceContainerOrHandler`). `None` when there is no container. + fn suck_from_container(&mut self, above: Pos, at: [f64; 3], hopper: &View) -> Option { let c = self.containers(); - let source = c.view(above, false)?; + let Some(source) = c.view(above, false) else { + let id = self.entity_container_at(at)?; + return self + .with_entity_container(id, |g, source| g.suck_from_slots(None, source, hopper)); + }; if let Kind::Composter(level) = source.kind { if level != 8 { return Some(false); @@ -681,26 +705,133 @@ impl Game<'_> { return Some(moved); } let source_hopper = (source.kind == Kind::Hopper).then_some(above); + Some(self.suck_from_slots(source_hopper, &source, hopper)) + } + /// `HopperBlockEntity.tryTakeInItemFromSlot` over the `DOWN` face of `source`. + fn suck_from_slots( + &mut self, + source_hopper: Option, + source: &View, + hopper: &View, + ) -> bool { for slot in source.slots_for_face(Some(Direction::Down)) { let c = self.containers(); - let Some(stack) = c.get(&source, slot) else { + let Some(stack) = c.get(source, slot) else { continue; }; - if !c.can_take(&source, slot, stack, Direction::Down) { + if !c.can_take(source, slot, stack, Direction::Down) { continue; } - let Some(one) = self.take_one(&source, slot) else { + let Some(one) = self.take_one(source, slot) else { continue; }; match self.add_item(source_hopper, hopper, one, None) { None => { - self.view_changed(&source); - return Some(true); + self.view_changed(source); + return true; } - Some(rest) => self.put_back(&source, slot, rest), + Some(rest) => self.put_back(source, slot, rest), } } - Some(false) + false + } + /// `HopperBlockEntity.getEntityContainer`: one of the alive container + /// entities (`EntitySelector.CONTAINER_ENTITY_SELECTOR`: chest and hopper + /// minecarts, chest boats) whose box meets the 1x1x1 box around `at`, + /// picked at random. + fn entity_container_at(&mut self, at: [f64; 3]) -> Option { + let meets = |b: horizon_core::geometry::Aabb| { + let (lo, hi) = (b.min_position(), b.max_position()); + lo.x < at[0] + 0.5 + && hi.x > at[0] - 0.5 + && lo.y < at[1] + 0.5 + && hi.y > at[1] - 0.5 + && lo.z < at[2] + 0.5 + && hi.z > at[2] - 0.5 + }; + let mut found: Vec = self + .carts + .iter() + .filter(|c| { + matches!( + c.kind, + super::minecarts::CartKind::Chest | super::minecarts::CartKind::Hopper + ) && meets(c.bounds()) + }) + .map(|c| c.id) + .collect(); + found.extend( + self.boats + .iter() + .filter(|b| b.chest && meets(b.bounds())) + .map(|b| b.id), + ); + if found.is_empty() { + return None; + } + let pick = self + .world + .random + .next_int_bound(found.len() as i32) + .unwrap_or(0); + found.get(pick as usize).copied() + } + /// Runs `f` on a container entity's items as a container, under the + /// placeholder key its menu uses (the open menu's copy when it is open), + /// then hands the items back to the entity. + fn with_entity_container( + &mut self, + id: u32, + f: impl FnOnce(&mut Self, &View) -> R, + ) -> Option { + let mut items = if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + std::mem::take(&mut c.items) + } else { + std::mem::take(&mut self.boats.iter_mut().find(|b| b.id == id)?.items) + }; + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, id as i32); + let (view, open) = self.lend_items(key, &mut items); + let result = f(self, &view); + self.reclaim_items(key, open, &mut items); + if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + c.items = items; + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + b.items = items; + } + Some(result) + } + /// A vehicle's slots as a container under its placeholder `key`. When its + /// menu is open the placeholder is the live copy and stays as it is. + /// Returns the view and whether the menu was open. + fn lend_items(&mut self, key: Pos, items: &mut Vec>) -> (View, bool) { + let open = self.world.block_entities.contains_key(&key); + if !open { + let slots = BlockEntity::Chest(std::mem::take(items)); + self.world.block_entities.insert(key, slots); + } + let size = self + .world + .block_entities + .get(&key) + .map_or(0, |e| e.slots().len()); + let view = View { + parts: vec![(key, size)], + kind: Kind::Generic, + }; + (view, open) + } + /// Gives `lend_items`' slots back to the vehicle, so its own items stay + /// the one source of truth: a menu copy that is still around (open, or + /// left by a guest's close) gets the changed items copied to `items`. + fn reclaim_items(&mut self, key: Pos, open: bool, items: &mut Vec>) { + let slots = if open { + self.world.block_entities.get(&key).cloned() + } else { + self.world.block_entities.remove(&key) + }; + if let Some(BlockEntity::Chest(slots)) = slots { + *items = slots; + } } /// The item half of `HopperBlockEntity.suckInItems` (`getItemsAtAndAbove`): /// adds the item entities that meet the box, until one is taken whole. @@ -736,20 +867,7 @@ impl Game<'_> { // The cart's slots are edited as a container under the placeholder key // its menu uses; when that menu is open the placeholder is the live copy. let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, cart.id as i32); - let open = self.world.block_entities.contains_key(&key); - if !open { - let items = BlockEntity::Chest(std::mem::take(&mut cart.items)); - self.world.block_entities.insert(key, items); - } - let size = self - .world - .block_entities - .get(&key) - .map_or(0, |e| e.slots().len()); - let view = View { - parts: vec![(key, size)], - kind: Kind::Generic, - }; + let (view, open) = self.lend_items(key, &mut cart.items); let p = cart.position; // getLevelY is the cart's y + 0.5, so the container is the block at // y + 1.5, and Hopper.SUCK_AABB (moved by getLevel - 0.5) starts 11/16 @@ -759,7 +877,8 @@ impl Game<'_> { (p.y + 1.5).floor() as i32, p.z.floor() as i32, ); - let took = match self.suck_from_container(above, &view) { + let at = [p.x, p.y + 1.5, p.z]; + let took = match self.suck_from_container(above, at, &view) { Some(took) => took, None => self.suck_item_entities( &view, @@ -777,17 +896,7 @@ impl Game<'_> { [hi.x + 0.25, hi.y, hi.z + 0.25], ); } - // The cart's own items stay the one source of truth: a menu copy that - // is still around (open, or left by a guest's close) gets the pulled - // items back into `cart.items`, so reopening never restores a stale copy. - let slots = if open { - self.world.block_entities.get(&key).cloned() - } else { - self.world.block_entities.remove(&key) - }; - if let Some(BlockEntity::Chest(items)) = slots { - cart.items = items; - } + self.reclaim_items(key, open, &mut cart.items); } // ---- dispensers and droppers ---- From ff28fd839036a7c3f88203a428bd6c23a92963f9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:13:40 +0100 Subject: [PATCH 128/221] Read a chiseled bookshelf's last slot and a shelf's back mask with a comparator --- crates/horizon-client/src/game.rs | 7 +++- crates/horizon-client/src/game/machines.rs | 39 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..087b15dc7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -700,7 +700,7 @@ impl LevelAccess for GameLevel<'_> { &self, pos: BlockPos, state: BlockStateId, - _direction: Direction, + direction: Direction, ) -> i32 { if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) { return signal; @@ -725,6 +725,11 @@ impl LevelAccess for GameLevel<'_> { if let Some(signal) = books::lectern_signal(self.world, pos) { return signal; } + if let Some(signal) = + machines::shelf_signal(self.world, self.registry, state, pos, direction) + { + return signal; + } machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } fn block_entity_signal( diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index bb936744b..f398f4511 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -399,6 +399,45 @@ pub(super) fn container_signal( .map_or(0, |v| c.signal(&v)) } +/// `ChiseledBookShelfBlock.getAnalogOutputSignal` and +/// `ShelfBlock.getAnalogOutputSignal`, from the block entity Horizon keeps as +/// it was loaded; `None` for any other block. `direction` points from the +/// block to the comparator. +pub(super) fn shelf_signal( + world: &World, + registry: &'static horizon_world::registry::BlockRegistry, + state: BlockStateId, + pos: BlockPos, + direction: Direction, +) -> Option { + let info = registry.state(state)?; + let chiseled = info.name == "minecraft:chiseled_bookshelf"; + if !chiseled && !info.name.ends_with("_shelf") { + return None; + } + let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); + if chiseled { + // The last slot touched, plus one (`lastInteractedSlot` starts at -1). + let last = tag + .as_ref() + .and_then(|t| horizon_client::save::number(t.get("last_interacted_slot"))); + return Some(last.map_or(0, |slot| slot as i32 + 1)); + } + // Only read from the back: a bit for each of the three slots in use. + let facing = info.properties.get("facing").and_then(|f| dir_from_name(f)); + if facing.map(Direction::opposite) != Some(direction) { + return Some(0); + } + let items = horizon_client::save::decode_items(tag.as_ref().and_then(|t| t.get("Items")), 3); + Some( + items + .iter() + .enumerate() + .map(|(slot, item)| i32::from(item.is_some()) << slot) + .sum(), + ) +} + impl Game<'_> { fn containers(&self) -> Containers<'_> { Containers { From f92cf816b17e8376d497c67a4d9edea9f2facb25 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:16:32 +0100 Subject: [PATCH 129/221] Pick blocks and entities on the server like vanilla --- crates/horizon-client/src/game.rs | 14 ++- crates/horizon-client/src/game/lan_actions.rs | 63 ++++++++++-- crates/horizon-client/src/game/pick_entity.rs | 98 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 11 ++- crates/horizon-protocol/src/packets/play.rs | 2 + 5 files changed, 179 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/game/pick_entity.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..475c3b7fc 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -131,6 +131,7 @@ mod paintings; mod passengers; mod persist; mod perspective; +mod pick_entity; mod pickups; mod piglins; mod player_equip; @@ -11524,7 +11525,18 @@ impl Game<'_> { // Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock: // the block's clone item, with its block entity's data on Ctrl in // creative, picked from the inventory (`pick_item`). - if let Some(hit) = self.pick() { + if let Some(entity) = self.pick_entity_hit() { + // handlePickItemFromEntity: the entity's pick result. + if let Some(stack) = entity.and_then(|id| self.entity_pick_result(id)) { + let infinite = self.creative; + horizon_client::pick_item::pick( + &mut self.inventory[..36], + &mut self.selected, + &stack, + infinite, + ); + } + } else if let Some(hit) = self.pick() { let include_data = self.creative && self.has_control_down(); if let Some(stack) = self.picked_stack(hit.pos, include_data) { let infinite = self.creative; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..81e34de6a 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1374,19 +1374,68 @@ impl Game<'_> { .unwrap_or_default(); host.hub.send_stats(conn, &stats); } + // handlePickItemFromBlock: a block within the block reach plus 1, its + // data only with infinite materials. S::PickItemFromBlock(p) => { - let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let item = self.res.facts().get(state).item.clone(); - let g = &mut host.hub.guests[gi]; - if g.creative() && &*item != "minecraft:air" { - let slot = g.selected; - g.inventory[slot] = Some(ItemStack::new(&item, 1)); - } + self.guest_pick_item(host, conn, |g| { + let eye = g.eye_position()?; + let d2: f64 = (0..3) + .map(|a| { + let lo = f64::from(p.pos[a]); + (eye[a] - eye[a].clamp(lo, lo + 1.0)).powi(2) + }) + .sum(); + let range = g.reach() + 1.0; + if d2 >= range * range { + return None; + } + g.picked_stack(p.pos, g.creative && p.include_data) + }); + } + // handlePickItemFromEntity. + S::PickItemFromEntity(p) => { + self.guest_pick_item(host, conn, |g| { + g.within_entity_range(p.id) + .then(|| g.entity_pick_result(p.id)) + .flatten() + }); } _ => {} } } + /// `ServerGamePacketListenerImpl.tryPickItem` for the guest: a matching stack + /// is selected, else a creative player gets the item; the held slot is sent + /// back and the changed slots follow with the tick's inventory changes. + fn guest_pick_item( + &mut self, + host: &mut LanHost, + conn: u32, + stack: impl FnOnce(&mut Self) -> Option, + ) { + let picked = self.as_guest(host, conn, |g| { + let stack = stack(g)?; + let infinite = g.creative; + horizon_client::pick_item::pick( + &mut g.inventory[..36], + &mut g.selected, + &stack, + infinite, + ); + Some(()) + }); + if picked.flatten().is_some() + && let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) + { + host.hub.send_to( + conn, + &C::SetHeldSlot(play::SetHeldSlot { + slot: g.selected as i32, + }), + ); + } + } + fn item_from_network( &self, host: &LanHost, diff --git a/crates/horizon-client/src/game/pick_entity.rs b/crates/horizon-client/src/game/pick_entity.rs new file mode 100644 index 000000000..5efc54d44 --- /dev/null +++ b/crates/horizon-client/src/game/pick_entity.rs @@ -0,0 +1,98 @@ +//! Pick Block on an entity (`Minecraft.pickBlockOrEntity`'s entity case and +//! `ServerGamePacketListenerImpl.handlePickItemFromEntity`): the client aims, +//! the server answers with `Entity.getPickResult`. +use super::Game; +use horizon_client::items::ItemStack; + +impl Game<'_> { + /// The entity the crosshair hits before any block, as `Entity.getId`; an + /// entity with nothing to pick (a projectile, a player, the dragon) is + /// `Some(None)`. `None` when the view hits a block or nothing. + pub(super) fn pick_entity_hit(&self) -> Option> { + let mut best: Option<(f64, Option)> = None; + let mut offer = |distance: f64, id: Option| { + if self.before_block(distance) && best.is_none_or(|b| distance < b.0) { + best = Some((distance, id)); + } + }; + if let Some(hit) = self.remote_object_hit(true) { + offer(hit.distance, Some(hit.id)); + } + if let Some((i, d)) = self.mob_hit() { + offer(d, Some(self.mobs[i].id as i32)); + } + if let Some((_, d)) = self.guest_hit() { + offer(d, None); + } + if let Some((_, d)) = self.redirectable_hit() { + offer(d, None); + } + if let Some((_, d)) = self.dragon_hit() { + offer(d, None); + } + best.map(|b| b.1) + } + + /// `Entity.getPickResult` of the entity `id`: a mob's spawn egg, the item + /// of a boat, minecart, armor stand, cushion, painting, item frame (the + /// framed item when it holds one) or end crystal. + pub(super) fn entity_pick_result(&self, id: i32) -> Option { + let id = u32::try_from(id).ok()?; + let item = if let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // Mob.getPickResult: SpawnEggItem.byId. + let egg = format!("{}_spawn_egg", m.kind.id); + return self.res.items().get(&egg).map(|_| ItemStack::new(&egg, 1)); + } else if let Some(b) = self.boats.iter().find(|b| b.id == id) { + b.entity_type() + } else if let Some(c) = self.carts.iter().find(|c| c.id == id) { + c.kind.id().to_owned() + } else if self.armor_stands.iter().any(|a| a.id == id) { + "minecraft:armor_stand".to_owned() + } else if let Some(c) = self.cushions.iter().find(|c| c.id == id) { + c.item() + } else if let Some(f) = self.item_frames.iter().find(|f| f.id == id) { + // ItemFrame.getPickResult: what it frames, else the frame itself. + return Some( + f.item + .clone() + .unwrap_or_else(|| ItemStack::new(f.kind(), 1)), + ); + } else if self.paintings.iter().any(|p| p.id == id) { + "minecraft:painting".to_owned() + } else if self.crystals.iter().any(|c| c.id == id) { + "minecraft:end_crystal".to_owned() + } else { + return None; + }; + Some(ItemStack::new(&item, 1)) + } + + /// `Player.isWithinEntityInteractionRange(entity, 3.0)`: the entity's box + /// within the interaction range plus 3 of the eyes. + pub(super) fn within_entity_range(&self, id: i32) -> bool { + let Some(eye) = self.eye_position() else { + return false; + }; + let mob = u32::try_from(id) + .ok() + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| m.bounds()); + let Some(b) = self + .object_target(id) + .map(|(lo, hi, _)| (lo, hi)) + .or_else(|| { + mob.or_else(|| self.tracked_special_box(id)).map(|b| { + let (lo, hi) = (b.min_position(), b.max_position()); + ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) + }) + }) + else { + return false; + }; + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(b.0[a], b.1[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..e6261bbf8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -5595,7 +5595,16 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ self.0.remote_use(); } fn pick(&mut self) { - if let Some(hit) = self.0.pick() { + // Minecraft.pickBlockOrEntity: an entity before the block is asked + // for (`handlePickItemFromEntity`), else the block. + if let Some(entity) = self.0.pick_entity_hit() { + if let Some(id) = entity { + self.0.send(S::PickItemFromEntity(play::PickItemFromEntity { + id, + include_data: self.0.has_control_down(), + })); + } + } else if let Some(hit) = self.0.pick() { self.0.send(S::PickItemFromBlock(play::PickItemFromBlock { pos: hit.pos, include_data: self.0.has_control_down(), diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 7ab82720d..5138197c3 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2234,6 +2234,7 @@ packet!( PaddleBoat { left: bool => Bool, right: bool => Bool } ); packet!(PickItemFromBlock { pos: [i32; 3] => Pos, include_data: bool => Bool }); +packet!(PickItemFromEntity { id: i32 => VarInt, include_data: bool => Bool }); packet!( /// ServerboundPlayerActionPacket.Action: 0 start destroy, 1 change destroy /// direction, 2 abort, 3 stop destroy, 4 drop all, 5 drop item, 6 release @@ -2311,6 +2312,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { MoveVehicle(MoveVehicleRequest) = MOVE_VEHICLE, PaddleBoat(PaddleBoat) = PADDLE_BOAT, PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, + PickItemFromEntity(PickItemFromEntity) = PICK_ITEM_FROM_ENTITY, PingRequest(crate::packets::status::Ping) = PING_REQUEST, PlayerAbilities(PlayerAbilitiesRequest) = PLAYER_ABILITIES, PlayerAction(PlayerAction) = PLAYER_ACTION, From 80fd68e1c23997acc1bd6629d5961710d76bc3ea Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:16:45 +0100 Subject: [PATCH 130/221] Send the dragon's breath cloud particle to the client --- crates/horizon-client/src/game/lan_entities.rs | 4 +++- crates/horizon-client/src/game/lan_particles.rs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 665710be2..da58f4300 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -469,7 +469,9 @@ impl Game<'_> { // The dragon's breath 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( + // The hub is out of `self.lan` meanwhile, so it is passed in. + let breath = Self::hub_particle( + hub, &horizon_client::particles::ParticleOptions::simple( horizon_client::particles::ParticleType::DragonBreath, ), diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 648cef962..c7740cc4e 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -156,7 +156,7 @@ impl Game<'_> { /// `network_particle` for a hub that is out of `self.lan` meanwhile (a /// guest's turn). - fn hub_particle( + pub(super) fn hub_particle( hub: &Hub, options: &ParticleOptions, state: Option, From 29ab66935e357a547da200a59af3162e36dbef93 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:17:48 +0100 Subject: [PATCH 131/221] Restart a break when the held item changes and reset the attack strength when it stops --- crates/horizon-client/src/game/hand.rs | 9 ++++++--- crates/horizon-client/src/game/remote.rs | 17 ++++++++++++----- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index d91d3b979..7c12223c9 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -144,6 +144,11 @@ impl Game<'_> { let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); speed / facts.hardness / if harvest { 30.0 } else { 100.0 } } + /// A key for the main-hand stack (`destroyingItem`): its item and components. + pub(super) fn main_hand_key(&self) -> String { + self.held() + .map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra)) + } /// Whether an attack would hit an entity rather than the block behind /// it: the crosshair's `EntityHitResult`. pub(super) fn entity_targeted(&self) -> bool { @@ -445,9 +450,7 @@ impl HandWorld for GameHands<'_, '_> { true } fn main_hand_key(&mut self) -> String { - self.game - .held() - .map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra)) + self.game.main_hand_key() } fn destroy_stage(&mut self, _: [i32; 3], _: Option) {} fn swing(&mut self, hand: Hand, animation: SwingAnimation) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..d128602c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -187,6 +187,8 @@ pub(super) struct Remote { /// The local player's profile name: its score holder and team member. pub(super) profile_name: String, destroying: Option<([i32; 3], u8, f32)>, + /// `MultiPlayerGameMode.destroyingItem`: the held item key the break began with. + destroying_item: String, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, stop_mining: bool, @@ -471,6 +473,7 @@ impl Game<'_> { profile: 0, profile_name: String::new(), destroying: None, + destroying_item: String::new(), destroy_delay: 0, input: Default::default(), stop_mining: false, @@ -3837,6 +3840,8 @@ impl Game<'_> { } } + /// `MultiPlayerGameMode.stopDestroyBlock`: aborts the break and starts + /// the attack strength again. pub(super) fn stop_remote_mining(&mut self) { if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { self.send(S::PlayerAction(play::PlayerAction { @@ -3845,6 +3850,7 @@ impl Game<'_> { direction: 0, sequence: 0, })); + self.reset_attack_strength(); } } @@ -3898,11 +3904,11 @@ impl Game<'_> { } else { self.destroy_progress(hit.pos) }; - let same = self - .remote - .as_ref() - .and_then(|r| r.destroying) - .is_some_and(|(p, _, _)| p == hit.pos); + // sameDestroyTarget: the same block and still the item the break began with. + let held = self.main_hand_key(); + let same = self.remote.as_ref().is_some_and(|r| { + r.destroying.is_some_and(|(p, _, _)| p == hit.pos) && r.destroying_item == held + }); if start && same { return; } @@ -3929,6 +3935,7 @@ impl Game<'_> { } if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); + r.destroying_item = held; } self.mining = Some(Mining { pos: hit.pos, From 59bdb0059992dd7438a3cf0ee38f4fdcae495a7d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:19:41 +0100 Subject: [PATCH 132/221] Husk, cave spider, wither skeleton, bee and pufferfish effects only come when the hit lands --- crates/horizon-client/src/game/creatures.rs | 12 +++++++++++ crates/horizon-client/src/game/lan_mobs.rs | 1 + crates/horizon-client/src/mobs.rs | 10 +++++++++ crates/horizon-client/src/mobs/ai.rs | 24 ++++++++++++++++++++- crates/horizon-client/src/mobs/aquatic.rs | 7 +++--- crates/horizon-client/src/mobs/bee.rs | 6 ++++-- 6 files changed, 53 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..bd32153d5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -961,6 +961,18 @@ impl Game<'_> { MobEvent::AttackPlayer(amount, from) => { self.mob_hits_player(amount, from, "minecraft:mob_attack"); } + // doHurtTarget: the effect only when hurtServer took damage. + MobEvent::AttackPlayerWithEffect { + amount, + from, + effect, + ticks, + amplifier, + } => { + if self.mob_hits_player(amount, from, "minecraft:mob_attack") { + self.give_player_effect(effect, ticks, amplifier); + } + } MobEvent::DamagePlayer { amount, from, kind } => { self.mob_hits_player(amount, from, kind); } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 6527f1015..f9d997452 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -65,6 +65,7 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool { matches!( e, MobEvent::AttackPlayer(..) + | MobEvent::AttackPlayerWithEffect { .. } | MobEvent::DamagePlayer { .. } | MobEvent::Push { target: Who::Player, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..ef93a2ff4 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -968,6 +968,16 @@ pub enum MobEvent { state: horizon_world::registry::BlockStateId, }, AttackPlayer(f32, [f64; 3]), + /// A melee hit whose effect comes only if the hit lands (husk hunger, + /// cave spider poison, wither skeleton wither, bee and pufferfish + /// poison): a shield-blocked hit gives nothing. + AttackPlayerWithEffect { + amount: f32, + from: [f64; 3], + effect: &'static str, + ticks: i32, + amplifier: i32, + }, /// Damage of a given type to the player (guardian lasers, thorns). DamagePlayer { amount: f32, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 26b94eeac..0bd93d151 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1419,6 +1419,7 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { let mut amount = m.attrs.attack_damage; let from = [m.position.x, m.position.y, m.position.z]; let source = Damage::mob(m.id, from); + let first_event = cx.events.len(); match m.species() { // Difficulty NORMAL: cave spiders poison for 7 seconds. Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer { @@ -1480,7 +1481,28 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }); } match who { - Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)), + // The effect picked above goes with the hit: it applies only when + // the player takes damage (a shield-blocked hit gives none). + Who::Player => { + let effect = cx.events[first_event..] + .iter() + .position(|e| matches!(e, MobEvent::EffectPlayer { .. })) + .map(|k| cx.events.remove(first_event + k)); + cx.events.push(match effect { + Some(MobEvent::EffectPlayer { + effect, + ticks, + amplifier, + }) => MobEvent::AttackPlayerWithEffect { + amount, + from, + effect, + ticks, + amplifier, + }, + _ => MobEvent::AttackPlayer(amount, from), + }); + } Who::Mob(id) => cx.events.push(MobEvent::AttackMob { target: id, amount, diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index f63a42239..3f42ddd31 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -244,11 +244,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { && m.ai.no_action_time % 10 == 0 { let amount = 1.0 + m.extra.size as f32; - events.push(MobEvent::AttackPlayer( + // Only when the sting hurt the player. + events.push(MobEvent::AttackPlayerWithEffect { amount, - [m.position.x, m.position.y, m.position.z], - )); - events.push(MobEvent::EffectPlayer { + from: [m.position.x, m.position.y, m.position.z], effect: "minecraft:poison", ticks: 60 * m.extra.size, amplifier: 0, diff --git a/crates/horizon-client/src/mobs/bee.rs b/crates/horizon-client/src/mobs/bee.rs index 27d8e7c84..330625fb0 100644 --- a/crates/horizon-client/src/mobs/bee.rs +++ b/crates/horizon-client/src/mobs/bee.rs @@ -322,9 +322,11 @@ pub fn sting(m: &mut Mob, who: Who, cx: &mut Cx) { let amount = (m.attrs.attack_damage as i32) as f32; match who { Who::Player => { - cx.events.push(MobEvent::AttackPlayer(amount, from)); + // Bee.doHurtTarget: the poison only when the sting hurt. let seconds = if cx.w.difficulty.hard { 18 } else { 10 }; - cx.events.push(MobEvent::EffectPlayer { + cx.events.push(MobEvent::AttackPlayerWithEffect { + amount, + from, effect: "minecraft:poison", ticks: seconds * 20, amplifier: 0, From 85f34393fe6438c0b5563496408907bcf429cae2 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:21:01 +0100 Subject: [PATCH 133/221] Save and load creative toolbars with the toolbar keys --- crates/horizon-client/src/game.rs | 12 +++++- .../src/game/creative_hotbar.rs | 39 +++++++++++++++++++ crates/horizon-client/src/hotbar.rs | 20 ++++++++++ 3 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-client/src/game/creative_hotbar.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..a0e9e6b3c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod consume; mod control; mod copper_golems; mod creaking; +mod creative_hotbar; mod creatures; mod crossbow; pub(crate) mod cushions; @@ -11471,7 +11472,7 @@ impl Game<'_> { | KeyCode::Digit9 if self.screen == Screen::Playing => { - self.selected = match key { + let slot = match key { KeyCode::Digit1 => 0, KeyCode::Digit2 => 1, KeyCode::Digit3 => 2, @@ -11482,6 +11483,15 @@ impl Game<'_> { KeyCode::Digit8 => 7, _ => 8, }; + // Minecraft.handleKeybinds: a creative player holding the load + // or save toolbar key loads or saves a toolbar instead (load + // first when both are held). + let load = self.mapped_key_down("key.loadToolbarActivator"); + if self.creative && (load || self.mapped_key_down("key.saveToolbarActivator")) { + self.hotbar_load_or_save(slot, load); + } else { + self.selected = slot; + } } _ => {} } diff --git a/crates/horizon-client/src/game/creative_hotbar.rs b/crates/horizon-client/src/game/creative_hotbar.rs new file mode 100644 index 000000000..81e5ad6c4 --- /dev/null +++ b/crates/horizon-client/src/game/creative_hotbar.rs @@ -0,0 +1,39 @@ +//! The creative toolbars, `hotbar.nbt` beside `options.txt`: hold the save or +//! load key and press a hotbar key (`Minecraft.handleKeybinds`). +use super::Game; +use horizon_client::{hotbar, keybinds, text::Text}; + +impl Game<'_> { + /// Whether the key bound to `mapping` is held. + pub(super) fn mapped_key_down(&self, mapping: &str) -> bool { + keybinds::key_code(self.settings.keys.get(mapping)) + .is_some_and(|k| self.physical_keys.contains(&k)) + } + + /// `CreativeModeInventoryScreen.handleHotbarLoadOrSave` for the hotbar key + /// `index`: load puts the saved row in the hotbar (the creative slot + /// packets follow from the inventory change), save stores the hotbar and + /// says so on the action bar. + pub(super) fn hotbar_load_or_save(&mut self, index: usize, load: bool) { + let path = Self::options_path().with_file_name("hotbar.nbt"); + let known = |id: &str| self.res.items().get(id).is_some(); + let mut rows = hotbar::load(&path, &known); + if load { + for (slot, stack) in rows[index].iter().enumerate() { + self.inventory[slot] = stack.clone(); + } + return; + } + rows[index] = self.inventory[..hotbar::SIZE].to_vec(); + let _ = hotbar::save(&path, &rows); + let key = |mapping: &str| keybinds::display_name(self.settings.keys.get(mapping)); + let message = Text::translate( + "inventory.hotbarSaved", + &[ + key("key.loadToolbarActivator"), + key(&format!("key.hotbar.{}", index + 1)), + ], + ); + self.titles.set_overlay(message, false); + } +} diff --git a/crates/horizon-client/src/hotbar.rs b/crates/horizon-client/src/hotbar.rs index a60f28287..dccae7560 100644 --- a/crates/horizon-client/src/hotbar.rs +++ b/crates/horizon-client/src/hotbar.rs @@ -119,3 +119,23 @@ pub fn load(path: &Path, known: &dyn Fn(&str) -> bool) -> Vec { _ => (0..GROUPS).map(|_| empty()).collect(), } } + +/// `HotbarManager.save`: the nine rows with the current data version, each +/// stack as `ItemStack.OPTIONAL_CODEC` writes it (an empty one is `{}`). +pub fn save(path: &Path, rows: &[Hotbar]) -> crate::Result<()> { + let mut entries = vec![( + JavaString::from("DataVersion"), + Tag::Int(horizon_world::DATA_VERSION), + )]; + for (i, row) in rows.iter().enumerate() { + let stacks = row.iter().map(|s| match s { + Some(s) => save::item_to_nbt(s), + None => Tag::compound(Vec::<(&str, Tag)>::new()), + }); + entries.push(( + JavaString::from(i.to_string().as_str()), + Tag::List(stacks.collect()), + )); + } + save::write_dat(path, Tag::compound(entries)) +} From 008c4f91cdd86513118c2001844550c29653674a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:21:37 +0100 Subject: [PATCH 134/221] Treat single player as a local server for the tab list and F3 charts --- crates/horizon-client/src/game/debug_keys.rs | 5 +++-- crates/horizon-client/src/game/scoreboard.rs | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 16e7fc6e7..ff44c76dd 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -244,7 +244,8 @@ impl Game<'_> { if on { "visible" } else { "hidden" } ) }; - let remote = self.remote.is_some(); + // `DebugScreenOverlay`: the single-player variants for a local server. + let remote = !self.has_singleplayer_server(); let c = &self.debug_charts; [ format!( @@ -463,7 +464,7 @@ impl Game<'_> { height, self.settings.max_fps, 1000.0 / self.clock.rate(), - self.remote.is_some(), + !self.has_singleplayer_server(), ); draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale( scale, scale, diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 72b3ab000..fd0b6ec98 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -677,7 +677,7 @@ impl Game<'_> { let objective = board.display_objective(sb::SLOT_LIST); let shown = tab_list::visible( key, - self.remote.is_none(), + self.has_singleplayer_server(), players.len(), objective.is_some(), ); From 6b1d376e6f1fa7d75aabb7e0014e5c56caf2d708 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:22:11 +0100 Subject: [PATCH 135/221] Show the sleeping players count on the action bar of a LAN host or server --- crates/horizon-client/src/game.rs | 6 ++ crates/horizon-client/src/game/lan_actions.rs | 64 +++++++++++++++++-- crates/horizon-client/src/lan/hub.rs | 7 ++ 3 files changed, 71 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..675b73f17 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1481,6 +1481,8 @@ struct Game<'a> { /// The head of the bed while sleeping; the visual timer also survives waking. sleeping: Option<[i32; 3]>, sleep_timer: u32, + /// `SleepStatus`'s active and sleeping players at the last announcement. + sleep_seen: (i64, i64), dim: Dim, world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. @@ -4943,6 +4945,7 @@ impl Game<'_> { self.tick_friends(); horizon_client::spans::time("tick_hand", || self.tick_hand()); horizon_client::spans::time("tick_sleep", || self.tick_sleep()); + self.announce_sleep_status(); horizon_client::spans::time("tick_portal", || self.tick_nether_portal())?; if running { horizon_client::spans::time("tick_end", || self.tick_end())?; @@ -10370,6 +10373,8 @@ impl Game<'_> { self.wake_up(); } self.wake_guests(); + // SleepStatus.removeAllSleepers: waking everyone is not announced. + self.sleep_seen.1 = 0; } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { @@ -12970,6 +12975,7 @@ impl<'a> Game<'a> { lightning_seen: [0; 2], sleeping: None, sleep_timer: 0, + sleep_seen: (0, 0), dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..561e46533 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2096,11 +2096,10 @@ impl Game<'_> { } } - /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the - /// host's player and the guests: of the players not in spectator mode, - /// players_sleeping_percentage of them (at least one) are in bed, and as - /// many have slept 100 ticks. - pub(super) fn enough_slept(&self) -> bool { + /// `SleepStatus.update`'s counts over the host's player and the guests: + /// the players not in spectator mode, how many are in bed, and how many + /// of those have slept 100 ticks. + fn sleep_counts(&self) -> (i64, i64, i64) { let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64); let mut count = |in_bed: bool, timer: u32| { active += 1; @@ -2124,11 +2123,64 @@ impl Game<'_> { count(g.bed.is_some(), g.sleep_timer); } } + (active, sleeping, deep) + } + + /// `SleepStatus.sleepersNeeded`. + fn sleepers_needed(&self, active: i64) -> i64 { let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0)); - let needed = ((active * percent + 99) / 100).max(1); + ((active * percent + 99) / 100).max(1) + } + + /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the + /// host's player and the guests: of the players not in spectator mode, + /// players_sleeping_percentage of them (at least one) are in bed, and as + /// many have slept 100 ticks. + pub(super) fn enough_slept(&self) -> bool { + let (active, sleeping, deep) = self.sleep_counts(); + let needed = self.sleepers_needed(active); sleeping >= needed && deep >= needed } + /// `ServerLevel.updateSleepingPlayerList` and `announceSleepStatus`: when + /// the players or the sleepers change, a published or dedicated world + /// shows everyone "n/m players sleeping", or "Sleeping through this + /// night" once enough are in bed, on the action bar. + pub(super) fn announce_sleep_status(&mut self) { + let (active, sleeping, _) = self.sleep_counts(); + let (old_active, old_sleeping) = self.sleep_seen; + self.sleep_seen = (active, sleeping); + let changed = (old_sleeping > 0 || sleeping > 0) + && (old_active != active || old_sleeping != sleeping); + let published = self.lan.is_some() || self.options.dedicated.is_some(); + if !changed || !published { + return; + } + // ServerLevel.canSleepThroughNights. + if self.ui.rules.int("players_sleeping_percentage") > 100 { + return; + } + let needed = self.sleepers_needed(active); + let text = if sleeping >= needed { + horizon_client::text::Text::translate("sleep.skipping_night", &[]) + } else { + horizon_client::text::Text::translate( + "sleep.players_sleeping", + &[ + horizon_client::text::Text::literal(sleeping.to_string()), + horizon_client::text::Text::literal(needed.to_string()), + ], + ) + }; + if let Some(host) = self.lan.as_ref() { + host.hub + .overlay_message(horizon_client::lan::data::component_nbt(&text.component())); + } + if self.options.dedicated.is_none() { + self.titles.set_overlay(text, false); + } + } + /// `ServerLevel.wakeUpAllPlayers` for the guests. pub(super) fn wake_guests(&mut self) { if let Some(host) = self.lan.as_mut() { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index f9b6e8ce7..e19d4fa83 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -470,6 +470,13 @@ impl Hub { overlay: false, })); } + /// `ServerPlayer.sendOverlayMessage` to every guest (the action bar). + pub fn overlay_message(&self, content: Tag) { + self.broadcast(&C::SystemChat(play::SystemChat { + content, + overlay: true, + })); + } /// A chat message from the host (a disguised chat: the host has no /// connection to sign with). pub fn chat(&self, sender: &str, text: &str) { From 4afb5748f2312a5f274cb5523893ab79693d5ca9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:22:13 +0100 Subject: [PATCH 136/221] Let a player's axe hit disable the victim's shield --- crates/horizon-client/src/game/combat.rs | 4 ++++ crates/horizon-client/src/game/lan_pvp.rs | 13 ++++++++++++ crates/horizon-client/src/game/shield.rs | 24 ++++++++++++++++++++++- 3 files changed, 40 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 2d6b75902..f0395dda1 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -33,6 +33,10 @@ pub(super) struct CombatTracker { /// The projectile hitting the player now is another player's that /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). pub(super) refuse_player_hit: bool, + /// The player whose melee hit is landing on the player now: where they + /// stand and the seconds their weapon disables a shield for + /// (`getSecondsToDisableBlocking`). + pub(super) player_attacker: Option<([f64; 3], f32)>, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 65520221a..8e15bb1f3 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -40,6 +40,8 @@ pub(super) struct Strike { /// `Player.attack`'s `magicBoost > 0`: the enchantments added damage. magic: bool, from: [f64; 3], + /// `getSecondsToDisableBlocking` of the attacker's weapon. + disable_blocking: f32, sweep: Option<[f64; 3]>, /// `causeExtraKnockback`: its strength and direction (the attacker's /// yaw), and whether the hit is a sprinting knockback attack. @@ -122,6 +124,14 @@ impl Game<'_> { p.cause_food_exhaustion(0.1); } self.swing_arm(); + // LivingEntity.getSecondsToDisableBlocking: the held weapon's value, + // none while another item is in use. + let disable_blocking = if self.using.is_some() { + 0.0 + } else { + self.attack_item_info() + .map_or(0.0, |i| i.disable_blocking_seconds) + }; Some(Strike { attacker: self.lan_acting, amount, @@ -129,6 +139,7 @@ impl Game<'_> { crit, magic, from, + disable_blocking, sweep, knockback: (strength, xd, zd), knockback_attack, @@ -243,7 +254,9 @@ impl Game<'_> { // Player.attack: the hurt (with its knockback away from the // attacker), then causeExtraKnockback along the attacker's yaw. let land = |g: &mut Self| { + g.combat.player_attacker = Some((s.from, s.disable_blocking)); let hurt = g.mob_hits_player(s.amount, s.from, "minecraft:player_attack"); + g.combat.player_attacker = None; let (strength, xd, zd) = s.knockback; if hurt && strength > 0.0 { g.knock_back_player(f64::from(strength), xd, zd); diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index c4f7f98d1..e75dd56de 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -176,7 +176,14 @@ impl Game<'_> { if projectile { return; } - let Some(id) = attacker else { return }; + let Some(id) = attacker else { + // Another player's melee hit has no mob behind it. + if let Some((from, disable)) = self.combat.player_attacker { + let fully = outcome.blocked >= damage; + self.blocked_by_attacker(&component, [from[0], from[2]], fully, disable, at); + } + return; + }; let fully = outcome.blocked >= damage; let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; @@ -214,6 +221,21 @@ impl Game<'_> { let _ = self.handle_mob_events(events); return; } + self.blocked_by_attacker(&component, [mx, mz], fully, disable, at); + } + + /// What a blocked melee hit does to the defender once the shield took + /// it: `LivingEntity.blockedByItem` knocks them back unless fully + /// blocked, then `Player.blockUsingItem` disables the shield. + fn blocked_by_attacker( + &mut self, + component: &horizon_client::items::BlocksAttacks, + attacker: [f64; 2], + fully: bool, + disable: f32, + at: Option<[f64; 3]>, + ) { + let [mx, mz] = attacker; // LivingEntity.blockedByItem: defender.knockback(0.5, defender - attacker), // which moves the defender along -(xd, zd). if !fully && let Some(p) = self.player.as_mut() { From 0cd3410a2db5a69d146b3a18631a73f99d9d21cb Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:23:01 +0100 Subject: [PATCH 137/221] Squeeze hotbar slots that gain items and draw the bundle fullness bar --- crates/horizon-client/src/bundle.rs | 11 +++++++++++ crates/horizon-client/src/game.rs | 18 +++++++++++++++--- crates/horizon-client/src/game/remote.rs | 18 ++++++++++++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/bundle.rs b/crates/horizon-client/src/bundle.rs index 948e2f4a9..49d29d5f9 100644 --- a/crates/horizon-client/src/bundle.rs +++ b/crates/horizon-client/src/bundle.rs @@ -211,6 +211,17 @@ impl Contents { self.weight.n >= self.weight.d } + /// `BundleItem.isBarVisible`, `getBarWidth` and `getBarColor`: the fullness bar + /// (width, RGB), blue until the bundle is full, then red. + pub fn bar(&self) -> Option<(i32, u32)> { + if self.weight.n <= 0 { + return None; + } + let width = (1 + self.weight.n * 12 / self.weight.d).min(13) as i32; + let color = if self.is_full() { 0xFF5454 } else { 0x7087FF }; + Some((width, color)) + } + /// `toImmutable`, written back into the bundle's component. pub fn store(self, bundle: &mut ItemStack) { let data = bundle.data_mut(); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..d30cba2bf 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1431,6 +1431,9 @@ struct Game<'a> { armor: [Option; 4], /// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here). offhand: Option, + /// `ItemStack.popTime` of the nine hotbar stacks, then the off hand: set to 5 + /// when a slot gains items, counted down each tick. + hotbar_pop: [u8; 10], /// The hand an item use acts with (`InteractionHand`): the off hand only /// for its turn in `use_item` and while its item is being used. hand: Hand, @@ -5308,7 +5311,10 @@ impl Game<'_> { let decorations = hud_overlays::ItemDecorations { count: stack.count, count_text, - bar: hud_overlays::damage_bar(stack.damage as i32, max_damage), + // BundleItem overrides the bar with its fullness. + bar: horizon_client::bundle::Contents::of(self.res.items(), stack) + .map(|c| c.bar()) + .unwrap_or_else(|| hud_overlays::damage_bar(stack.damage as i32, max_damage)), cooldown: self.cooldowns.percent(&cooldown, partial), }; let mut draws = vec![hud_layout::GuiDraw::Push(vec![ @@ -5405,12 +5411,17 @@ impl Game<'_> { hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { + let partial = self.clock.fraction() as f32; let inputs = hud_layout::HotbarInputs { selected: self.selected as i32, right_handed: !self.settings.main_hand_left, offhand: self.offhand.is_some(), - slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)), - offhand_pop: 0.0, + slots: std::array::from_fn(|i| { + self.inventory[i] + .as_ref() + .map(|_| (f32::from(self.hotbar_pop[i]) - partial).max(0.0)) + }), + offhand_pop: (f32::from(self.hotbar_pop[9]) - partial).max(0.0), attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); @@ -12941,6 +12952,7 @@ impl<'a> Game<'a> { title: None, armor: [None, None, None, None], offhand: None, + hotbar_pop: [0; 10], hand: Hand::Main, shield_cooldown: 0, cooldowns: Default::default(), diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..20832879f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2358,6 +2358,20 @@ impl Game<'_> { r.state_id = p.state; } let stack = self.to_stack(&p.item); + // ClientPacketListener.handleContainerSetSlot: a hotbar slot that + // gains items squeezes for 5 ticks. + if p.container == 0 + && (36..=45).contains(&p.slot) + && let Some(new) = &stack + { + let (pop, old) = match p.slot { + 45 => (9, self.offhand.as_ref()), + s => (s as usize - 36, self.inventory[s as usize - 36].as_ref()), + }; + if old.is_none_or(|old| old.count < new.count) { + self.hotbar_pop[pop] = 5; + } + } self.set_menu_slot(p.container, i32::from(p.slot), stack); self.remote_synced(); } @@ -3177,6 +3191,10 @@ impl Game<'_> { // server says the entry ended. `onCooldownEnded` is the plain // ItemCooldowns' no-op on a client. self.cooldowns.tick(); + // Inventory.tick's ItemStack.inventoryTick: the pop time runs down. + for pop in &mut self.hotbar_pop { + *pop = pop.saturating_sub(1); + } // Leaving a slot clears its bundle's selection here and on the server. self.tick_bundle_hover(); // Options.broadcastOptions: a changed render distance or Chat option From 1f98f3ca89d04dc6046ed5c2c4717c96496593ca Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:23:22 +0100 Subject: [PATCH 138/221] Open the Leave Bed chat screen while the player sleeps --- crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/chat.rs | 77 +++++++++++++++++++++++- crates/horizon-client/src/game/titles.rs | 1 + 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..db9a96d01 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10333,7 +10333,9 @@ impl Game<'_> { fn tick_sleep(&mut self) { self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); if let Some(head) = self.sleeping { - if self.keys.contains(&KeyCode::ShiftLeft) + // Vanilla has no Shift wake-up: the chat screen's capitals must + // not get the sleeper up. + if (self.screen != Screen::Chat && self.keys.contains(&KeyCode::ShiftLeft)) || self .player .as_ref() diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..9a87f2d74 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -81,6 +81,8 @@ pub struct UiState { pub chat_screen: Option, /// When the chat screen opened (its input took the focus: the cursor blink). pub chat_opened: Option, + /// The chat screen is `InBedChatScreen`: the sleeper's, with a Leave Bed button. + pub in_bed_chat: bool, pub registries: Registries, pub rules: GameRules, pub clock: WorldClock, @@ -440,6 +442,12 @@ impl Game<'_> { self.capture(false); } pub(super) fn close_chat(&mut self) { + // InBedChatScreen.onClose: leaving the screen means getting up; the + // screen goes once the player has woken (`tick_in_bed_chat`). + if self.ui.in_bed_chat && self.sleeping.is_some() { + self.wake_up(); + return; + } self.ui.chat_screen = None; self.ui.chat.reset_scroll(); if self.screen == Screen::Chat { @@ -447,6 +455,35 @@ impl Game<'_> { self.capture(true); } } + /// `Gui.tick`: a sleeper gets `InBedChatScreen`; when the player has + /// woken (`onPlayerWokeUp`) it closes, or turns into the plain chat + /// screen if something was typed. + pub(super) fn tick_in_bed_chat(&mut self) { + if self.screen != Screen::Chat { + self.ui.in_bed_chat = false; + } + if self.ui.in_bed_chat { + if self.sleeping.is_none() { + self.ui.in_bed_chat = false; + let text = self + .ui + .chat_screen + .as_ref() + .map_or_else(String::new, |s| s.value().to_owned()); + self.close_chat(); + if !text.is_empty() { + self.open_chat(&text); + } + } + } else if self.sleeping.is_some() && self.screen == Screen::Playing { + self.open_chat(""); + self.ui.in_bed_chat = self.screen == Screen::Chat; + } + } + /// The Leave Bed button of `InBedChatScreen`: its bounds. + fn leave_bed_button(width: f32, height: f32) -> (i32, i32, i32, i32) { + (width as i32 / 2 - 100, height as i32 - 40, 200, 20) + } /// `Minecraft.computeChatAbilities` from the Chat option. pub(super) fn chat_abilities(&self) -> ChatAbilities { ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility)) @@ -559,7 +596,15 @@ impl Game<'_> { match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) { ChatAction::Close => self.close_chat(), ChatAction::Submit(message) => { - self.close_chat(); + // InBedChatScreen sends without closing (`closeOnSubmit` is + // false): the box empties and the screen stays. + if self.ui.in_bed_chat && self.sleeping.is_some() { + screen.suggest_command(&m, &c, ""); + self.ui.chat.reset_scroll(); + self.ui.chat_screen = Some(screen); + } else { + self.close_chat(); + } if !message.is_empty() { self.handle_chat_input(&message); } @@ -675,6 +720,16 @@ impl Game<'_> { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; + if self.ui.in_bed_chat && self.sleeping.is_some() { + let width = self.renderer.as_ref().map_or(1280.0, |r| { + HudBatch::new([r.config.width, r.config.height]).width + }); + let (x, y, w, h) = Self::leave_bed_button(width, height); + if horizon_client::screen_draw::inside((cursor.0 as i32, cursor.1 as i32), x, y, w, h) { + self.wake_up(); + return; + } + } if let Some(screen) = self.ui.chat_screen.as_mut() { if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) { return; @@ -737,6 +792,26 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); + if self.ui.in_bed_chat && self.sleeping.is_some() { + let (x, y, w, h) = Self::leave_bed_button(batch.width, batch.height); + let label = Text::literal(horizon_client::lang::get_or( + "multiplayer.stopSleeping", + "Leave Bed", + )); + let mut button = Vec::new(); + horizon_client::screen_draw::button( + &mut button, + &m, + &label, + x, + y, + w, + h, + true, + horizon_client::screen_draw::inside(mouse, x, y, w, h), + ); + horizon_client::screen_draw::paint(batch, &self.gui.atlas, &button); + } // The hovered message part's tooltip, one row per line of its text. if let Some(hover) = self.ui.chat.hover_at( &self.gui.atlas.font, diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 9bb000314..daf2e9f5d 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -60,6 +60,7 @@ impl Game<'_> { /// The title, action bar and selected-item parts of `Hud.tick`. pub(super) fn tick_hud(&mut self) { self.titles.tick(); + self.tick_in_bed_chat(); // `MinecraftServer.isCurrentlySaving` of single player's server. let saving = self .integrated From 5bbb61aec20c2de22f61d9bcebf6136f7a9ba8b5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:23:23 +0100 Subject: [PATCH 139/221] Angry endermen open their mouth on a server thread --- crates/horizon-client/src/game/lan.rs | 6 +++++- crates/horizon-client/src/game/remote_mob_data.rs | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..d4e497628 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -397,7 +397,7 @@ fn mob_meta( } defaults.push((17, serializer::BYTE, Value::Byte(0))); } - // Enderman.DATA_CARRY_STATE. + // Enderman.DATA_CARRY_STATE and DATA_CREEPY (angry: the open mouth). "minecraft:enderman" => { if let Some(state) = e.carried { meta.push(( @@ -406,6 +406,10 @@ fn mob_meta( Value::Id(state.0 as i32), )); } + if e.flag { + meta.push((17, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((17, serializer::BOOLEAN, Value::Bool(false))); } _ => {} } diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 65bbbfbbe..56302eb8d 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -94,6 +94,9 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => { m.extra.size = (*size).clamp(1, 127); } + // Enderman.DATA_CREEPY (after DATA_CARRY_STATE): the open mouth + // and raised head of an angry enderman. + (Species::Enderman, 17, Value::Bool(creepy)) => m.extra.flag = *creepy, // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, From b6c77e12f3a0df7e61039030d0af48397d643163 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:23:43 +0100 Subject: [PATCH 140/221] Hide invisible guests in the host window --- crates/horizon-client/src/game/lan.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..c81e8eb1a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1498,6 +1498,14 @@ impl Game<'_> { .filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient)) .collect(); m.extra.effect_ambient = visible().all(|e| e.ambient); + // Entity.isInvisible: the invisibility effect hides the body (the + // model pass, the name tag rules and `trader::is_invisible` read it). + m.extra.effects.retain(|e| e.0 != "minecraft:invisibility"); + if let Some(e) = g.effects.get("invisibility") { + m.extra + .effects + .push(("minecraft:invisibility", e.duration, e.amplifier)); + } // Lying in its bed (LivingEntity.getBedOrientation). m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. From 71b2f110ebd8f3e6453821ef202966f2b895af4c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:23:59 +0100 Subject: [PATCH 141/221] Show the account name on the book signing screen --- crates/horizon-client/src/game/books.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 2f38dffd9..5c158536d 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -1077,7 +1077,12 @@ impl Game<'_> { BLACK, ); } - let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME); + // BookSignScreen: `owner.getName()`, the account's name on a server. + let owner = self + .remote + .as_ref() + .map_or(super::chat::PLAYER_NAME, |r| r.profile_name.as_str()); + let by = tr("book.byAuthor", "by %1$s").replace("%1$s", owner); let tw = HudBatch::text_width(atlas, &by); batch.text( atlas, From 6d69bba15ee6630c2bb88e48b0c34deb9e317508 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:24:05 +0100 Subject: [PATCH 142/221] Remote mining test fixture: the held-item key and the attack strength reset --- tests/test_remote_mining.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_remote_mining.py b/tests/test_remote_mining.py index 9feb255fa..b940eefb5 100644 --- a/tests/test_remote_mining.py +++ b/tests/test_remote_mining.py @@ -26,7 +26,7 @@ class RemoteMiningTests(unittest.TestCase): struct Hit { pos: [i32; 3], face: u8 } struct Mining { pos: [i32; 3], progress: f32, ticks: u32 } #[derive(Default)] -struct Remote { destroy_delay: u32, destroying: Option<([i32; 3], u8, f32)> } +struct Remote { destroy_delay: u32, destroying: Option<([i32; 3], u8, f32)>, destroying_item: String } struct Ground { on_ground: bool } struct Player { ground: Ground } #[derive(Clone)] @@ -70,6 +70,8 @@ struct Game { hit: Hit, sequence: i32, packets: Vec, } impl Game { + fn main_hand_key(&self) -> String { String::new() } + fn reset_attack_strength(&mut self) {} fn new(hardness: f32, speed: f32, creative: bool) -> Self { Self { remote: Some(Remote::default()), mining: None, creative, From 18217532af91668d2be99db0fecac32a0d9bddd5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:24:15 +0100 Subject: [PATCH 143/221] Show other players gliding, swimming, spinning and holding a loaded crossbow --- crates/horizon-client/src/game/creatures.rs | 12 ++++++++ crates/horizon-client/src/game/lan.rs | 30 +++++++++++++++++++ crates/horizon-client/src/game/perspective.rs | 29 +++++++++++++----- crates/horizon-client/src/game/remote.rs | 18 +++++++++++ .../src/game/remote_mob_data.rs | 18 +++++++++++ crates/horizon-client/src/lan/hub.rs | 2 +- crates/horizon-client/src/mobs.rs | 21 +++++++++++++ 7 files changed, 122 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..d377564e7 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3471,6 +3471,18 @@ impl Game<'_> { &armor, out, ); + if &*mob.kind.id == "minecraft:player" { + // PlayerRenderer's WingsLayer and SpinAttackEffectLayer. + self.player_elytra_geometry( + mob, + mob.extra.chest.as_deref(), + camera, + alpha as f32, + packed, + out, + ); + self.spin_attack_geometry(mob, camera, alpha as f32, packed, out); + } self.mob_block_geometry(mob, camera, alpha, packed, out); // Glowing outlines and a guardian's beam remain visible independently // of whether the body is hidden behind terrain. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..dd5268a92 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1492,6 +1492,27 @@ impl Game<'_> { .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; m.extra.sprinting = g.sprinting; + // Entity.DATA_POSE and the shared and living flags the others + // get (hub::guest_body): gliding, swimming, Riptide's spin. + let body = lan::hub::guest_body(g); + m.extra.fall_flying = body.gliding; + m.extra.synced_pose = if body.swimming || body.crawling { 3 } else { 0 }; + m.extra.auto_spin_attack = body.spin_attack; + m.velocity = g + .motion + .as_ref() + .map_or(Vec3::new(dx, dy, dz), |motion| motion.velocity); + m.tick_avatar_pose( + g.motion + .as_ref() + .is_some_and(|motion| motion.fluids.was_touching_water), + ); + // CrossbowItem.isCharged: the held crossbow's projectiles. + m.extra.charged = g + .inventory + .get(g.selected) + .and_then(|s| s.as_ref()) + .is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty())); // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. let visible = || g.effects.list.iter().filter(|e| e.visible); m.extra.effect_particles = visible() @@ -1558,6 +1579,15 @@ impl Game<'_> { ), out, ); + self.player_elytra_geometry( + m, + m.extra.chest.as_deref(), + camera, + alpha as f32, + packed, + out, + ); + self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); if !m.glowing { self.cull_entity_vertices(out, entity_start); diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index caf49883b..5b65486d6 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -453,7 +453,14 @@ impl Game<'_> { &self.player_armor_layers(), out, ); - self.player_elytra_geometry(m, camera, alpha as f32, packed, out); + self.player_elytra_geometry( + m, + self.armor[1].as_ref().map(|s| &*s.item), + camera, + alpha as f32, + packed, + out, + ); self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } @@ -509,7 +516,14 @@ impl Game<'_> { &self.player_armor_layers(), &mut verts, ); - self.player_elytra_geometry(&m, camera, 1.0, 240 | 240 << 8, &mut verts); + self.player_elytra_geometry( + &m, + self.armor[1].as_ref().map(|s| &*s.item), + camera, + 1.0, + 240 | 240 << 8, + &mut verts, + ); self.held_item_geometry(&m, camera, 1.0, 240 | 240 << 8, false, &mut verts); let height = if m.extra.crouching { 1.5 } else { 1.8 }; // PictureInPictureRenderer: the box centre, (size, size, -size); @@ -548,17 +562,18 @@ impl Game<'_> { } impl Game<'_> { - fn player_elytra_geometry( + /// `WingsLayer` for a player wearing `chest`. + pub(super) fn player_elytra_geometry( &self, m: &Mob, + chest: Option<&str>, camera: glam::DVec3, partial: f32, light: u32, out: &mut Vec, ) { - let Some(asset) = self.armor[1] - .as_ref() - .and_then(|s| self.res.items().get(&s.item)) + let Some(asset) = chest + .and_then(|item| self.res.items().get(item)) .and_then(|i| i.equip_asset.as_ref()) else { return; @@ -598,7 +613,7 @@ impl Game<'_> { } /// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning /// player (`SpinAttackEffectModel.setupAnim`). - fn spin_attack_geometry( + pub(super) fn spin_attack_geometry( &self, m: &Mob, camera: glam::DVec3, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..3559dbb71 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2029,7 +2029,23 @@ impl Game<'_> { .iter() .map(|(slot, stack)| (*slot, stack.as_ref().map(|s| self.item_name(s.item)))) .collect(); + // CrossbowItem.isCharged: the main hand's `charged_projectiles` + // (AvatarRenderer.getArmPose holds a loaded crossbow up). + let charged = p.slots.iter().find(|(slot, _)| *slot == 0).map(|(_, s)| { + s.as_ref().is_some_and(|s| { + matches!( + s.component(horizon_protocol::item::component::CHARGED_PROJECTILES), + Some(horizon_protocol::item::Component::Stacks(list)) + if !list.is_empty() + ) + }) + }); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + if let Some(charged) = charged + && &*m.kind.id == "minecraft:player" + { + m.extra.charged = charged; + } for (slot, item) in items { let e = &mut m.extra; match slot { @@ -3632,6 +3648,8 @@ impl Game<'_> { // a player's body following its walk and look. if player { remote_player_head_turn(m); + // LivingEntity.tick: the glide count, wings and swim amount. + m.tick_avatar_pose(m.fluids.in_water); } else if m.alive() { m.body_rotation_tick(); } diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 65bbbfbbe..932ecaa32 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -15,6 +15,9 @@ use horizon_protocol::registry::Builtin; fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_entity: i32) { let species = m.species(); let baby = super::lan::baby_index(&m.kind.id); + if &*m.kind.id == "minecraft:player" { + player_poses(m, values); + } for (index, _, value) in values { match (*index, value) { // Entity.DATA_SHARED_FLAGS_ID's FLAG_ONFIRE: Entity.isOnFire on a @@ -115,6 +118,21 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti } } +/// What another player's pose draws from: gliding (Entity.isFallFlying, flag +/// 0x80 of the shared flags), the pose (swimming), Riptide's spin +/// (LivingEntity.isAutoSpinAttack, flag 4) and a loaded crossbow in the +/// hand (the held stack comes with SetEquipment). +fn player_poses(m: &mut Mob, values: &[(u8, i32, Value)]) { + for (index, _, value) in values { + match (*index, value) { + (0, Value::Byte(flags)) => m.extra.fall_flying = flags & -128 != 0, + (6, Value::Id(pose)) => m.extra.synced_pose = (*pose).clamp(0, 17) as u8, + (8, Value::Byte(flags)) => m.extra.auto_spin_attack = flags & 4 != 0, + _ => {} + } + } +} + /// The options of a synched particle list: an entity effect carries its ARGB /// colour, the omens none. fn swirls(list: &[Particle], builtin: &Builtin) -> Vec { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index f9b6e8ce7..e16d8f36c 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2714,7 +2714,7 @@ fn ticking_state(rate: f32, frozen: bool) -> C { } /// What the others see of a guest's body, from its server-side state. -fn guest_body(g: &Guest) -> BodyFlags { +pub fn guest_body(g: &Guest) -> BodyFlags { let m = g.motion.as_deref(); BodyFlags { gliding: g.fall_flying, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..00f256343 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -705,6 +705,8 @@ pub struct Extra { pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, + /// `Entity.DATA_POSE` of another player, as the server sent it. + pub synced_pose: u8, /// `LivingEntity.isAutoSpinAttack` (Riptide). pub auto_spin_attack: bool, pub main_hand_left: bool, @@ -2321,6 +2323,25 @@ impl SwimAnimation { } } +impl Mob { + /// The part of `LivingEntity.tick` and `aiStep` that animates another + /// player from its synched pose and flags: the glide count, the wings + /// (`elytraAnimationState`) and the swim amount (`updateSwimAmount`). + pub fn tick_avatar_pose(&mut self, in_water: bool) { + let e = &mut self.extra; + e.fall_fly_ticks = if e.fall_flying { + e.fall_fly_ticks + 1 + } else { + 0 + }; + // LivingEntity.isVisuallySwimming: the swimming pose, or the gliding + // pose after the glide ended. + let visually = e.synced_pose == 3 || (!e.fall_flying && e.synced_pose == 1); + e.elytra.tick(e.fall_flying, e.crouching, self.velocity); + e.swim.tick(visually, in_water); + } +} + #[cfg(test)] mod elytra_tests { use super::*; From 1131a2910ddc732a65011d789875cf6d25497090 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:24:43 +0100 Subject: [PATCH 144/221] Apply Haste and Mining Fatigue to the attack speed --- crates/horizon-client/src/game.rs | 3 +-- crates/horizon-client/src/game/dragon.rs | 11 ++++------- crates/horizon-client/src/game/hand.rs | 15 ++++++++++++--- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..30c8e5b41 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7863,8 +7863,7 @@ impl Game<'_> { } /// `Player.getAttackStrengthScale(0.5)`. fn attack_strength_scale(&self) -> f32 { - let speed = self.attack_item_info().map_or(0.0, |i| i.attack_speed); - let delay = 20.0 / (4.0 + speed).max(0.1); + let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed()); ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0) } /// `Player.isSweepAttack`: a charged, grounded sword hit below the movement limit. diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8f3fdb224..5d8208f5a 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -1031,14 +1031,11 @@ impl Game<'_> { if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { return false; } - let modifiers = self - .attack_item_info() - .map(|i| (i.attack_damage, i.attack_speed)) - .unwrap_or((0.0, 0.0)); - let speed = (4.0 + modifiers.1).max(0.1); - let scale = ((self.attack_ticks as f32 + 0.5) / (20.0 / speed)).clamp(0.0, 1.0); + let hand_damage = self.attack_item_info().map_or(0.0, |i| i.attack_damage); + let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed()); + let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0); let mut amount = - (1.0 + modifiers.0 + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8); + (1.0 + hand_damage + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8); let falling = self .player .as_ref() diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index d91d3b979..210e62ac5 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -289,12 +289,21 @@ impl Game<'_> { // Only alive mobs are hit, so a picked living entity is alive. Some(true) } - /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier. + /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier and the + /// Haste and Mining Fatigue modifiers (`ADD_MULTIPLIED_TOTAL`), clamped to + /// the attribute's range. pub(super) fn main_hand_attack_speed(&self) -> f64 { - horizon_client::attack_strength::BASE_ATTACK_SPEED + let value = horizon_client::attack_strength::BASE_ATTACK_SPEED + self .attack_item_info() - .map_or(0.0, |i| f64::from(i.attack_speed)) + .map_or(0.0, |i| f64::from(i.attack_speed)); + self.potions + .effects + .modifiers() + .into_iter() + .filter(|m| m.0 == "minecraft:attack_speed") + .fold(value, |v, m| v * (1.0 + m.2)) + .clamp(0.0, 1024.0) } /// The item whose attack damage and speed modifiers the player has (`attack_item`). pub(super) fn attack_item_info(&self) -> Option<&horizon_client::items::ItemInfo> { From ffad9e1f0acbde0e338cc8f89c8dda5a1790d588 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:25:21 +0100 Subject: [PATCH 145/221] Keep the styling of the death message on the death screen --- crates/horizon-client/src/game/remote.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..57e5c7c59 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -191,7 +191,7 @@ pub(super) struct Remote { input: horizon_client::interaction_input::InteractionInput, stop_mining: bool, placing: Option<([i32; 3], u64)>, - death_message: Option, + death_message: Option, player_type: Option>, /// Inventory as last synchronised, for creative-mode slot updates. synced: Vec>, @@ -2233,7 +2233,7 @@ impl Game<'_> { // The component resolves in the client's current language, as // the chat line does, not in the language the session joined // with (`Remote.lang` is the vanilla server-language table). - let message = remote_text(&p.message).plain(); + let message = remote_text(&p.message); let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id); if let Some(r) = self.remote.as_mut() { r.death_message = Some(message); @@ -5225,8 +5225,16 @@ impl Game<'_> { if self.screen == Screen::Dead && let Some(message) = &r.death_message { - let tw = HudBatch::text_width(atlas, message); - batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true); + // DeathScreen draws the styled cause component. + let tw = atlas.font.width_text(message); + batch.text_styled( + atlas, + message, + ((w - tw) / 2.0).floor(), + 85.0, + u32::MAX, + true, + ); } } /// Status for `horizon-ctl status`. From 7b84a7ae91fe62175c76024ef497eb7a1d83932a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:25:43 +0100 Subject: [PATCH 146/221] Let a sweep attack hurt and push back the other players next to the target --- crates/horizon-client/src/game.rs | 35 +++-- crates/horizon-client/src/game/creatures.rs | 3 + crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_pvp.rs | 137 +++++++++++++++++++- 4 files changed, 163 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..5df9291fe 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7899,18 +7899,9 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.sweep", from, 1.0, 1.0); } - /// The damage and knockback part of `Player.doSweepAttack` after a sweep - /// hit on the mob at `target`: every other living mob in its box grown by - /// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative - /// too), but the player's allies - /// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the - /// weapon's enchantments, scaled by the attack strength, and is pushed 0.4 - /// along the player's yaw. - pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) { - let Some(p) = self.player.as_ref() else { - return; - }; - let from = [p.position.x, p.position.y, p.position.z]; + /// What `Player.doSweepAttack` deals before the target's enchantment + /// bonus and the attack strength: `1 + sweeping_damage_ratio * baseDamage`. + pub(super) fn sweep_base_damage(&self, scale: f32) -> f32 { // `baseDamage` of `Player.attack` before a critical hit (a sweep has // none) and the enchantments: the attack damage attribute with the // strength and weakness effects, scaled by the attack strength. @@ -7926,7 +7917,21 @@ impl Game<'_> { "minecraft:sweeping_damage_ratio", ) .clamp(0.0, 1.0) as f32; - let sweep_damage = 1.0 + ratio * base_damage; + 1.0 + ratio * base_damage + } + /// The damage and knockback part of `Player.doSweepAttack` after a sweep + /// hit on the mob at `target`: every other living mob in its box grown by + /// (1, 0.25, 1) and closer than 3 blocks (`distanceToSqr < 9`, in creative + /// too), but the player's allies + /// (`isAlliedTo`), takes `1 + sweeping_damage_ratio * baseDamage` with the + /// weapon's enchantments, scaled by the attack strength, and is pushed 0.4 + /// along the player's yaw. + pub(super) fn sweep_damage(&mut self, target: usize, scale: f32) { + let Some(p) = self.player.as_ref() else { + return; + }; + let from = [p.position.x, p.position.y, p.position.z]; + let sweep_damage = self.sweep_base_damage(scale); let hit_box = self.mobs[target] .bounds() .inflate(horizon_core::geometry::Vec3::new(1.0, 0.25, 1.0)); @@ -7961,6 +7966,10 @@ impl Game<'_> { .insert(self.mobs[i].id, self.lan_acting); } } + // `getEntitiesOfClass(LivingEntity.class)` takes the other players too. + let mut sweep = self.player_sweep(sweep_damage, scale); + sweep.hit_box = hit_box; + self.sweep_other_players(sweep); } /// `Player.attack`'s sounds when a vehicle takes the hit (it always does, /// and can't be hit critically): knockback when sprinting at full diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..51437944f 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -46,6 +46,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, + /// Sweep attacks from a guest's turn, waiting for it to end + /// (game/lan_pvp.rs). + pub sweeps: Vec, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..cba61960e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1166,6 +1166,8 @@ impl Game<'_> { self.lan = Some(host); // A mace's wind burst from a guest's attack. let _ = self.flush_wind_bursts(); + // A sweep attack's reach to the other players from a guest's attack. + self.flush_sweeps(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 65520221a..614d23d79 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -12,6 +12,7 @@ use horizon_client::{ mobs::Who, projectiles::{Hit, Projectile, ProjectileKind}, }; +use horizon_core::geometry::{Aabb, Vec3}; /// The player projectiles that meet other players: arrows (their hurt), and /// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0 @@ -24,7 +25,7 @@ pub(super) fn meets_players(kind: &ProjectileKind) -> bool { } /// Who a player's attack lands on. -#[derive(Clone, Copy)] +#[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Victim { Host, Guest(u32), @@ -47,6 +48,26 @@ pub(super) struct Strike { knockback_attack: bool, /// The attacker's team, for the victim's `Player.canHarmPlayer`. team: Option, + /// The sweep's damage to the players around the victim. + sweep_hit: Option, +} + +/// A sweep attack's reach to the other players (`Player.doSweepAttack`), +/// worked out as the attacker. +#[derive(Clone)] +pub(super) struct Sweep { + /// The attacking guest (none: the host). + attacker: Option, + from: [f64; 3], + /// The damage after the enchantments and the attack strength. + damage: f32, + /// The push along the attacker's yaw. + knockback: (f64, f64), + team: Option, + /// The target's box grown by (1, 0.25, 1). + pub(super) hit_box: Aabb, + /// The player the sweep started from, which it spares. + skip: Option, } impl Strike { @@ -113,6 +134,10 @@ impl Game<'_> { let from = [p.position.x, p.position.y, p.position.z]; let (amount, scale, crit, magic) = self.melee_damage("minecraft:player"); let sweep = self.sweep_attack_position(scale, crit); + let sweep_hit = sweep.map(|_| { + let base = self.sweep_base_damage(scale); + self.player_sweep(base, scale) + }); let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); self.attack_ticks = 0; @@ -133,6 +158,7 @@ impl Game<'_> { knockback: (strength, xd, zd), knockback_attack, team: self.player_team().cloned(), + sweep_hit, }) } @@ -300,9 +326,118 @@ impl Game<'_> { }; if let Some(at) = s.sweep.filter(|_| hurt) { self.sweep_attack(at, Some(s.from)); + // The other players next to the victim (Player.doSweepAttack). + let bounds = match victim { + Victim::Host => self.player.as_ref().map(|p| p.bounds()), + Victim::Guest(conn) => host.hub.guest(conn).map(guest_bounds), + }; + if let (Some(sweep), Some(bounds)) = (&s.sweep_hit, bounds) { + self.sweep_players( + host, + &Sweep { + hit_box: bounds.inflate(Vec3::new(1.0, 0.25, 1.0)), + skip: Some(victim), + ..sweep.clone() + }, + ); + } } else { self.audio.play(sound, Some(s.from), 1.0, 1.0); } hurt } + + /// The sweep of the player in place, for the players it reaches: the + /// damage (`1 + ratio * baseDamage`, plus the enchantments against a + /// player, scaled by the attack strength) and who hits. The box is set + /// by the caller. + pub(super) fn player_sweep(&mut self, base: f32, scale: f32) -> Sweep { + let from = self + .player + .as_ref() + .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]); + let damage = (base + self.enchant_damage_bonus("minecraft:player")) * scale; + Sweep { + attacker: self.lan_acting, + from, + damage, + knockback: self.extra_knockback_direction(), + team: self.player_team().cloned(), + hit_box: Aabb::new(Vec3::ZERO, Vec3::ZERO), + skip: None, + } + } + + /// A sweep from a mob hit reaches the other players. Inside a guest's + /// turn the host holds the other players (`as_guest`), so it waits for + /// the turn to end. + pub(super) fn sweep_other_players(&mut self, sweep: Sweep) { + if self.lan_acting.is_some() { + self.creatures.sweeps.push(sweep); + } else if let Some(mut host) = self.lan.take() { + self.sweep_players(&mut host, &sweep); + self.lan = Some(host); + } + } + + /// The sweeps guests' turns put off. + pub(super) fn flush_sweeps(&mut self) { + for sweep in std::mem::take(&mut self.creatures.sweeps) { + self.sweep_other_players(sweep); + } + } + + /// `Player.doSweepAttack` on the players: each other player in the box, + /// closer than 3 blocks (`distanceToSqr < 9`) and not an ally + /// (`isAlliedTo`), is hurt (`ServerPlayer.canHarmPlayer`: the `pvp` rule) + /// and pushed 0.4 along the attacker's yaw. + pub(super) fn sweep_players(&mut self, host: &mut LanHost, sweep: &Sweep) { + let from = Vec3::new(sweep.from[0], sweep.from[1], sweep.from[2]); + let mut victims = Vec::new(); + if sweep.attacker.is_some() + && self.options.dedicated.is_none() + && !self.spectator() + && let Some(p) = self.player.as_ref() + && !p.health.dead_or_dying() + && p.bounds().intersects(sweep.hit_box) + && p.position.distance_squared(from) < 9.0 + { + victims.push((Victim::Host, self.player_team().cloned())); + } + for g in &host.hub.guests { + if host.hub.here(g) + && g.loaded + && !g.dead + && !g.spectator() + && sweep.attacker != Some(g.conn) + && guest_bounds(g).intersects(sweep.hit_box) + && Vec3::new(g.position[0], g.position[1], g.position[2]).distance_squared(from) + < 9.0 + { + let team = self.score.board.players_team(&g.name).cloned(); + victims.push((Victim::Guest(g.conn), team)); + } + } + let (xd, zd) = sweep.knockback; + let land = |g: &mut Self| { + let hurt = g.mob_hits_player(sweep.damage, sweep.from, "minecraft:player_attack"); + if hurt { + g.knock_back_player(0.4, xd, zd); + } + }; + for (victim, team) in victims { + if sweep.skip == Some(victim) + || horizon_client::scoreboard::teams_allied(team.as_ref(), sweep.team.as_ref()) + || !self.ui.rules.bool("pvp") + { + continue; + } + match victim { + Victim::Host => land(self), + Victim::Guest(conn) => { + self.guest_struck_by(host, conn, land); + } + } + } + } } From f2db04bd64b049a936700261be9f139c84ef730b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:26:07 +0100 Subject: [PATCH 147/221] Translate the sleep messages and send the respawn point message only when it changes --- crates/horizon-client/src/game.rs | 87 ++++++++++++++++++++++--------- 1 file changed, 63 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..72dda4d6a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10214,11 +10214,29 @@ impl Game<'_> { rain.extend(snow_vertices); rain } + /// A translated message for the player the game acts for: `overlay` is + /// `sendOverlayMessage` (the action bar), else `sendSystemMessage` (chat). + /// A guest gets a packet, so its own client translates it. + fn tell_sleeper(&mut self, key: &str, fallback: &str, overlay: bool) { + if self.lan_acting.is_some() { + self.guest_packets + .push(horizon_protocol::packets::play::Clientbound::SystemChat( + horizon_protocol::packets::play::SystemChat { + content: horizon_protocol::text::translatable(key, &[]), + overlay, + }, + )); + } else if overlay { + self.message = Some((self.translate(key, fallback), Instant::now())); + } else { + self.system_message(horizon_client::text::Text::translate(key, &[])); + } + } /// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder, /// and (outside creative) no monsters within 8 blocks; the bed becomes the /// respawn point either way. fn try_sleep(&mut self, pos: [i32; 3]) { - let Some(p) = self.player.as_ref() else { + let Some((position, yaw)) = self.player.as_ref().map(|p| (p.position, p.yaw)) else { return; }; let time = self.world.day_time.rem_euclid(24000); @@ -10241,15 +10259,16 @@ impl Game<'_> { // ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks // sideways and 2 vertically of the head or the foot. let reachable = |bed: [i32; 3]| { - (p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 - && (p.position.y - f64::from(bed[1])).abs() <= 2.0 - && (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 + (position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0 + && (position.y - f64::from(bed[1])).abs() <= 2.0 + && (position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0 }; if !reachable(head) && !reachable(foot) { - self.message = Some(( - "You may not rest now; the bed is too far away".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.too_far_away", + "You may not rest now; the bed is too far away", + true, + ); return; } // ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the @@ -10262,7 +10281,11 @@ impl Game<'_> { f.full_collision && f.solid_render }); if blocked { - self.message = Some(("This bed is obstructed".into(), Instant::now())); + self.tell_sleeper( + "block.minecraft.bed.obstructed", + "This bed is obstructed", + true, + ); return; } // In reach (bedInRange), day or night: setRespawnPosition( @@ -10271,9 +10294,16 @@ impl Game<'_> { // and finds where to stand up (findRespawnAndUseSpawnBlock). // Straw beds never set it (`straw_bed_rule`). if self.bed_sets_spawn(state) { - self.respawn_config = Some(respawn_anchor::RespawnConfig::wrapped( - self.dim, head, p.yaw, false, - )); + let config = respawn_anchor::RespawnConfig::wrapped(self.dim, head, yaw, false); + // ServerPlayer.setRespawnPosition: the chat message only when the + // point moved (`isSamePosition`). + let moved = self + .respawn_config + .is_none_or(|c| (c.dim, c.pos) != (config.dim, config.pos)); + self.respawn_config = Some(config); + if moved { + self.tell_sleeper("block.minecraft.set_spawn", "Respawn point set", false); + } // The fallback becomes the world spawn: a guest's is none of its // own, so it follows `setworldspawn`. self.spawn = if self.lan_acting.is_some() { @@ -10288,10 +10318,11 @@ impl Game<'_> { }; } if !night { - self.message = Some(( - "You can sleep only at night or during thunderstorms".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.no_sleep", + "You can sleep only at night or during thunderstorms", + true, + ); return; } // Creative players skip the monster check (`!this.isCreative()`). @@ -10299,18 +10330,26 @@ impl Game<'_> { && self.mobs.iter().any(|m| { m.hostile() && m.alive() - && (m.position.x - p.position.x).abs() < 8.0 - && (m.position.y - p.position.y).abs() < 5.0 - && (m.position.z - p.position.z).abs() < 8.0 + && (m.position.x - position.x).abs() < 8.0 + && (m.position.y - position.y).abs() < 5.0 + && (m.position.z - position.z).abs() < 8.0 }); if monsters { - self.message = Some(( - "You may not rest now; there are monsters nearby".into(), - Instant::now(), - )); + self.tell_sleeper( + "block.minecraft.bed.not_safe", + "You may not rest now; there are monsters nearby", + true, + ); return; } - self.message = Some(("Respawn point set".into(), Instant::now())); + // ServerPlayer.startSleepInBed: a percentage above 100 cannot skip the night. + if self.ui.rules.int("players_sleeping_percentage") > 100 { + self.tell_sleeper( + "sleep.not_possible", + "No amount of rest can pass this night", + true, + ); + } self.stop_mining(); self.left = false; self.right = false; From 180e2f612a374fc47002465614b7770e806a25be Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:26:12 +0100 Subject: [PATCH 148/221] Chat lines: server message bar and tooltip, item hover, run_command clicks, Shift insertion --- crates/horizon-client-core/src/component.rs | 24 ++++-- crates/horizon-client-core/src/text.rs | 25 +++++- crates/horizon-client/src/chat.rs | 37 +++++--- crates/horizon-client/src/game/chat.rs | 95 ++++++++++++++------- crates/horizon-client/src/game/remote.rs | 6 +- crates/horizon-client/src/item_data.rs | 5 ++ 6 files changed, 140 insertions(+), 52 deletions(-) diff --git a/crates/horizon-client-core/src/component.rs b/crates/horizon-client-core/src/component.rs index 5b828b305..21416e1c9 100644 --- a/crates/horizon-client-core/src/component.rs +++ b/crates/horizon-client-core/src/component.rs @@ -174,19 +174,31 @@ fn object_style(o: &serde_json::Map) -> Style { let text = |k: &str| e.get(k).and_then(Value::as_str).map(str::to_owned); style.click = match e.get("action").and_then(Value::as_str) { Some("suggest_command") => text("command").map(crate::text::ClickEvent::SuggestCommand), + Some("run_command") => text("command").map(crate::text::ClickEvent::RunCommand), Some("copy_to_clipboard") => { text("value").map(crate::text::ClickEvent::CopyToClipboard) } _ => None, }; } - // HoverEvent.ShowText. - if let Some(e) = o.get("hover_event").and_then(Value::as_object) - && e.get("action").and_then(Value::as_str) == Some("show_text") - && let Some(value) = e.get("value") - { - style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + // HoverEvent.ShowText and ShowItem. + if let Some(e) = o.get("hover_event").and_then(Value::as_object) { + match e.get("action").and_then(Value::as_str) { + Some("show_text") => { + if let Some(value) = e.get("value") { + style.hover = Some(Box::new(to_text(value, &mut |s| Text::literal(s)))); + } + } + Some("show_item") if e.get("id").is_some_and(Value::is_string) => { + style.hover_item = Some(Box::new(Value::Object(e.clone()))); + } + _ => {} + } } + style.insertion = o + .get("insertion") + .and_then(Value::as_str) + .map(str::to_owned); style } /// `ComponentSerialization.CODEC` decoding into text. `selector` components diff --git a/crates/horizon-client-core/src/text.rs b/crates/horizon-client-core/src/text.rs index 0a2b6eadb..1f71ae4a9 100644 --- a/crates/horizon-client-core/src/text.rs +++ b/crates/horizon-client-core/src/text.rs @@ -43,6 +43,8 @@ pub fn named_color(name: &str) -> Option { #[derive(Clone, Debug, PartialEq, Eq)] pub enum ClickEvent { SuggestCommand(String), + /// `ClickEvent.RunCommand`: the command, with or without its `/`. + RunCommand(String), CopyToClipboard(String), /// A local file to open with the system handler. /// Only allow this in locally constructed messages, never server/LAN text. @@ -61,6 +63,10 @@ pub struct Style { pub click: Option, /// Hover text. pub hover: Option>, + /// `HoverEvent.ShowItem`: the event's `{id, count?, components?}` object. + pub hover_item: Option>, + /// `Style.insertion`: the text a Shift-click puts in the chat box. + pub insertion: Option, /// The font (`FontDescription.Resource`), a full id like /// `minecraft:alt`; the default font when unset. pub font: Option, @@ -90,6 +96,12 @@ impl Style { if self.hover.is_none() { self.hover.clone_from(&base.hover); } + if self.hover_item.is_none() { + self.hover_item.clone_from(&base.hover_item); + } + if self.insertion.is_none() { + self.insertion.clone_from(&base.insertion); + } if self.font.is_none() { self.font.clone_from(&base.font); } @@ -495,7 +507,7 @@ impl Text { } /// The style fields of a component's JSON. -const STYLE_KEYS: [&str; 9] = [ +const STYLE_KEYS: [&str; 10] = [ "color", "bold", "italic", @@ -504,6 +516,7 @@ const STYLE_KEYS: [&str; 9] = [ "obfuscated", "click_event", "hover_event", + "insertion", "font", ]; /// Style.Serializer: the fields a style sets. @@ -535,6 +548,9 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { ClickEvent::CopyToClipboard(value) => { json!({ "action": "copy_to_clipboard", "value": value }) } + ClickEvent::RunCommand(command) => { + json!({ "action": "run_command", "command": command }) + } ClickEvent::OpenFile(path) => json!({ "action": "open_file", "path": path }), }; out.push(("click_event".to_owned(), event)); @@ -544,6 +560,13 @@ fn style_json(style: &Style) -> Vec<(String, Value)> { "hover_event".to_owned(), json!({ "action": "show_text", "value": hover.component() }), )); + } else if let Some(Value::Object(item)) = style.hover_item.as_deref() { + let mut event = item.clone(); + event.insert("action".into(), "show_item".into()); + out.push(("hover_event".to_owned(), Value::Object(event))); + } + if let Some(insertion) = &style.insertion { + out.push(("insertion".to_owned(), insertion.clone().into())); } if let Some(font) = &style.font { out.push(("font".to_owned(), font.clone().into())); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 04b9d486c..060bbf303 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -458,26 +458,34 @@ impl Chat { pub fn hover_at(&self, font: &crate::font::Font, height: i32, x: f64, y: f64) -> Option { self.style_at(font, height, x, y)?.hover.map(|h| *h) } - /// ChatComponent.getClickedComponentStyleAt. - fn style_at( - &self, - font: &crate::font::Font, - height: i32, - x: f64, - y: f64, - ) -> Option { + /// The wrapped line under a GUI-space cursor while chat is focused, and + /// the cursor's x within it (the text starts at 0). + fn line_at(&self, height: i32, x: f64, y: f64) -> Option<(&Line, f64)> { let scale = self.options.scale as f32; - let mut x = x / f64::from(scale) - 4.0; + let x = x / f64::from(scale) - 4.0; let bottom = hud_layout::floor((height - 40) as f32 / scale); let from_bottom = f64::from(bottom) - y / f64::from(scale); - if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 { + if x >= f64::from(self.max_width()) || from_bottom <= 0.0 { return None; } let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1; if row >= self.lines_per_page(true) { return None; } - let line = self.lines.get(self.scroll + row)?; + Some((self.lines.get(self.scroll + row)?, x)) + } + /// ChatComponent.getClickedComponentStyleAt. + pub fn style_at( + &self, + font: &crate::font::Font, + height: i32, + x: f64, + y: f64, + ) -> Option { + let (line, mut x) = self.line_at(height, x, y)?; + if x < 0.0 { + return None; + } let content = line.content.resolve_legacy(); for (c, style) in content.chars() { x -= f64::from(font.advance(c, style)); @@ -487,6 +495,13 @@ impl Chat { } None } + /// Whether the cursor is on a line's indicator bar while chat is focused + /// (`DrawingFocusedGraphicsAccess.handleTag`), whose tooltip is the + /// message tag's text. + pub fn indicator_at(&self, height: i32, x: f64, y: f64) -> bool { + self.line_at(height, x, y) + .is_some_and(|(line, x)| line.indicator.is_some() && (-4.0..-2.0).contains(&x)) + } /// Plain text of the newest messages (for tests and the control socket). pub fn recent_lines(&self, n: usize) -> Vec { self.messages diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..ffc09357a 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -682,12 +682,25 @@ impl Game<'_> { } else { return; } - match self.ui.chat.click_at( + let Some(style) = self.ui.chat.style_at( &self.gui.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, - ) { + ) else { + return; + }; + // ChatScreen.handleComponentClicked: with Shift held only an + // insertion acts, else only the click event. + if self.has_shift_down() { + if let Some(insertion) = style.insertion + && let Some(screen) = self.ui.chat_screen.as_mut() + { + screen.type_text(&m, &c, &insertion); + } + return; + } + match style.click { Some(ClickEvent::CopyToClipboard(value)) => { use horizon_client::clipboard::Clipboard; self.clipboard.set(&value); @@ -700,9 +713,26 @@ impl Game<'_> { screen.suggest_command(&m, &c, &command); } } + Some(ClickEvent::RunCommand(command)) => self.click_command(&command), None => {} } } + /// `Screen.clickCommandAction`: run a clicked command as the player + /// without adding it to the chat history. A client mod's command goes + /// first, as `ClientPacketListener.sendUnattendedCommand` lets client + /// commands take it. (Vanilla asks first when the command fails to + /// parse; here the server answers it.) + fn click_command(&mut self, command: &str) { + let command = command.strip_prefix('/').unwrap_or(command); + if self.mod_command(command) { + return; + } + if self.remote.is_some() { + self.send_chat(&format!("/{command}")); + } else if !self.local_server_mod_command(command) { + self.run_command(command); + } + } /// Chat lines over the HUD (focused while the chat screen is open). pub(super) fn draw_chat(&mut self, batch: &mut HudBatch) { let focused = self.screen == Screen::Chat; @@ -737,17 +767,39 @@ impl Game<'_> { let draws = screen.draw(&m, mouse, blink, background); horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); - // The hovered message part's tooltip, one row per line of its text. - if let Some(hover) = self.ui.chat.hover_at( - &self.gui.atlas.font, - batch.height as i32, - f64::from(self.cursor.0), - f64::from(self.cursor.1), - ) { - let lines = hover_rows(&hover); + // The hovered message part's tooltip (`renderComponentHoverEffect`), + // or the text of the message tag under the cursor. + let height = batch.height as i32; + let (cx, cy) = (f64::from(self.cursor.0), f64::from(self.cursor.1)); + let wrap = (batch.width as i32 / 2).max(200); + if let Some(style) = self.ui.chat.style_at(&self.gui.atlas.font, height, cx, cy) { + if let Some(hover) = style.hover { + let lines = self.wrapped_rows(&hover, wrap); + self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); + } else if let Some(stack) = style + .hover_item + .as_deref() + .and_then(horizon_client::item_data::stack_from_hover) + .filter(|s| self.res.items().get(&s.item).is_some()) + { + self.draw_stack_tooltip(batch, &stack, self.cursor.0, self.cursor.1); + } + } else if self.ui.chat.indicator_at(height, cx, cy) { + // GuiMessageTag.systemSinglePlayer's text, split at 210. + let tag = Text::translate("chat.tag.system_single_player", &[]); + let lines = self.wrapped_rows(&tag, 210); self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1); } } + /// `Font.split`: a tooltip text wrapped at `width`, one white row per line. + fn wrapped_rows(&self, text: &Text, width: i32) -> Vec<(Text, u32)> { + let split = self + .gui + .atlas + .font + .split(&text.resolve_legacy(), width as f32); + split.into_iter().map(|row| (row, u32::MAX)).collect() + } /// Advance the overworld clock (ServerClockManager.tick) when /// `advance_time` allows it. pub(super) fn advance_clock(&mut self) { @@ -1022,26 +1074,3 @@ fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client:: fn owner_permission(allow_commands: bool) -> u8 { if allow_commands { 4 } else { 0 } } - -/// A hover text's rows for the tooltip: split at line breaks, each in the -/// colour of its first styled character (white without one). -fn hover_rows(hover: &horizon_client::text::Text) -> Vec<(String, u32)> { - let mut rows = vec![(String::new(), None)]; - for (c, style) in hover.resolve_legacy().chars() { - if c == '\n' { - rows.push((String::new(), None)); - continue; - } - let row = rows.last_mut().expect("one row"); - if row.0.is_empty() { - row.1 = style.color; - } - row.0.push(c); - } - rows.into_iter() - .map(|(text, color)| { - let [_, r, g, b] = color.unwrap_or(0xFF_FFFF).to_be_bytes(); - (text, horizon_client::hud::rgba(r, g, b, 255)) - }) - .collect() -} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..707159e44 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -666,10 +666,14 @@ impl Game<'_> { } let text = content.plain(); log::info!("[chat] {text}"); + // addServerSystemMessage and addClientSystemMessage both carry + // GuiMessageTag.systemSinglePlayer: the grey bar at the line's left. + let indicator = (source != horizon_client::chat::ChatSource::Player) + .then_some(horizon_client::chat::SYSTEM_INDICATOR); self.ui.chat.add( &self.gui.atlas, content, - None, + indicator, source, self.ticks, self.screen == Screen::Chat, diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 253bc6cc5..f706ed812 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -396,6 +396,11 @@ fn template_from(tag: &Tag) -> Option { } } } +/// The stack a `show_item` hover event holds (`HoverEvent.ShowItem`): its +/// `{id, count?, components?}` object. +pub fn stack_from_hover(event: &serde_json::Value) -> Option { + template_from(&crate::scoreboard::json_to_tag(event)) +} /// Sorted-key, type-annotated text of a tag (the differential harnesses /// print the same form from the vanilla side). pub fn canon_tag(tag: &Tag) -> String { From ca83704cbb6d4634b5fe8053668eb0a51b76e71b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:26:12 +0100 Subject: [PATCH 149/221] Add zombie village sieges --- crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/raids.rs | 146 ++++++++++++++++++++ 2 files changed, 147 insertions(+) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..e669fc703 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -480,6 +480,7 @@ impl Game<'_> { if self.ui.rules.bool("spawn_mobs") { self.tick_wandering_trader(); self.tick_patrol_spawner(); + self.tick_village_siege(); } self.tick_raids(); self.tick_creature_entities() diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index da7c79394..e5e3f2790 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -23,6 +23,7 @@ use std::collections::{HashMap, HashSet}; #[derive(Default)] pub(super) struct Raiding { patrol: PatrolSpawner, + siege: Siege, /// The raids of the dimension the player is in, and that dimension. raids: Raids, loaded: Option, @@ -38,6 +39,17 @@ pub(super) struct Raiding { homes: HashMap>)>, } +/// `VillageSiege`: whether tonight is a siege, whether the spot is chosen, +/// and the zombies still to spawn there. +#[derive(Default)] +struct Siege { + tonight: bool, + set_up: bool, + zombies_to_spawn: i32, + next_spawn_time: i32, + spot: [i32; 3], +} + impl Raiding { /// Exchange the level-held parts (`ServerLevel.getRaids`) with another /// level's (game/levels.rs). @@ -1187,6 +1199,140 @@ impl Game<'_> { self.spawn_event_mob("minecraft:pillager", at, m.leader, raider::Reason::Patrol); } } + /// `VillageSiege.tick`: at midnight one night in ten, 20 zombies spawn + /// two ticks apart near a village 32 blocks from a player standing in it. + pub(super) fn tick_village_siege(&mut self) { + if self.dim != Dim::Overworld { + return; + } + let enemies = self.ui.rules.bool("spawn_mobs") && self.ui.rules.bool("spawn_monsters"); + if self.sky_darken() < 4 || !enemies { + self.raiding.siege.tonight = false; + self.raiding.siege.set_up = false; + return; + } + // ClockTimeMarkers.ROLL_VILLAGE_SIEGE: tick 18000 of the 24000 tick day. + if self.world.day_time.rem_euclid(24000) == 18000 { + self.raiding.siege.tonight = self.world.random.next_int_bound(10).unwrap_or(1) == 0; + } + if !self.raiding.siege.tonight { + return; + } + if !self.raiding.siege.set_up { + if !self.try_to_setup_siege() { + return; + } + self.raiding.siege.set_up = true; + } + if self.raiding.siege.next_spawn_time > 0 { + self.raiding.siege.next_spawn_time -= 1; + return; + } + self.raiding.siege.next_spawn_time = 2; + if self.raiding.siege.zombies_to_spawn > 0 { + self.try_spawn_siege_zombie(); + self.raiding.siege.zombies_to_spawn -= 1; + } else { + self.raiding.siege.tonight = false; + } + } + /// `ServerLevel.isVillage`: within one section of a village. + fn is_village(centers: &HashSet<(i32, i32, i32)>, pos: [i32; 3]) -> bool { + sections_to_village(centers, section(pos)) <= 1 + } + /// `VillageSiege.tryToSetupSiege`: the first player standing in a village + /// picks a spot 32 blocks away (ten tries); true when one stood in a + /// village, even if no spot was found. + fn try_to_setup_siege(&mut self) -> bool { + let centers = self.village_centers(); + for player in self.level_players() { + if player.spectator { + continue; + } + let center = block_of(player.position); + if !Self::is_village(¢ers, center) + || self.natural_level().biome_tag( + "minecraft:without_zombie_sieges", + center[0], + center[1], + center[2], + ) + { + continue; + } + for _ in 0..10 { + let angle = self.world.random.next_float() * std::f32::consts::TAU; + let spot = [ + center[0] + (angle.cos() * 32.0).floor() as i32, + center[1], + center[2] + (angle.sin() * 32.0).floor() as i32, + ]; + if self.find_siege_spawn_pos(¢ers, spot).is_some() { + self.raiding.siege.spot = spot; + self.raiding.siege.next_spawn_time = 0; + self.raiding.siege.zombies_to_spawn = 20; + break; + } + } + return true; + } + false + } + /// `VillageSiege.trySpawn`: one zombie, in a random yaw. + fn try_spawn_siege_zombie(&mut self) { + let centers = self.village_centers(); + let spot = self.raiding.siege.spot; + let Some(at) = self.find_siege_spawn_pos(¢ers, spot) else { + return; + }; + let Some(id) = self.spawn_event_mob("minecraft:zombie", at, false, raider::Reason::Event) + else { + return; + }; + let yaw = self.world.random.next_float() * 360.0; + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + (m.yaw, m.previous_yaw, m.body_yaw, m.previous_body_yaw) = (yaw, yaw, yaw, yaw); + (m.head_yaw, m.previous_head_yaw) = (yaw, yaw); + } + self.spawn_jockeys(id, false); + } + /// `VillageSiege.findRandomSpawnPos`: ten tries within 8 blocks of the + /// spot for a village column where a zombie may spawn. + fn find_siege_spawn_pos( + &mut self, + centers: &HashSet<(i32, i32, i32)>, + spot: [i32; 3], + ) -> Option<[f64; 3]> { + let mut random = std::mem::replace( + &mut self.world.random, + horizon_core::random::LegacyRandom::new(0), + ); + let mut found = None; + for _ in 0..10 { + let x = spot[0] + random.next_int_bound(16).unwrap_or(0) - 8; + let z = spot[2] + random.next_int_bound(16).unwrap_or(0) - 8; + if !self.world.chunks.contains_key(&(x >> 4, z >> 4)) { + continue; + } + let y = self.surface_height(x, z); + if Self::is_village(centers, [x, y, z]) + && spawn_rules::check_spawn_rules( + Species::Zombie, + &self.natural_level(), + spawn_rules::Reason::Event, + &mut random, + x, + y, + z, + ) + { + found = Some([f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + break; + } + } + self.world.random = random; + found + } /// A raider's ominous banner (drop chance 2.0: always dropped) and a /// patrol captain's ominous bottle (`entities/pillager`). /// `OminousBottleAmplifier.onConsume`: Bad Omen for 100 minutes at the From 2a1132387f318caf43e421ad4ba0094e8c00c661 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:26:53 +0100 Subject: [PATCH 150/221] Swing the right arm and for the right time on other players --- crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 3 +- crates/horizon-client/src/game/remote.rs | 9 ++- crates/horizon-client/src/mobs/ai.rs | 60 +++++++++++++++++-- 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..87ab2bfa4 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1492,6 +1492,8 @@ impl Game<'_> { .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; m.extra.sprinting = g.sprinting; + // ClientInformation.mainHand (HumanoidArm: 0 left, 1 right). + m.extra.main_hand_left = g.info.main_hand == 0; // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. let visible = || g.effects.list.iter().filter(|e| e.visible); m.extra.effect_particles = visible() diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..badc9f82d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2872,7 +2872,8 @@ impl Game<'_> { let packet = swing_packet(id, c.hand, c.animation); host.hub.broadcast_near(at, 128.0, &packet, Some(conn)); if let Some(m) = host.models.get_mut(&conn) { - m.swing(); + // The duration already counts the guest's haste or fatigue. + m.swing_hand(c.hand == Hand::Off, c.duration_ticks); } } play.swing.tick(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..96810acdf 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1946,6 +1946,13 @@ impl Game<'_> { m.extra.ints[1] = code; } } + // Avatar.DATA_PLAYER_MAIN_HAND (HumanoidArm: 0 left, 1 + // right): the arm a swing of the main hand moves. + if let (15, Value::Id(arm)) = (index, value) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + m.extra.main_hand_left = *arm == 0; + } } } // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this @@ -2187,7 +2194,7 @@ impl Game<'_> { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { self.swing_hand(hand, animation); } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - m.swing(); + m.swing_hand_modified(hand == Hand::Off, animation.duration); } } // The player's own instances: its maximum health (the hearts the diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 26b94eeac..978d4bd36 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -53,17 +53,62 @@ pub struct Ai { /// Swing animation progress (attackAnim) and ticks. pub swing_time: i32, pub swinging: bool, + /// The current swing's `SwingDescription.durationTicks`; 0 is the default 6. + pub swing_duration: i32, /// Walked distance and the next footstep. pub steps: super::living::Steps, } impl Mob { + /// `LivingEntity.getCurrentSwingDuration`: 6 ticks unless a swing set its own. + pub fn swing_duration(&self) -> i32 { + if self.ai.swing_duration > 0 { + self.ai.swing_duration + } else { + 6 + } + } + /// `SwingState.startIfAble`: a swing past the first half of the current + /// one restarts it. + fn start_swing(&mut self, duration: i32) -> bool { + let half = self.swing_duration() / 2; + if self.ai.swinging && self.ai.swing_time >= 0 && self.ai.swing_time < half { + return false; + } + self.ai.swing_time = -1; + self.ai.swinging = true; + self.ai.swing_duration = duration.max(1); + true + } /// LivingEntity.swing pub fn swing(&mut self) { - if !self.ai.swinging || self.ai.swing_time >= 3 || self.ai.swing_time < 0 { - self.ai.swing_time = -1; - self.ai.swinging = true; + if self.start_swing(6) { + self.extra.swing_right_arm = None; } } + /// `LivingEntity.swing(hand, animation, false)` for a swing of `duration` + /// ticks (`getModifiedSwingDuration`): the arm is `hand.asArm(mainArm)`. + pub fn swing_hand(&mut self, off_hand: bool, duration: i32) { + if self.start_swing(duration) { + self.extra.swing_right_arm = Some(!off_hand != self.main_arm_left()); + } + } + /// `swing_hand` for a swing of `base` ticks, lengthened or shortened by + /// this mob's haste, conduit power or mining fatigue + /// (`LivingEntity.getModifiedSwingDuration`). + pub fn swing_hand_modified(&mut self, off_hand: bool, base: i32) { + let amplifier = |id: &str| self.extra.effects.iter().find(|e| e.0 == id).map(|e| e.2); + let dig_speed = amplifier("minecraft:haste").max(amplifier("minecraft:conduit_power")); + let fatigue = amplifier("minecraft:mining_fatigue"); + let duration = crate::first_person::swing_duration( + crate::first_person::SwingAnimation { + kind: 1, + duration: base, + }, + dig_speed, + fatigue, + ); + self.swing_hand(off_hand, duration); + } } /// The module implementing a species' behaviour. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -435,18 +480,21 @@ pub fn tick( } true } -/// LivingEntity.updateSwingTime (6-tick swing duration). +/// LivingEntity.updateSwingTime. pub fn tick_swing(m: &mut Mob) { + let duration = m.swing_duration(); if m.ai.swinging { m.ai.swing_time += 1; - if m.ai.swing_time >= 6 { + if m.ai.swing_time >= duration { m.ai.swing_time = 0; m.ai.swinging = false; + m.ai.swing_duration = 0; + m.extra.swing_right_arm = None; } } else { m.ai.swing_time = 0; } - m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; + m.anim.attack_anim = m.ai.swing_time as f32 / duration as f32; } /// `LivingEntity.baseTick` refills a breather's air by 4, then /// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills From c4427d2a14b1dd029ea07c1b2437d7668759ad0e Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:27:34 +0100 Subject: [PATCH 151/221] Size the mount hearts from the server's max health and fix the jump bar --- crates/horizon-client/src/game/mounts.rs | 23 +++++++++------ crates/horizon-client/src/game/remote.rs | 36 ++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa4bbc209..c216a18ff 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -253,10 +253,7 @@ impl Game<'_> { /// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is /// held; on release, the jump's strength (0 when there is none). pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 { - // PlayerRideableJumping: horses, camels and nautili (the dash). - let saddled = self.mobs[i].extra.saddled - && (equine::is_equine(self.mobs[i].species()) - || horizon_client::mobs::nautilus::is_nautilus(self.mobs[i].species())); + let saddled = self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species()); let mut jump = 0.0; if saddled { let st = &mut self.mount; @@ -463,10 +460,15 @@ impl Game<'_> { _ => {} } } - /// `Player.jumpableVehicle`: a saddled mount that jumps. + /// `PlayerRideableJumping`: horses, camels and nautili (the dash). + fn jumps(species: Species) -> bool { + equine::is_equine(species) || horizon_client::mobs::nautilus::is_nautilus(species) + } + /// `Player.jumpableVehicle`: a saddled mount that jumps (not a pig or a + /// strider, which a saddle only steers). pub(super) fn jumpable_mount(&self) -> bool { self.mount_index() - .is_some_and(|i| self.mobs[i].extra.saddled) + .is_some_and(|i| self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species())) } /// `willPrioritizeJumpInfo`: charging a jump or recharging. pub(super) fn mount_jumping(&self) -> bool { @@ -491,8 +493,13 @@ impl Game<'_> { let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); if jump_bar { - // JumpableVehicleBar: the cooldown shows while the jump recharges. - let cooldown = i32::from(self.mount.jump_ticks < 0); + // JumpableVehicleBar: `getJumpCooldown`, which only the camel's and + // the nautilus' dash have; a horse always shows the progress. + let cooldown = i32::from( + self.mount.jump_ticks < 0 + && (matches!(m.species(), Species::Camel | Species::CamelHusk) + || horizon_client::mobs::nautilus::is_nautilus(m.species())), + ); let draws = horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..e95a18303 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1609,6 +1609,41 @@ impl Game<'_> { } } + /// `ClientPacketListener.handleUpdateAttributes` for a mob: its maximum + /// health (the hearts drawn over its mount) takes the server's value, from + /// `AttributeInstance.calculateValue`. + fn remote_mob_attributes(&mut self, id: i32, values: &[play::AttributeSnapshot]) { + let catalog = &self.motion.attributes; + let Some(max_health) = catalog.id("minecraft:max_health") else { + return; + }; + let Some(s) = values + .iter() + .find(|s| s.attribute == max_health.registry_id()) + else { + return; + }; + let amounts = |op: i32| { + s.modifiers + .iter() + .filter(move |m| m.operation == op) + .map(|m| m.amount) + }; + let base = s.base + amounts(0).sum::(); + let mut value = base + amounts(1).map(|a| base * a).sum::(); + for amount in amounts(2) { + value *= 1.0 + amount; + } + let value = catalog.attribute(max_health).definition.sanitize(value); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + horizon_client::mobs::finalize::set_base( + m, + horizon_client::mobs::finalize::Attr::MaxHealth, + value, + ); + } + } + fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { // ClientCommonPacketListenerImpl.handlePing runs on the game @@ -2199,6 +2234,7 @@ impl Game<'_> { } self.apply_remote_health(); } + C::UpdateAttributes(p) => self.remote_mob_attributes(p.id, &p.values), C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) From eeceb9c2de52bee63cd84d2fdebd65df6ed27737 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:27:40 +0100 Subject: [PATCH 152/221] Let a fishing hook catch and pull other players --- crates/horizon-client/src/game/creatures.rs | 4 + crates/horizon-client/src/game/fishing.rs | 103 +++++++++++++++++- crates/horizon-client/src/game/lan.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 4 + 4 files changed, 109 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..281bf4d4e 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -46,6 +46,10 @@ 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, + /// The players a fishing hook can catch, taken as the hooks tick, and + /// the pulls on them waiting for the hub (game/fishing.rs). + pub hook_targets: Vec, + pub hook_pulls: Vec<(u32, horizon_core::geometry::Vec3)>, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 39f9e5ffe..dbf4c37b7 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -1,7 +1,7 @@ //! Fishing: `FishingRodItem.use` (cast / reel in), the `FishingHook` (flight, //! bobbing, lure and bite timers, open water, hooking mobs, retrieving the //! `gameplay/fishing` loot) and `FishingHookRenderer` (bobber and line). -use super::{Game, view_vector}; +use super::{Game, lan::LanHost, lan_mobs::guest_bounds, view_vector}; use horizon_client::lan::{entity::States, hub::Hub}; use horizon_client::{ blocks::Fluid, @@ -45,6 +45,13 @@ pub(super) struct Hook { luck: i32, lure: i32, } +/// A player a hook can catch (`canHitEntity`): their entity id, which +/// guest they are (none: the host) and their box. +pub(super) struct HookTarget { + id: u32, + conn: Option, + bounds: Aabb, +} const SIZE: f64 = 0.25; fn bounds(p: Vec3) -> Aabb { let h = SIZE / 2.0; @@ -166,6 +173,11 @@ impl Game<'_> { } else if let Some(item) = self.dropped.iter_mut().find(|i| i.id == id) { item.velocity = pulled(item.velocity); hooked_item = true; + } else if self.creatures.hook_targets.iter().any(|t| t.id == id) { + // A player: the hub moves them when the tick ends. + self.creatures + .hook_pulls + .push((id, Vec3::new(d.x * 0.1, d.y * 0.1, d.z * 0.1))); } // `hookedIn instanceof ItemEntity ? 3 : 5`. damage = if hooked_item { 3 } else { 5 }; @@ -449,6 +461,15 @@ impl Game<'_> { if !self.holds_rod() || d2 > 1024.0 { return; } + // The players it can catch, as they stand now (the host's own hook; + // guests' hooks use the ones taken as their turns start). + if self.lan_acting.is_none() + && matches!(h.state, State::Flying | State::Hooked(_)) + && let Some(host) = self.lan.take() + { + self.refresh_hook_targets(&host); + self.lan = Some(host); + } h.previous = h.position; if h.on_ground { h.life += 1; @@ -474,8 +495,8 @@ impl Game<'_> { self.hook = Some(h); return; } - // checkCollision: hook the first living mob it touches, or (via - // `canHitEntity`) a dropped item. + // checkCollision: hook the first living mob or other player it + // touches, or (via `canHitEntity`) a dropped item. let bb = bounds(h.position); let (lo, hi) = (bb.min_position(), bb.max_position()); let touches = |b: Aabb| { @@ -487,6 +508,14 @@ impl Game<'_> { .iter() .find(|m| m.alive() && touches(m.bounds())) .map(|m| m.id) + .or_else(|| { + let owner = self.lan_acting; + self.creatures + .hook_targets + .iter() + .find(|t| t.conn != owner && touches(t.bounds)) + .map(|t| t.id) + }) .or_else(|| { self.dropped .iter() @@ -501,12 +530,25 @@ impl Game<'_> { } } State::Hooked(id) => { - // updateHookedEntity: ride the hooked mob or item at 0.8 of its height. + // updateHookedEntity: ride the hooked mob, player or item at 0.8 of its height. let hooked = self .mobs .iter() .find(|m| m.id == id && m.alive()) .map(|m| (m.position, f64::from(m.height()))) + .or_else(|| { + self.creatures + .hook_targets + .iter() + .find(|t| t.id == id) + .map(|t| { + let (lo, hi) = (t.bounds.min_position(), t.bounds.max_position()); + ( + Vec3::new((lo.x + hi.x) / 2.0, lo.y, (lo.z + hi.z) / 2.0), + hi.y - lo.y, + ) + }) + }) .or_else(|| { self.dropped .iter() @@ -575,6 +617,59 @@ impl Game<'_> { ); self.hook = Some(h); } + /// The players a hook can catch: everyone but spectators and the dead + /// (`Projectile.canHitEntity`), the host and the guests in the level. + pub(super) fn refresh_hook_targets(&mut self, host: &LanHost) { + let mut targets = Vec::new(); + if self.options.dedicated.is_none() + && !self.spectator() + && let Some(p) = self.player.as_ref() + && !p.health.dead_or_dying() + { + targets.push(HookTarget { + id: host.host_entity as u32, + conn: None, + bounds: p.bounds(), + }); + } + for g in &host.hub.guests { + if host.hub.here(g) && g.loaded && !g.dead && !g.spectator() { + targets.push(HookTarget { + id: g.entity_id as u32, + conn: Some(g.conn), + bounds: guest_bounds(g), + }); + } + } + self.creatures.hook_targets = targets; + } + /// `FishingHook.pullEntity` on the players the hooks reeled in this tick + /// pulled: their velocity moves, and a guest's reaches their client. + pub(super) fn flush_hook_pulls(&mut self) { + let pulls = std::mem::take(&mut self.creatures.hook_pulls); + let Some(mut host) = self.lan.take() else { + return; + }; + for (id, delta) in pulls { + let push = |g: &mut Self| { + if let Some(p) = g.player.as_mut() { + p.velocity = p.velocity.add_vector(delta); + } + }; + if id == host.host_entity as u32 { + push(self); + } else if let Some(conn) = host + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| g.conn) + { + self.guest_hit_by(&mut host, conn, push); + } + } + self.lan = Some(host); + } /// `FishingRodCast`: the stack in the arm holding the rod /// (`FishingHookRenderer.getHoldingArm`) while the hook is out. pub(super) fn cast_rod(&self) -> Option<&ItemStack> { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..cbe559578 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1166,6 +1166,8 @@ impl Game<'_> { self.lan = Some(host); // A mace's wind burst from a guest's attack. let _ = self.flush_wind_bursts(); + // A reeled-in hook pulling a player. + self.flush_hook_pulls(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..0c6896daf 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1899,6 +1899,10 @@ impl Game<'_> { .filter(|g| host.hub.here(g) && g.loaded) .map(|g| g.conn) .collect(); + // The players the guests' hooks can catch. + if host.play.values().any(|p| p.hook.is_some()) { + self.refresh_hook_targets(host); + } for conn in conns { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; From cc0f8f8a50b4a4fcc6924265d38920700987c89a Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:27:49 +0100 Subject: [PATCH 153/221] Track a vehicle as far as its widest passenger --- crates/horizon-client/src/lan/entity.rs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 920052b5a..19eda20a9 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -742,6 +742,24 @@ impl Entities { chunk, }); } + // TrackedEntity.getEffectiveRange: a vehicle is tracked as far as its + // widest indirect passenger, so a rider never leaves before its mount. + for (&vehicle, passengers) in &riding.passengers { + let Some(own) = self.states.get(&vehicle).filter(|s| s.seen == now) else { + continue; + }; + let (index, mut range) = (own.index, own.range); + let mut pending = passengers.clone(); + while let Some(id) = pending.pop() { + if let Some(s) = self.states.get(&id).filter(|s| s.seen == now) { + range = range.max(s.range); + } + pending.extend_from_slice(riding.passengers(id)); + } + self.probes[index].range = self + .range_percent + .map_or(range * 16, |p| p * (range * 16) / 100); + } self.flags.resize_with(viewers.len(), Vec::new); self.pairs.clear(); self.pairs.resize(entities.len(), false); From f918fc711a2df776d13bc3acf7e6c0fc9cd6faed Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:28:21 +0100 Subject: [PATCH 154/221] Keep the command history between runs and show the restricted chat prompt --- crates/horizon-client/src/chat.rs | 100 ++++++++++++++++++++++++- crates/horizon-client/src/game.rs | 2 +- crates/horizon-client/src/game/chat.rs | 12 +++ 3 files changed, 112 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 04b9d486c..d7def2866 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -16,6 +16,9 @@ use crate::{ #[path = "chat_tests.rs"] mod tests; +/// `CommandHistory.PERSISTED_COMMANDS_FILE_NAME` and its size cap. +const COMMAND_HISTORY_FILE: &str = "command_history.txt"; +const MAX_PERSISTED_COMMAND_HISTORY: usize = 50; /// GuiMessageTag.systemSinglePlayer's indicator colour. pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; @@ -80,6 +83,10 @@ impl ChatAbilities { ChatSource::Client => true, } } + /// `ChatAbilities.hasAnyRestrictions`: the Chat option takes something. + pub fn any_restriction(&self) -> bool { + *self != Self::new(ChatVisibility::Full) + } /// Whether the chat screen may send `input` (`hasAllowedInput`). pub fn allows(&self, input: &str) -> bool { if input.starts_with('/') { @@ -185,6 +192,10 @@ pub struct Chat { lines: Vec, /// Sent messages and commands (ChatComponent.recentChat). pub recent: Vec, + /// `CommandHistory`: the last commands, kept in `command_history.txt` + /// in the game folder once `load_history` has set it. + commands: Vec, + history_file: Option, scroll: usize, new_since_scroll: bool, pub options: ChatOptions, @@ -310,6 +321,17 @@ impl Chat { self.lines.clear(); self.scroll = 0; } + /// `new CommandHistory(gameFolder)`: the commands kept from earlier runs + /// start the chat's history (`ChatComponent`'s constructor). + pub fn load_history(&mut self, game_folder: &std::path::Path) { + let file = game_folder.join(COMMAND_HISTORY_FILE); + if let Ok(text) = std::fs::read_to_string(&file) { + self.commands = text.lines().map(str::to_owned).collect(); + self.recent.extend(self.commands.iter().cloned()); + } + self.history_file = Some(file); + } + /// `ChatComponent.addRecentChat`: a command also goes to the saved history. pub fn add_recent(&mut self, message: &str) { if self.recent.last().map(String::as_str) != Some(message) { if self.recent.len() >= 100 { @@ -317,6 +339,21 @@ impl Chat { } self.recent.push(message.to_owned()); } + if message.starts_with('/') && self.commands.last().map(String::as_str) != Some(message) { + if self.commands.len() >= MAX_PERSISTED_COMMAND_HISTORY { + self.commands.remove(0); + } + self.commands.push(message.to_owned()); + if let Some(file) = &self.history_file { + let mut text = self.commands.join("\n"); + text.push('\n'); + if let Err(e) = std::fs::write(file, text) { + log::error!( + "Failed to write {COMMAND_HISTORY_FILE}, command history will be missing: {e}" + ); + } + } + } } pub fn reset_scroll(&mut self) { self.scroll = 0; @@ -438,10 +475,71 @@ impl Chat { out.push(GuiDraw::Pop); out } - /// Draws [`Chat::layout`] into the HUD batch. + /// Draws [`Chat::layout`] into the HUD batch, and with the chat screen + /// open the restricted prompt above the lines. pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { let draws = self.layout(batch.height as i32, ticks, focused); hud_layout::paint(batch, atlas, &draws); + if focused && self.abilities.any_restriction() { + let prompt = self.restricted_prompt(&atlas.font, batch.height as i32); + hud_layout::paint(batch, atlas, &prompt); + } + } + /// `ChatComponent.extractRenderState` for `FOREGROUND_RESTRICTED`: a + /// background row and the red, underlined "Chat is restricted" line in + /// the row above the messages, clipped to the chat's width. + fn restricted_prompt(&self, font: &crate::font::Font, height: i32) -> Vec { + let o = &self.options; + let scale = o.scale as f32; + let max_width = hud_layout::ceil(o.width_px() as f32 / scale); + let chat_bottom = hud_layout::floor((height - 40) as f32 / scale); + let entry_height = o.line_height(); + let bottom_to_text = + (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32; + let shown = self + .lines + .len() + .saturating_sub(self.scroll) + .min(self.lines_per_page(true)); + let top = chat_bottom - (shown as i32 + 1) * entry_height; + let mut prompt = Text::translate("chat_screen.restricted", &[]).with_style(&Style { + color: Some(text::RED), + underlined: Some(true), + ..Style::default() + }); + // ComponentRenderUtils.clipText. + let mut width = 0.0; + let fits = prompt + .chars() + .take_while(|(c, style)| { + width += font.advance(*c, style); + width <= max_width as f32 + }) + .count(); + if fits < prompt.chars().count() { + prompt = prompt.slice(0, fits); + } + vec![ + GuiDraw::Push(vec![ + PoseOp::Scale(scale, scale), + PoseOp::Translate(4.0, 0.0), + ]), + hud_layout::fill( + -2, + top, + max_width + 4 + 4, + top + entry_height, + hud_layout::as8(o.background_opacity as f32) << 24, + ), + GuiDraw::Text { + text: prompt, + x: 0, + y: top + entry_height - bottom_to_text - 1, + color: hud_layout::white(o.opacity as f32 * 0.9 + 0.1), + shadow: true, + }, + GuiDraw::Pop, + ] } /// The click action under a GUI-space cursor while chat is focused. pub fn click_at( diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..f471f1505 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -13107,7 +13107,7 @@ impl<'a> Game<'a> { admin_feedback: Vec::new(), console_broadcast: None, cmds: Default::default(), - ui: Default::default(), + ui: chat::UiState::new(), combat: Default::default(), guest_combat: Default::default(), mount: Default::default(), diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..95f4cb48a 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -106,6 +106,18 @@ pub struct UiState { pub death_time: u32, } +impl UiState { + /// The state a window starts with: the chat remembers the commands kept + /// in the game folder (`ChatComponent`'s constructor). + pub fn new() -> Self { + let mut ui = Self::default(); + if let Ok(dir) = std::env::current_dir() { + ui.chat.load_history(&dir); + } + ui + } +} + impl Game<'_> { /// `PlayerList.isOp` for the single-player owner: the world's Allow Commands. pub(super) fn allow_commands(&self) -> bool { From 29616ad50247b50e0c98a135b21f1dfb56aca38d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:29:44 +0100 Subject: [PATCH 155/221] Stack toasts in five slots and hide them with F1 --- crates/horizon-client/src/game.rs | 9 +- .../horizon-client/src/game/advancements.rs | 123 +++++++++++++----- .../horizon-client/src/game/server_packs.rs | 27 +++- crates/horizon-client/src/toasts.rs | 3 + 4 files changed, 117 insertions(+), 45 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..c5e5a7183 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5374,12 +5374,12 @@ impl Game<'_> { // The ToastManager draws over every screen: a server's packs // download while the connection screen shows. if self.remote_overlay(&mut batch) { - self.draw_pack_toasts(&mut batch); + self.draw_pack_toasts(&mut batch, false); return batch; } if let Some(reason) = self.loading_reason() { self.draw_level_loading(&mut batch, reason); - self.draw_pack_toasts(&mut batch); + self.draw_pack_toasts(&mut batch, false); return batch; } // Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the @@ -5594,8 +5594,9 @@ impl Game<'_> { Screen::Playing | Screen::Options | Screen::Win => {} } self.draw_saving_indicator(&mut batch); - self.draw_toasts(&mut batch); - self.draw_pack_toasts(&mut batch); + // ToastManager.extractRenderState: F1 hides the toasts too. + self.draw_toasts(&mut batch, !show_hud); + self.draw_pack_toasts(&mut batch, !show_hud); self.remote_hud(&mut batch); self.draw_sign_editor(&mut batch); self.draw_book(&mut batch); diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 0f76d0ca9..66955a851 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -21,6 +21,9 @@ pub(super) struct Toast { frame: Frame, title: Text, slide: Slide, + /// `ToastInstance.firstSlotIndex`: the 32-pixel slot it stacks in once it + /// leaves the queue. + slot: Option, /// A `RecipeToast`: the crafting station and result of each display /// unlocked while it lasts (`recipeItems`); empty for an advancement. recipes: Vec<(String, ItemStack)>, @@ -36,6 +39,7 @@ impl Toast { frame: Frame::Task, title: Text::literal(""), slide: Slide::default(), + slot: None, recipes: items, changed: true, last_changed: 0, @@ -524,6 +528,7 @@ impl Game<'_> { frame: d.frame, title: text_of(&d.title), slide: Slide::default(), + slot: None, recipes: Vec::new(), changed: false, last_changed: 0, @@ -806,58 +811,105 @@ impl Game<'_> { c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to) }); } - /// `ToastManager` with the `AdvancementToast` and the `RecipeToast`, - /// one at a time. - pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) { + /// `ToastManager.SLOT_COUNT`. + pub(super) const TOAST_SLOTS: usize = 5; + /// `ToastManager.update` and `extractRenderState` for the `AdvancementToast`s and + /// `RecipeToast`s: up to five stack in 32-pixel slots, the rest queue. `hidden` (F1) + /// keeps them timing out without drawing them. + pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch, hidden: bool) { let multiplier = f64::from(self.settings.notification_display_time); - let Some(t) = self.adv.toasts.front_mut() else { - return; - }; - let first = t.slide.origin.is_none(); - let origin = *t.slide.origin.get_or_insert_with(Instant::now); - let now = origin.elapsed().as_millis() as i64; - let mut slide = std::mem::take(&mut t.slide); - let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); - t.slide = slide; - if finished { - self.adv.toasts.pop_front(); + let mut sound_played = false; + let mut i = 0; + while i < self.adv.toasts.len() { + let t = &mut self.adv.toasts[i]; + if t.slot.is_none() { + i += 1; + continue; + } + let origin = *t.slide.origin.get_or_insert_with(Instant::now); + let now = origin.elapsed().as_millis() as i64; + let mut slide = std::mem::take(&mut t.slide); + let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier)); + t.slide = slide; + if finished { + self.adv.toasts.remove(i); + continue; + } + // Only the first visibility change of an update plays its sound. + if let Some(show) = sound + && !std::mem::replace(&mut sound_played, true) + { + let event = if show { "ui.toast.in" } else { "ui.toast.out" }; + self.audio + .play(&format!("minecraft:{event}"), None, 1.0, 1.0); + } + i += 1; + } + // The queued toasts take the free slots in order; a challenge's own sound + // plays once as it leaves the queue. + let mut used = self.toast_slots_used(); + let mut challenge_sound = false; + for t in &mut self.adv.toasts { + if t.slot.is_some() { + continue; + } + let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else { + break; + }; + used |= 1 << slot; + t.slot = Some(slot); + challenge_sound |= !t.is_recipe() && t.frame == Frame::Challenge; + } + if challenge_sound { + self.audio + .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); + } + if hidden { return; } + for i in 0..self.adv.toasts.len() { + if let Some(slot) = self.adv.toasts[i].slot { + self.draw_toast(batch, i, 32.0 * slot as f32, multiplier); + } + } + } + /// The slots held by shown advancement, recipe and pack toasts, as bits. + pub(super) fn toast_slots_used(&self) -> u32 { + let packs = self.server_packs.toast_slots(); + self.adv + .toasts + .iter() + .filter_map(|t| t.slot) + .chain(packs) + .fold(0, |used, slot| used | 1 << slot) + } + /// The `AdvancementToast` or `RecipeToast` at `index` in its slot at `y`. + fn draw_toast(&mut self, batch: &mut HudBatch, index: usize, y: f32, multiplier: f64) { + let t = &self.adv.toasts[index]; let x = batch.width - 160.0 * t.slide.portion; let fully_for = t.slide.fully_for; let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone()); let recipe = t .is_recipe() .then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone()); - // ToastManager.update: the sound of the new visibility, and a - // challenge's own sound as it leaves the queue. - if let Some(show) = sound { - let event = if show { "ui.toast.in" } else { "ui.toast.out" }; - self.audio - .play(&format!("minecraft:{event}"), None, 1.0, 1.0); - } - if first && recipe.is_none() && frame == Frame::Challenge { - self.audio - .play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0); - } if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. let atlas = &self.gui.atlas; - batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); + batch.sprite(atlas, "gui/sprites/toast/recipe", x, y); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); let atlas = &self.gui.atlas; - batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); - batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); + batch.text(atlas, &title, x + 30.0, y + 7.0, 0xFF50_0050, false); + batch.text(atlas, &description, x + 30.0, y + 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); - self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0); - batch.scale_since(start, x, 0.0, 0.6, 0.6); - self.draw_item_model(batch, &item, x + 8.0, 8.0); + self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, y + 3.0); + batch.scale_since(start, x, y, 0.6, 0.6); + self.draw_item_model(batch, &item, x + 8.0, y + 8.0); return; } let atlas = &self.gui.atlas; - batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); + batch.sprite(atlas, "gui/sprites/toast/advancement", x, y); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), Frame::Goal => ("advancements.toast.goal", 0xFF00_FFFF), @@ -867,12 +919,12 @@ impl Game<'_> { atlas, &Text::translate(key, &[]), x + 30.0, - 7.0, + y + 7.0, color, false, ); - batch.text_styled(atlas, &title, x + 30.0, 18.0, u32::MAX, false); - self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0); + batch.text_styled(atlas, &title, x + 30.0, y + 18.0, u32::MAX, false); + self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, y + 8.0); } } /// `Advancement.name`: the bracketed title in the frame's colour, with the @@ -1053,6 +1105,7 @@ impl Game<'_> { frame: d.frame, title: text_of(&d.title), slide: Slide::default(), + slot: None, recipes: Vec::new(), changed: false, last_changed: 0, diff --git a/crates/horizon-client/src/game/server_packs.rs b/crates/horizon-client/src/game/server_packs.rs index 58d25de0e..6e6016dce 100644 --- a/crates/horizon-client/src/game/server_packs.rs +++ b/crates/horizon-client/src/game/server_packs.rs @@ -67,6 +67,13 @@ impl PackPrompt { } } +impl ServerPackState { + /// The `ToastManager` slots the download toasts hold. + pub(super) fn toast_slots(&self) -> impl Iterator + '_ { + self.notifiers.iter().filter_map(|n| n.toast.as_ref()?.slot) + } +} + /// The game's `DownloadedPackSource`. #[derive(Default)] pub(super) struct ServerPackState { @@ -423,15 +430,22 @@ impl Game<'_> { .layout(atlas, (w, h)) .draw(batch, atlas, self.cursor, [&yes, &no]); } - /// The download notifiers' toasts, each in the next 32-pixel slot - /// below an advancement or recipe toast (`ToastManager`). - pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch) { + /// The download notifiers' toasts, each in a free 32-pixel slot of the + /// `ToastManager` (`hidden`, F1, keeps them timing out undrawn). + pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch, hidden: bool) { let multiplier = f64::from(self.settings.notification_display_time); - let mut slot = usize::from(!self.adv.toasts.is_empty()); + let mut used = self.toast_slots_used(); for notifier in &mut self.server_packs.notifiers { let Some(toast) = &mut notifier.toast else { continue; }; + if toast.slot.is_none() { + let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else { + continue; + }; + used |= 1 << slot; + toast.slot = Some(slot); + } let (sound, finished) = toast.update(multiplier); if let Some(show) = sound { let event = if show { "ui.toast.in" } else { "ui.toast.out" }; @@ -442,8 +456,9 @@ impl Game<'_> { notifier.toast = None; continue; } - toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); - slot += 1; + if let (false, Some(slot)) = (hidden, toast.slot) { + toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32); + } } } /// A left click on the prompt: its answer when it hit a button. diff --git a/crates/horizon-client/src/toasts.rs b/crates/horizon-client/src/toasts.rs index b70a37036..3b6a467ea 100644 --- a/crates/horizon-client/src/toasts.rs +++ b/crates/horizon-client/src/toasts.rs @@ -63,6 +63,8 @@ impl Slide { /// has passed since its last change, or until it is hidden. pub struct SystemToast { pub slide: Slide, + /// `ToastInstance.firstSlotIndex`: its 32-pixel slot once shown. + pub slot: Option, title: String, message: Option, /// `changed`: the next update takes its time as `lastChanged`. @@ -76,6 +78,7 @@ impl SystemToast { pub fn new(title: String, message: Option) -> Self { Self { slide: Slide::default(), + slot: None, title, message, changed: false, From 62556429dcee4673e443015fcaa5bbc91abb9743 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:30:09 +0100 Subject: [PATCH 156/221] Add the four missing options to the Chat page --- crates/horizon-client/src/options_ui.rs | 33 ++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index a40d11258..4e372e75c 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -56,6 +56,7 @@ pub enum Opt { ChatVisibility, ChatColors, ChatLinks, + ChatLinksPrompt, ChatOpacity, TextBackgroundOpacity, ChatScale, @@ -64,7 +65,10 @@ pub enum Opt { ChatHeightUnfocused, ChatLineSpacing, AutoSuggestions, + HideMatchedNames, ReducedDebugInfo, + OnlySecureChat, + SaveChatDrafts, HighContrast, ShowSubtitles, MusicFrequency, @@ -167,6 +171,11 @@ impl Opt { Opt::Narrator | Opt::NarratorHotkey | Opt::ChatDelay + // Stored, but there are no blocked players, signed chat or + // chat drafts yet. + | Opt::HideMatchedNames + | Opt::OnlySecureChat + | Opt::SaveChatDrafts | Opt::DistortionEffects | Opt::GlintSpeed | Opt::GlintStrength @@ -184,6 +193,10 @@ impl Opt { Opt::Narrator => "narrator", Opt::TextBackground => "backgroundForChatOnly", Opt::ChatDelay => "chatDelay", + Opt::ChatLinksPrompt => "chatLinksPrompt", + Opt::HideMatchedNames => "hideMatchedNames", + Opt::OnlySecureChat => "onlyShowSecureChat", + Opt::SaveChatDrafts => "saveChatDrafts", Opt::DistortionEffects => "screenEffectScale", Opt::FovEffects => "fovEffectScale", Opt::DarknessPulsing => "darknessEffectScale", @@ -243,6 +256,7 @@ impl Opt { Opt::ChatVisibility => "options.chat.visibility", Opt::ChatColors => "options.chat.color", Opt::ChatLinks => "options.chat.links", + Opt::ChatLinksPrompt => "options.chat.links.prompt", Opt::ChatOpacity => "options.chat.opacity", Opt::TextBackgroundOpacity => "options.accessibility.text_background_opacity", Opt::ChatScale => "options.chat.scale", @@ -251,6 +265,9 @@ impl Opt { Opt::ChatHeightUnfocused => "options.chat.height.unfocused", Opt::ChatLineSpacing => "options.chat.line_spacing", Opt::AutoSuggestions => "options.autoSuggestCommands", + Opt::HideMatchedNames => "options.hideMatchedNames", + Opt::OnlySecureChat => "options.onlyShowSecureChat", + Opt::SaveChatDrafts => "options.chat.drafts", Opt::ReducedDebugInfo => "options.reducedDebugInfo", Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", @@ -524,6 +541,10 @@ impl Opt { Opt::HideLightningFlashes => on_off(s.file.bool("hideLightningFlashes")), Opt::MonochromeLogo => on_off(s.file.bool("darkMojangStudiosBackground")), Opt::HideSplashTexts => on_off(s.file.bool("hideSplashTexts")), + Opt::ChatLinksPrompt + | Opt::HideMatchedNames + | Opt::OnlySecureChat + | Opt::SaveChatDrafts => on_off(s.file.bool(self.file_key().unwrap())), Opt::NarratorHotkey => on_off(s.file.bool("narratorHotkey")), Opt::RotateWithMinecarts => on_off(s.file.bool("rotateWithMinecart")), Opt::HighContrastBlockOutlines => on_off(s.file.bool("highContrastBlockOutline")), @@ -718,7 +739,13 @@ impl Opt { value + 1 }; } - Opt::TextBackground | Opt::HideLightningFlashes | Opt::HideSplashTexts => { + Opt::TextBackground + | Opt::HideLightningFlashes + | Opt::HideSplashTexts + | Opt::ChatLinksPrompt + | Opt::HideMatchedNames + | Opt::OnlySecureChat + | Opt::SaveChatDrafts => { let key = self.file_key().unwrap(); s.file .set(key, crate::options_file::V::Bool(!s.file.bool(key))); @@ -1507,6 +1534,7 @@ impl OptionsUi { Opt::ChatVisibility, Opt::ChatColors, Opt::ChatLinks, + Opt::ChatLinksPrompt, Opt::ChatOpacity, Opt::TextBackgroundOpacity, Opt::ChatScale, @@ -1515,7 +1543,10 @@ impl OptionsUi { Opt::ChatHeightFocused, Opt::ChatHeightUnfocused, Opt::AutoSuggestions, + Opt::HideMatchedNames, Opt::ReducedDebugInfo, + Opt::OnlySecureChat, + Opt::SaveChatDrafts, ]), Page::Accessibility => { let mut rows = vec![Row::Buttons( From 4940a2442391aa75d0c83f1a177e6a293e92605a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:30:20 +0100 Subject: [PATCH 157/221] Send the fox's type and flags at indices 18 and 19 Fox extends Animal, and AgeableMob has two entries in 26.3 (DATA_BABY_ID 16, AGE_LOCKED 17): DATA_TYPE_ID is 18 and DATA_FLAGS_ID 19. An int at 17 is the wrong type for AGE_LOCKED's boolean on a vanilla client. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 10 +++++----- crates/horizon-client/src/game/remote_mob_data.rs | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 16e2b822d..971052b3d 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -244,17 +244,17 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(0))); } - // Fox.DATA_TYPE_ID and DATA_FLAGS_ID (sleeping 32, ...). + // Fox.DATA_TYPE_ID and DATA_FLAGS_ID (after AgeableMob's two; sleeping 32, ...). "minecraft:fox" => { if e.variant != 0 { - meta.push((17, serializer::INT, Value::Int(i32::from(e.variant)))); + meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); } - defaults.push((17, serializer::INT, Value::Int(0))); + defaults.push((18, serializer::INT, Value::Int(0))); let flags = (e.ints[0] & 0xff) as u8 as i8; if flags != 0 { - meta.push((18, serializer::BYTE, Value::Byte(flags))); + meta.push((19, serializer::BYTE, Value::Byte(flags))); } - defaults.push((18, serializer::BYTE, Value::Byte(0))); + defaults.push((19, serializer::BYTE, Value::Byte(0))); } "minecraft:cat" | "minecraft:wolf" => { // TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4. diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 50afac107..98c716c1e 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -62,10 +62,10 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // Bat.DATA_ID_FLAGS: resting in bit 0. (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Fox.DATA_TYPE_ID and DATA_FLAGS_ID. - (Species::Fox, 17, Value::Int(variant)) => { + (Species::Fox, 18, Value::Int(variant)) => { m.extra.variant = (*variant).clamp(0, 1) as u8 } - (Species::Fox, 18, Value::Byte(flags)) => m.extra.ints[0] = i32::from(*flags as u8), + (Species::Fox, 19, Value::Byte(flags)) => m.extra.ints[0] = i32::from(*flags as u8), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. (Species::Sheep, 18, Value::Byte(wool)) => { m.extra.color = (*wool & 15) as u8; From 2c0d3c1a86e51f95badc0f34783f695b5c31b017 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:30:46 +0100 Subject: [PATCH 158/221] Chat wheel counts right Shift, durability line is translated --- crates/horizon-client/src/game/chat.rs | 3 ++- crates/horizon-client/src/game/stations.rs | 18 +++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..f4078ffc5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -661,7 +661,8 @@ impl Game<'_> { { return; } - let shift = self.keys.contains(&KeyCode::ShiftLeft); + // ChatScreen.mouseScrolled: `hasShiftDown`, either Shift key. + let shift = self.has_shift_down(); let amount = amount.clamp(-1.0, 1.0) * if shift { 1.0 } else { 7.0 }; self.ui.chat.scroll_by(amount as i32, true); } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 361879d2e..43eb1ca6c 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -2023,15 +2023,19 @@ impl Game<'_> { && stack.damage > 0 && advanced { - push( - &mut lines, - format!( - "Durability: {} / {}", - info.max_damage - stack.damage, - info.max_damage + // `item.durability`, in the selected language. + lines.push(( + horizon_client::text::Text::translate( + "item.durability", + &[ + horizon_client::text::Text::literal( + (info.max_damage - stack.damage).to_string(), + ), + horizon_client::text::Text::literal(info.max_damage.to_string()), + ], ), u32::MAX, - ); + )); } // ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id // and how many components the stack has. From 581828bf9419573b064976f704c969a279b742e6 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:30:47 +0100 Subject: [PATCH 159/221] Show the smithing template lines in item tooltips --- crates/horizon-client/src/game/stations.rs | 5 ++ crates/horizon-client/src/item_tooltip.rs | 60 +++++++++++++--------- 2 files changed, 41 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 361879d2e..47ae04472 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1768,6 +1768,11 @@ impl Game<'_> { }; let gray = rgba(170, 170, 170, 255); let item_info = self.res.items().get(&stack.item); + // SmithingTemplateItem.appendHoverText: `Item.appendHoverText` comes + // before the components. + for (text, c) in horizon_client::item_tooltip::smithing_template_lines(stack, &translate) { + push(&mut lines, text, c); + } // InstrumentComponent.addToTooltip. if let Some(text) = horizon_client::item_tooltip::instrument_line(stack, &display, &translate) diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs index 63a19b114..ce4fc352d 100644 --- a/crates/horizon-client/src/item_tooltip.rs +++ b/crates/horizon-client/src/item_tooltip.rs @@ -484,6 +484,37 @@ pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize { keys.len() } +/// `SmithingTemplateItem.appendHoverText`: the template's kind, what it applies to +/// and its ingredients (gray titles over blue descriptions); none for other items. +pub fn smithing_template_lines( + stack: &ItemStack, + translate: &dyn Fn(&str) -> Option, +) -> Vec<(String, u32)> { + let path = stack.item.trim_start_matches("minecraft:"); + if !path.ends_with("_smithing_template") { + return Vec::new(); + } + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let kind = if path == "netherite_upgrade_smithing_template" { + "netherite_upgrade" + } else { + "armor_trim" + }; + let (title, description) = (rgba(170, 170, 170, 255), rgba(85, 85, 255, 255)); + let described = |what: &str| { + let key = format!("item.minecraft.smithing_template.{kind}.{what}"); + (format!(" {}", text(&key)), description) + }; + vec![ + (text("item.minecraft.smithing_template"), title), + (String::new(), u32::MAX), + (text("item.minecraft.smithing_template.applies_to"), title), + described("applies_to"), + (text("item.minecraft.smithing_template.ingredients"), title), + described("ingredients"), + ] +} + /// The lines of `stack` below its name that its components give, in /// `ItemStack.addDetailsToTooltip` order. pub fn detail_lines( @@ -494,30 +525,11 @@ pub fn detail_lines( let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); let path = stack.item.trim_start_matches("minecraft:"); let mut lines = Vec::new(); - // SmithingTemplateItem.appendHoverText. - if path.ends_with("_smithing_template") { - let kind = if path == "netherite_upgrade_smithing_template" { - "netherite_upgrade" - } else { - "armor_trim" - }; - lines.push(text("item.minecraft.smithing_template")); - lines.push(String::new()); - lines.push(text("item.minecraft.smithing_template.applies_to")); - lines.push(format!( - " {}", - text(&format!( - "item.minecraft.smithing_template.{kind}.applies_to" - )) - )); - lines.push(text("item.minecraft.smithing_template.ingredients")); - lines.push(format!( - " {}", - text(&format!( - "item.minecraft.smithing_template.{kind}.ingredients" - )) - )); - } + lines.extend( + smithing_template_lines(stack, translate) + .into_iter() + .map(|l| l.0), + ); let display = TooltipDisplay::for_stack(stack); lines.extend(bees_line(stack, &display, translate)); lines.extend(honey_line(stack, &display, translate)); From e74a1fe46155aad64f29ac0ae5d05e151632d0a3 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:31:46 +0100 Subject: [PATCH 160/221] Use every player in the level for patrols, sniffers, allays, trap horses and other world checks on the server thread --- crates/horizon-client/src/entity_nbt.rs | 14 +++++-- crates/horizon-client/src/game/allays.rs | 41 +++++++++++++++++-- crates/horizon-client/src/game/creatures.rs | 14 +++---- crates/horizon-client/src/game/dragon.rs | 13 +++--- crates/horizon-client/src/game/lan_actions.rs | 5 ++- crates/horizon-client/src/game/passengers.rs | 17 +++++--- crates/horizon-client/src/game/raids.rs | 18 ++++---- crates/horizon-client/src/game/sculk.rs | 40 ++++++++---------- crates/horizon-client/src/game/sniffers.rs | 30 ++++++++------ 9 files changed, 119 insertions(+), 73 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index c49af48c9..d175a14fb 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -450,7 +450,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "memories", Tag::compound([( "minecraft:liked_player", - Tag::compound([("value", Tag::IntArray(vec![0, 0, 0, 1]))]), + Tag::compound([( + "value", + Tag::IntArray(m.extra.owner.unwrap_or([0, 0, 0, 1]).to_vec()), + )]), )]), )]), ); @@ -994,11 +997,14 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.ints[1] = number(first.get("count")).unwrap_or(1) as i32; } m.extra.egg_time = number(tag.get("DuplicationCooldown")).unwrap_or(0) as i32; - m.extra.tame = tag + let liked = tag .get("Brain") .and_then(|b| b.get("memories")) - .and_then(|b| b.get("minecraft:liked_player")) - .is_some(); + .and_then(|b| b.get("minecraft:liked_player")); + m.extra.tame = liked.is_some(); + m.extra.owner = liked + .and_then(|l| l.get("value")) + .and_then(|v| crate::save::uuid_from_tag(Some(v))); } if crate::mobs::camel::is_camel(m.species()) { let sitting = matches!(tag.get("LastPoseTick"), Some(Tag::Long(v)) if *v < 0); diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index bed835663..10ad5c315 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -8,7 +8,6 @@ use horizon_core::random::RandomSource; impl Game<'_> { pub(super) fn tick_allays(&mut self) { let griefing = self.ui.rules.bool("mob_griefing"); - let player = self.player.as_ref().map(|p| p.position); // The playing jukeboxes, found at the first allay: no allay starts // or stops one, and the block entities run into the thousands. let mut jukeboxes: Option> = None; @@ -58,7 +57,7 @@ impl Game<'_> { }; let Some((j, _)) = wanted else { self.mobs[i].extra.point = None; - self.allay_deliver(i, player); + self.allay_deliver(i); continue; }; let e = &self.dropped[j]; @@ -90,14 +89,46 @@ impl Game<'_> { } } } + /// `AllayAi.getLikedPlayer`: the player the allay was given an item by, + /// found by UUID among the host and the guests of the level (the window + /// is a guest on the server thread), when they are not a spectator and + /// within 64 blocks. + fn allay_liked_player(&self, i: usize) -> Option { + let m = &self.mobs[i]; + if !m.extra.tame { + return None; + } + // An allay saved before its player was kept belongs to the host. + let uuid = m + .extra + .owner + .filter(|u| *u != [0, 0, 0, 1]) + .or(self.level.player_uuid) + .unwrap_or([0, 0, 0, 1]); + let host = self + .player_view() + .filter(|p| !p.spectator && self.level.player_uuid.unwrap_or([0, 0, 0, 1]) == uuid) + .map(|p| p.position); + let found = host.or_else(|| { + self.lan_present() + .into_iter() + .find(|p| p.uuid == uuid && !p.spectator) + .map(|p| { + horizon_core::geometry::Vec3::new(p.position[0], p.position[1], p.position[2]) + }) + }); + found.filter(|p| p.distance_squared(m.position) < 64.0 * 64.0) + } /// `GoAndGiveItemsToTarget` / `AllayAi.throwItem`: within 3 blocks of /// the deposit, one item a tick, each restarting the three-second pause /// before it picks anything up again. - fn allay_deliver(&mut self, i: usize, player: Option) { + fn allay_deliver(&mut self, i: usize) { let m = &self.mobs[i]; if m.extra.ints[1] <= 0 { return; } + let player = self.allay_liked_player(i); + let m = &self.mobs[i]; let target = match m.extra.home.filter(|_| m.extra.ints[2] > 0) { Some(h) => horizon_core::geometry::Vec3::new( f64::from(h[0]) + 0.5, @@ -166,11 +197,14 @@ impl Game<'_> { self.consume_held(); return true; } + let acting = self.acting_uuid(); let holds = m.extra.main_hand.is_some(); if !holds && !item.is_empty() { let m = &mut self.mobs[index]; m.extra.main_hand = Some(item.into()); m.extra.tame = true; + // `Allay.mobInteract` remembers LIKED_PLAYER by UUID. + m.extra.owner = Some(acting); self.audio .play("minecraft:entity.allay.item_given", Some(at), 2.0, 1.0); self.consume_held(); @@ -185,6 +219,7 @@ impl Game<'_> { .unwrap_or_else(|| "minecraft:air".into()); let carried = std::mem::take(&mut m.extra.ints[1]); m.extra.tame = false; + m.extra.owner = None; self.audio .play("minecraft:entity.allay.item_taken", Some(at), 2.0, 1.0); if carried > 0 { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..b6720b928 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -424,9 +424,10 @@ impl Game<'_> { sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), + // The first player in the level: a server has no player of its own. difficulty: self.local_difficulty( - self.player - .as_ref() + self.level_players() + .first() .map_or([0.0; 3], |p| [p.position.x, p.position.y, p.position.z]), ), } @@ -3754,13 +3755,10 @@ impl Game<'_> { f64::from((pos[0] >> 4) * 16 + 8), f64::from((pos[2] >> 4) * 16 + 8), ]; - let spectator = self.spectator(); - let Some(close) = self.player.as_ref().filter(|_| !spectator).map(|p| { + let close = self.level_players().iter().any(|p| { let (dx, dz) = (p.position.x - centre[0], p.position.z - centre[1]); - dx * dx + dz * dz < 16384.0 - }) else { - return; - }; + !p.spectator && dx * dx + dz * dz < 16384.0 + }); if !close { return; } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8f3fdb224..2970d6e74 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2859,14 +2859,11 @@ impl Game<'_> { let (a, b) = (room.min_position(), room.max_position()); lo.x < b.x && hi.x > a.x && lo.y < b.y && hi.y > a.y && lo.z < b.z && hi.z > a.z }; - let player = self.player.as_ref().is_some_and(|p| { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - touches( - Vec3::new(p.position.x - w, p.position.y, p.position.z - w), - Vec3::new(p.position.x + w, p.position.y + h, p.position.z + w), - ) - }); + // Level.getEntities: the host's player and every guest in the level. + let player = self + .fight_players() + .iter() + .any(|p| !p.spectator && touches(p.bounds.min_position(), p.bounds.max_position())); player || self.crystals.iter().any(|c| { touches( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..6587ed6b9 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2321,7 +2321,10 @@ impl Game<'_> { if let Some((at, velocity)) = soul { super::lan_particles::send_soul_particle(host, at, velocity); } - self.as_guest(host, conn, |game| game.tick_player_sculk_events()); + self.as_guest(host, conn, |game| { + game.sculk_step_on_player(); + game.tick_player_sculk_events(); + }); for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at), diff --git a/crates/horizon-client/src/game/passengers.rs b/crates/horizon-client/src/game/passengers.rs index 8f205c484..c39a6d1af 100644 --- a/crates/horizon-client/src/game/passengers.rs +++ b/crates/horizon-client/src/game/passengers.rs @@ -279,11 +279,13 @@ impl Game<'_> { /// horse is a trap for fifteen minutes; a player within ten blocks springs /// it. pub(super) fn tick_skeleton_traps(&mut self) { - let player = self - .player - .as_ref() - .filter(|p| !p.health.dead_or_dying()) - .map(|p| p.position); + // `Level.hasNearbyAlivePlayer`: alive, not a spectator, in the level. + let players: Vec<_> = self + .level_players() + .into_iter() + .filter(|p| p.alive && !p.spectator) + .map(|p| p.position) + .collect(); let mut sprung = Vec::new(); for m in &mut self.mobs { if m.species() != Species::SkeletonHorse || !m.extra.trap || !m.alive() { @@ -296,7 +298,10 @@ impl Game<'_> { continue; } } - if player.is_some_and(|p| m.distance_sqr(p) < TRAP_RANGE * TRAP_RANGE) { + if players + .iter() + .any(|&p| m.distance_sqr(p) < TRAP_RANGE * TRAP_RANGE) + { sprung.push(m.id); } } diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index da7c79394..89fca4571 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -102,11 +102,12 @@ impl RaidLevel for Lvl<'_, '_> { && g.res.facts().is_air(g.world.block(x, y, z)) } fn player(&self) -> Option { - let p = self.game.player.as_ref()?; + // The first player in the level: a server has no player of its own. + let p = self.game.level_players().into_iter().next()?; Some(RaidPlayer { position: [p.position.x, p.position.y, p.position.z], block: block_of(p.position), - alive: !p.health.dead_or_dying(), + alive: p.alive, }) } } @@ -174,12 +175,13 @@ impl PatrolLevel for PatrolCx<'_, '_, '_> { fn bright_outside(&self) -> bool { self.level.game.dim == Dim::Overworld && self.level.game.sky_darken() < 4 } + /// `PatrolSpawner.tick` picks from `level.players()`: the local player + /// and every guest in the level. fn patrol_players(&self) -> Vec<([i32; 3], bool)> { - let g = self.level.game; - g.player - .as_ref() - .map(|p| (block_of(p.position), g.spectator())) - .into_iter() + self.level + .players + .iter() + .map(|p| (block_of(p.position), p.spectator)) .collect() } fn sections_to_village(&self, pos: [i32; 3]) -> i32 { @@ -633,7 +635,7 @@ impl Game<'_> { /// `Raid.playSound`: the horn, 13 blocks away from the player toward the /// wave, for players within 64 blocks or in the raid. fn raid_horn(&mut self, id: i32, pos: [i32; 3]) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { + let Some(p) = self.level_players().first().map(|p| p.position) else { return; }; let in_raid = self.raiding.raids.get(id).is_some_and(|r| r.bar.player); diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 7916c46a1..d3111a75f 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -876,17 +876,26 @@ impl Game<'_> { /// `SculkSensorBlock.stepOn` and `SculkShriekerBlock.stepOn`: standing on /// them is heard (or seen) every tick. fn sculk_step_on(&mut self) { + self.sculk_step_on_player(); let mut standing: Vec<(Who, [f64; 3])> = Vec::new(); - if let Some(p) = self.player.as_ref() - && p.ground.on_ground - { - standing.push((Who::Player, [p.position.x, p.position.y, p.position.z])); - } for m in &self.mobs { if m.alive() && m.on_ground { standing.push((Who::Mob(m.id), [m.position.x, m.position.y, m.position.z])); } } + self.sculk_stand_on(standing); + } + /// `stepOn` for the player in place: the host, or a guest swapped in + /// (`guest_server_tick`), as a server has no player of its own. + pub(super) fn sculk_step_on_player(&mut self) { + if let Some(p) = self.player.as_ref() + && p.ground.on_ground + { + let at = [p.position.x, p.position.y, p.position.z]; + self.sculk_stand_on(vec![(Who::Player, at)]); + } + } + fn sculk_stand_on(&mut self, standing: Vec<(Who, [f64; 3])>) { for (who, at) in standing { // getOnPosLegacy: 0.2 below the feet. let key = ( @@ -1108,23 +1117,10 @@ impl Game<'_> { /// in the way (`isUnobstructed`), and no block collision. fn warden_fits(&self, mob: &Mob) -> bool { let bounds = mob.bounds(); - let player_blocks = !self.spectator() - && self.player.as_ref().is_some_and(|p| { - let w = f64::from(p.dimensions.width) / 2.0; - let b = horizon_core::geometry::Aabb::new( - horizon_core::geometry::Vec3::new( - p.position.x - w, - p.position.y, - p.position.z - w, - ), - horizon_core::geometry::Vec3::new( - p.position.x + w, - p.position.y + f64::from(p.dimensions.height), - p.position.z + w, - ), - ); - !p.health.dead_or_dying() && b.intersects(bounds) - }); + let player_blocks = self + .level_players() + .iter() + .any(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); if player_blocks || self .mobs diff --git a/crates/horizon-client/src/game/sniffers.rs b/crates/horizon-client/src/game/sniffers.rs index 8e851d028..5027f5c2b 100644 --- a/crates/horizon-client/src/game/sniffers.rs +++ b/crates/horizon-client/src/game/sniffers.rs @@ -5,9 +5,8 @@ use super::Game; use horizon_client::{ items::ItemStack, mobs::{Mob, Species, sniffer}, - particles::Particle, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { /// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the @@ -46,15 +45,20 @@ impl Game<'_> { /// block's hit sound between the 1.7th and the 6th second of the /// digging animation) and `playSearchingSound`. pub(super) fn tick_sniffer_effects(&mut self) { - let Some(camera) = self.player.as_ref().map(|p| p.position) else { + // Vanilla runs these on each client: a sniffer within 32 blocks of + // any player in the level (the host and the guests) shows them. + let players = self.level_players(); + if players.is_empty() { return; - }; + } for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Sniffer || !m.alive() || m.silent - || m.position.distance_squared(camera) > 32.0 * 32.0 + || !players + .iter() + .any(|p| m.position.distance_squared(p.position) <= 32.0 * 32.0) { continue; } @@ -79,20 +83,20 @@ impl Game<'_> { } let head = sniffer::head_block(m); let below = self.world.block(head[0], head[1] - 1, head[2]); - let Some((sprite, tint)) = self.particle_sprite(below, [head[0], head[1] - 1, head[2]]) - else { + if self + .particle_sprite(below, [head[0], head[1] - 1, head[2]]) + .is_none() + { continue; - }; + } let dust = [ f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5 - f64::from(0.65_f32), f64::from(head[2]) + 0.5, ]; - for _ in 0..30 { - let particle = - Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint); - self.particles.push(particle); - } + // Drawn in this window when it has one, and sent to the players + // within 32 blocks (the server thread's window is one of them). + self.landing_dust(None, below, Vec3::new(dust[0], dust[1], dust[2]), 30, 0.0); if self.mobs[i].age.is_multiple_of(10) { let hit = self.res.facts().get(below).sounds.hit.clone(); self.audio.play(&hit, Some(at), 0.5, 0.5); From dca3bb89fe37a9a24b815eb75902767fac4e8d80 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:32:01 +0100 Subject: [PATCH 161/221] Show the air bubbles only when the eyes are below the water surface --- crates/horizon-client/src/game.rs | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..929a968c8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5495,17 +5495,9 @@ impl Game<'_> { } else { hud_layout::HeartKind::Normal }; - let eye = p.position.y + f64::from(p.dimensions.eye_height); - let under_water = self - .res - .facts() - .get(self.world.block( - p.position.x.floor() as i32, - eye.floor() as i32, - p.position.z.floor() as i32, - )) - .fluid - == horizon_client::blocks::Fluid::Water; + // Hud.extractAirBubbles: `isEyeInFluidMatching`, so the eyes are below + // the surface, not merely in the water block. + let under_water = p.is_eye_in_fluid(horizon_client::motion::WATER); let inputs = hud_layout::HealthInputs { tick: self.ticks as i32, millis: self.started.elapsed().as_millis() as i64, From 46f674f842a53d6c211d9189c79a8bd29ec97013 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:32:31 +0100 Subject: [PATCH 162/221] Give dolphins swim-with-player, jump and treasure goals and fish feeding --- .../examples/probe/mob_ai_probe.rs | 1 + crates/horizon-client/src/game/creatures.rs | 40 +++ crates/horizon-client/src/game/lan_mobs.rs | 1 + crates/horizon-client/src/mobs.rs | 9 + crates/horizon-client/src/mobs/aquatic.rs | 3 + crates/horizon-client/src/mobs/dolphin.rs | 263 ++++++++++++++++++ crates/horizon-client/src/mobs/goals.rs | 5 + 7 files changed, 322 insertions(+) create mode 100644 crates/horizon-client/src/mobs/dolphin.rs diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 5b6c26d2f..31b9508dd 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -1045,6 +1045,7 @@ pub fn main() -> horizon_client::Result<()> { alive: true, creative: s.creative, sneaking: false, + swimming: false, look: [0.0, 0.0, 1.0], main_hand: s.hand.as_deref().map(Into::into), off_hand: None, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..5c0d1aa11 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -182,6 +182,7 @@ impl Game<'_> { // EntitySelector.NO_CREATIVE_OR_SPECTATOR. creative: self.creative || self.spectator(), sneaking: self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft), + swimming: p.swimming, look: view_vector(self.yaw, self.pitch), main_hand: self.held().map(|s| s.item.clone()), off_hand: None, @@ -1289,6 +1290,27 @@ impl Game<'_> { .list .retain(|e| e.id != "mining_fatigue"); } + MobEvent::DolphinTreasure { mob } => { + // ServerLevel.findNearestMapStructure(#dolphin_located, 50). + let Some(at) = self.mobs.iter().find(|m| m.id == mob).map(|m| { + [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ] + }) else { + continue; + }; + let names = self.structure_tag("minecraft:dolphin_located"); + let found = self + .end + .locator() + .filter(|_| !names.is_empty()) + .and_then(|t| t.locate(&names, at, 50)); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { + m.extra.home = found.map(|(_, p)| p); + } + } MobEvent::EffectPlayer { effect, ticks, @@ -2881,6 +2903,12 @@ impl Game<'_> { .item_tags .get("minecraft:creeper_igniters") .is_some_and(|t| t.contains(&*item)); + let fish = self + .res + .items() + .item_tags + .get("minecraft:fishes") + .is_some_and(|t| t.contains(&*item)); let damageable = self .res .items() @@ -3168,6 +3196,18 @@ impl Game<'_> { self.trigger_entity("minecraft:tame_animal", "entity", &view); } } + // Dolphin.mobInteract: a fish makes a baby grow by a tenth and an + // adult remember it (`gotFish`), to swim to a treasure. + Species::Dolphin if fish => { + eat = Some(("entity.dolphin.eat", 1.0, 1.0)); + if m.extra.age < 0 { + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, secs, true); + } else { + m.extra.flag = true; + } + consume = true; + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 6527f1015..a783cd093 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -358,6 +358,7 @@ mod tests { alive: true, creative, sneaking: false, + swimming: false, look: [0.0; 3], main_hand: None, off_hand: None, diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..bf84e5040 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -25,6 +25,7 @@ pub mod creaking; pub mod creaking_heart; pub mod cube; pub mod data; +pub mod dolphin; pub mod doors; pub mod drops; pub mod enderman; @@ -1087,6 +1088,12 @@ pub enum MobEvent { }, /// Regeneration support after an axolotl-assisted kill. AxolotlSupportPlayer, + /// A dolphin that was given a fish asks the game for the nearest + /// shipwreck or ocean ruin (`DolphinSwimToTreasureGoal.start`): the game + /// sets the dolphin's `extra.home` to it, or leaves it empty. + DolphinTreasure { + mob: u32, + }, /// Apply an effect to the player (witch potions, bee stings, cave spider poison). EffectPlayer { effect: &'static str, @@ -1540,6 +1547,8 @@ pub struct PlayerView { pub alive: bool, pub creative: bool, pub sneaking: bool, + /// `Entity.isSwimming`. + pub swimming: bool, pub look: [f64; 3], pub main_hand: Option>, pub off_hand: Option>, diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index f63a42239..ffc443b21 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -128,9 +128,12 @@ pub fn register(m: &mut Mob) { let g = &mut m.ai.goals; g.add(0, BreathAir); g.add(0, TryFindWater::default()); + g.add(1, super::dolphin::SwimToTreasure::default()); + g.add(2, super::dolphin::SwimWithPlayer::new(4.0)); g.add(4, Stroll::swimming(1.0, 10)); g.add(4, RandomLookAround::default()); g.add(5, LookAtPlayer::new(6.0)); + g.add(5, super::dolphin::Jump::new(10)); g.add(6, MeleeAttack::new(1.2, true)); m.ai.targets.add(1, HurtByTarget::new().alert()); m.ai.mov.kind = MoveKind::SmoothSwimming { diff --git a/crates/horizon-client/src/mobs/dolphin.rs b/crates/horizon-client/src/mobs/dolphin.rs new file mode 100644 index 000000000..2f9643cef --- /dev/null +++ b/crates/horizon-client/src/mobs/dolphin.rs @@ -0,0 +1,263 @@ +//! Dolphin goals: `DolphinSwimToTreasureGoal`, `DolphinSwimWithPlayerGoal` +//! and `DolphinJumpGoal`. `extra.flag` is `gotFish` and `extra.home` the +//! `treasurePos` the game found for it (`MobEvent::DolphinTreasure`). +use super::{ + Mob, MobEvent, Who, + goals::{Cx, Goal, JUMP, LOOK, MOVE, goal_clone, reduced}, +}; +use crate::blocks::Fluid; +use horizon_core::random::RandomSource; + +/// `Entity.getMotionDirection`: the horizontal step of the yaw +/// (`Direction.fromYRot`: south, west, north, east). +fn motion_step(yaw: f32) -> [i32; 2] { + match (yaw / 90.0 + 0.5).floor() as i32 & 3 { + 0 => [0, 1], + 1 => [-1, 0], + 2 => [0, -1], + _ => [1, 0], + } +} + +/// `DolphinSwimToTreasureGoal`: a dolphin that was fed a fish leads the way to +/// a shipwreck or an ocean ruin within 50 sectors. +#[derive(Clone, Debug, Default)] +pub struct SwimToTreasure { + stuck: bool, +} +impl SwimToTreasure { + /// `BlockPos.containing(x, dolphin.getY(), z).closerToCenterThan(position, 4)`. + fn arrived(m: &Mob) -> bool { + let Some(t) = m.extra.home else { return false }; + let d = [ + f64::from(t[0]) + 0.5 - m.position.x, + m.position.y.floor() + 0.5 - m.position.y, + f64::from(t[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 16.0 + } +} +impl Goal for SwimToTreasure { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn interruptable(&self) -> bool { + false + } + fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.flag && m.air >= 100 + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + m.extra.home.is_some() && !Self::arrived(m) && !self.stuck && m.air >= 100 + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.stuck = false; + m.nav_stop(); + // The game looks for the structure and sets the position, or none. + m.extra.home = None; + cx.events.push(MobEvent::DolphinTreasure { mob: m.id }); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + if m.extra.home.is_none() || Self::arrived(m) || self.stuck { + m.extra.flag = false; + } + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(t) = m.extra.home else { return }; + let close = m.ai.nav.target_pos.is_some_and(|p| { + let d = [ + f64::from(p[0]) + 0.5 - m.position.x, + f64::from(p[1]) + 0.5 - m.position.y, + f64::from(p[2]) + 0.5 - m.position.z, + ]; + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 144.0 + }); + if !close && !m.ai.nav.is_done() { + return; + } + let treasure = [ + f64::from(t[0]) + 0.5, + f64::from(t[1]) + 0.5, + f64::from(t[2]) + 0.5, + ]; + let eighth = f64::from(std::f32::consts::FRAC_PI_8); + let half = f64::from(std::f32::consts::FRAC_PI_2); + let mut next = m.default_random_pos_towards(cx.w, 16, 1, treasure, eighth); + if next.is_none() { + next = m.default_random_pos_towards(cx.w, 8, 4, treasure, half); + } + // isPathfindable(WATER) is a water fluid state. + if let Some(n) = next + && cx.w.fluid( + n[0].floor() as i32, + n[1].floor() as i32, + n[2].floor() as i32, + ) != Fluid::Water + { + next = m.default_random_pos_towards(cx.w, 8, 5, treasure, half); + } + let Some(next) = next else { + self.stuck = true; + return; + }; + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + m.look_at_speed(next, y, x); + m.nav_move_to(cx.w, next, 1.3); + if m.random.next_int_bound(80).unwrap_or(1) == 0 { + // Entity event 38: happy villager particles about the dolphin. + cx.events.push(MobEvent::AroundSelf { + kind: "happy_villager", + feet: [m.position.x, m.position.y, m.position.z], + width: f64::from(m.width()), + height: f64::from(m.height()), + burst: crate::particles::Burst::DOLPHIN, + }); + } + } +} + +/// `DolphinSwimWithPlayerGoal`: swim up to a swimming player and give them +/// Dolphin's Grace. +#[derive(Clone, Debug)] +pub struct SwimWithPlayer { + speed: f64, +} +impl SwimWithPlayer { + pub fn new(speed: f64) -> Self { + Self { speed } + } +} +impl Goal for SwimWithPlayer { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | LOOK + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + // getNearestPlayer(forNonCombat().range(10).ignoreLineOfSight()). + m.can_see_player_through_walls(cx.w, 10.0) + && cx.w.player.as_ref().is_some_and(|p| p.swimming) + && m.ai.target != Some(Who::Player) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + cx.w.player + .as_ref() + .is_some_and(|p| p.swimming && m.distance_sqr(p.position) < 256.0) + } + fn start(&mut self, _: &mut Mob, cx: &mut Cx) { + cx.events.push(grace()); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.nav_stop(); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(p) = cx.w.player.clone() else { return }; + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + m.look_at_speed(p.eye, y, x); + if m.distance_sqr(p.position) < 6.25 { + m.nav_stop(); + } else { + m.nav_move_to_entity( + cx.w, + [p.position.x, p.position.y, p.position.z], + 1, + self.speed, + ); + } + if p.swimming && m.random.next_int_bound(6).unwrap_or(1) == 0 { + cx.events.push(grace()); + } + } +} +/// `MobEffectInstance(DOLPHINS_GRACE, 100)`. +fn grace() -> MobEvent { + MobEvent::EffectPlayer { + effect: "minecraft:dolphins_grace", + ticks: 100, + amplifier: 0, + } +} + +/// `DolphinJumpGoal`: leap out of clear water and arc back in. +#[derive(Clone, Debug)] +pub struct Jump { + interval: i32, + breached: bool, +} +impl Jump { + pub fn new(interval: i32) -> Self { + Self { + interval: reduced(interval), + breached: false, + } + } +} +impl Goal for Jump { + goal_clone!(); + fn flags(&self) -> u8 { + JUMP | MOVE + } + fn interruptable(&self) -> bool { + false + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if m.random.next_int_bound(self.interval).unwrap_or(1) != 0 { + return false; + } + let [sx, sz] = motion_step(m.yaw); + let (bx, by, bz) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let w = cx.w; + [0, 1, 4, 5, 6, 7].into_iter().all(|i| { + let (x, z) = (bx + sx * i, bz + sz * i); + // waterIsClear, then surfaceIsClear. + w.fluid(x, by, z) == Fluid::Water + && !w.has_tag("minecraft:blocks_dolphin_jump", w.block_name(x, by, z)) + && w.facts.is_air(w.world.block(x, by + 1, z)) + && w.facts.is_air(w.world.block(x, by + 2, z)) + }) + } + fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool { + let yd = m.velocity.y; + (yd * yd >= f64::from(0.03f32) + || m.head_pitch == 0.0 + || m.head_pitch.abs() >= 10.0 + || !m.fluids.in_water) + && !m.on_ground + } + fn start(&mut self, m: &mut Mob, _: &mut Cx) { + let [sx, sz] = motion_step(m.yaw); + m.velocity.x += f64::from(sx) * 0.6; + m.velocity.y += 0.7; + m.velocity.z += f64::from(sz) * 0.6; + m.nav_stop(); + } + fn stop(&mut self, m: &mut Mob, _: &mut Cx) { + m.head_pitch = 0.0; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let already = self.breached; + if !already { + self.breached = cx.w.fluid( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ) == Fluid::Water; + } + if self.breached && !already { + m.sound("entity.dolphin.jump", cx.events); + } + let v = m.velocity; + if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 { + // Mth.rotLerp(0.2, xRot, 0). + m.head_pitch += 0.2 * super::living::wrap(0.0 - m.head_pitch); + } else if v.length() > f64::from(1.0e-5f32) { + let horizontal = v.x.hypot(v.z); + m.head_pitch = ((-v.y).atan2(horizontal) * f64::from(180.0f32) + / f64::from(std::f32::consts::PI)) as f32; + } + } +} diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index d0b784166..b172597d9 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -595,6 +595,11 @@ impl Mob { pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool { self.player_in_range(w, range, true) } + /// `TargetingConditions.forNonCombat().range(range).ignoreLineOfSight()` + /// for the player. + pub fn can_see_player_through_walls(&mut self, w: &MobWorld, range: f64) -> bool { + self.player_in_range(w, range, false) + } fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { let Some(p) = &w.player else { return false }; if !p.alive || p.spectator { From 306c6625e90649544ecb3373c0126760076b1c67 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:33:07 +0100 Subject: [PATCH 163/221] Shear snow golems and bogged by hand and use vanilla's snowball spread --- crates/horizon-client/src/game/creatures.rs | 37 +++++++++++++++++++ .../horizon-client/src/game/remote_mob_use.rs | 2 + crates/horizon-client/src/mobs/golem.rs | 4 +- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..059ee1c30 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2857,6 +2857,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.interact_shear_mob(index, &item) { + self.swing_arm(); + return Ok(true); + } // AbstractHorse.mobInteract: feed, equip or ride. if self.interact_mount(index, &item) { self.swing_arm(); @@ -3255,6 +3259,39 @@ impl Game<'_> { } Ok(true) } + /// `SnowGolem.mobInteract` and `Bogged.mobInteract` with shears: the + /// pumpkin or the mushrooms come off (the shearing loot table), the shear + /// game event is posted and the tool takes one damage. + fn interact_shear_mob(&mut self, index: usize, item: &str) -> bool { + let m = &self.mobs[index]; + if item != "minecraft:shears" || !m.alive() || m.extra.sheared { + return false; + } + let (sound, table, height) = match m.species() { + Species::SnowGolem => ( + "minecraft:entity.snow_golem.shear", + "minecraft:shearing/snow_golem", + m.eye_height(), + ), + Species::Bogged => ( + "minecraft:entity.bogged.shear", + "minecraft:shearing/bogged", + f64::from(m.height()), + ), + _ => return false, + }; + let at = m.position; + let tool = self.held().cloned(); + self.audio.play(sound, Some([at.x, at.y, at.z]), 1.0, 1.0); + self.mobs[index].extra.sheared = true; + for stack in self.sequence_loot(table, table, tool.as_ref()) { + self.spawn_at_location(at, height, stack); + } + let ctx = self.who_context(Some(horizon_client::mobs::Who::Player), None); + self.post_game_event("minecraft:shear", [at.x, at.y, at.z], ctx); + self.damage_held_tool(); + true + } pub(super) fn damage_held_tool(&mut self) { if self.creative { return; diff --git a/crates/horizon-client/src/game/remote_mob_use.rs b/crates/horizon-client/src/game/remote_mob_use.rs index 9575cf925..31b1c1ad2 100644 --- a/crates/horizon-client/src/game/remote_mob_use.rs +++ b/crates/horizon-client/src/game/remote_mob_use.rs @@ -61,6 +61,8 @@ impl Game<'_> { ) && !baby } Species::Sheep => item == "minecraft:shears" || item.ends_with("_dye"), + // SnowGolem.mobInteract: shears take the pumpkin off. + Species::SnowGolem => item == "minecraft:shears" && !m.extra.sheared, // Bucketable.bucketMobPickup. Species::Cod | Species::Salmon diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index c41c34f11..593b855c4 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -309,12 +309,12 @@ fn snowball_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) { let zd = t.position.z - m.position.z; let yo = (xd * xd + zd * zd).sqrt() * 0.2; let mut p = Projectile::new(ProjectileKind::Snowball, start, Some(Who::Mob(m.id))); - // rangedAttackUncertainty: 14 - 4 * difficulty (normal: 6). + // SnowGolem.rangedAttackUncertainty: 12 on every difficulty. p.shoot( &mut crate::projectiles::own_random(m), [xd, yd + yo - start.y, zd], 1.6, - 6.0, + 12.0, ); cx.events.push(MobEvent::Projectile(p)); let pitch = 0.4 / (m.random.next_float() * 0.4 + 0.8); From 6c36da40e06897f483096371af5211f1315f4e64 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:33:50 +0100 Subject: [PATCH 164/221] Turn skeletons into strays after standing in powder snow --- crates/horizon-client/src/mobs/undead.rs | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 3707f4bbe..d87a09947 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -498,10 +498,67 @@ fn zombified_piglin_step(m: &mut Mob, cx: &mut Cx) { } } } +/// `Entity.isInPowderSnow`: the mob's box, shrunk by `1.0E-5` as in +/// `checkInsideBlocks`, touches powder snow. +fn in_powder_snow(m: &Mob, w: &super::MobWorld) -> bool { + let b = m.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + let (min, max) = (b.min_position(), b.max_position()); + for x in min.x.floor() as i32..=max.x.floor() as i32 { + for y in min.y.floor() as i32..=max.y.floor() as i32 { + for z in min.z.floor() as i32..=max.z.floor() as i32 { + if &*w.facts.get(w.world.block(x, y, z)).name == "minecraft:powder_snow" { + return true; + } + } + } + } + false +} +/// `Skeleton.freezingTracker` (`ConversionTracker.tick`): 140 ticks in +/// powder snow start a conversion into a stray that takes 300 more; leaving +/// the snow stops it. `counter` is the affliction time (-1 outside the snow) +/// and `counter2` the conversion time plus one while converting, so that +/// reaching 0 is vanilla's `conversionTime < 0`. +fn skeleton_freezing(m: &mut Mob, cx: &mut Cx) { + if !in_powder_snow(m, cx.w) { + m.extra.counter = -1; + m.extra.counter2 = 0; + } else if m.extra.counter2 > 0 { + m.extra.counter2 -= 1; + if m.extra.counter2 == 0 { + // levelEvent 1048: the conversion sound at the stray. + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + cx.events.push(MobEvent::Sound( + "entity.skeleton.converted_to_stray", + m.center(), + 2.0, + pitch, + )); + cx.events.push(MobEvent::SpawnKind { + kind: "minecraft:stray".into(), + at: [m.position.x, m.position.y, m.position.z], + setup: super::SpawnSetup { + yaw: m.yaw, + persistent: m.persistent, + ..Default::default() + }, + }); + m.removed = true; + } + } else { + m.extra.counter += 1; + if m.extra.counter >= 140 { + m.extra.counter2 = 301; + } + } +} pub fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { if m.species() == Species::ZombieVillager { super::zombie_villager::step(m, cx); } + if m.species() == Species::Skeleton && m.alive() && !m.no_ai { + skeleton_freezing(m, cx); + } if m.species() == Species::ZombifiedPiglin { return zombified_piglin_step(m, cx); } From 9142f57bc8567b29594c3c48a9d9effae845e771 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:33:52 +0100 Subject: [PATCH 165/221] Add the spectator menu with Teleport to Player and Teleport to Team Member --- crates/horizon-client/src/game.rs | 29 +- crates/horizon-client/src/game/lan_actions.rs | 52 ++- crates/horizon-client/src/game/spectator.rs | 112 +++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/spectator_menu.rs | 419 ++++++++++++++++++ crates/horizon-client/src/tab_list.rs | 15 +- crates/horizon-protocol/src/packets/play.rs | 2 + 7 files changed, 624 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-client/src/game/spectator.rs create mode 100644 crates/horizon-client/src/spectator_menu.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..5356352c5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -165,6 +165,7 @@ mod shield; mod sign_edit; mod sniffers; mod spawner; +mod spectator; mod spill; mod startup_menu; mod station_control; @@ -1344,6 +1345,8 @@ struct Game<'a> { /// The shader pack's entity and block entity ids, while one draws entities. pack_ids: Option, started: Instant, + /// `SpectatorGui`: the menu a spectator opens with the hotbar keys. + spectator_gui: horizon_client::spectator_menu::SpectatorGui, previous: Instant, /// FramerateLimitTracker.latestInputTime. last_input: Instant, @@ -5404,7 +5407,9 @@ impl Game<'_> { let draws = hud_layout::crosshair(wi, hi, attack, full); hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } - if !spectator { + if spectator { + self.draw_spectator_hotbar(&mut batch); + } else { let inputs = hud_layout::HotbarInputs { selected: self.selected as i32, right_handed: !self.settings.main_hand_left, @@ -11471,7 +11476,7 @@ impl Game<'_> { | KeyCode::Digit9 if self.screen == Screen::Playing => { - self.selected = match key { + let slot = match key { KeyCode::Digit1 => 0, KeyCode::Digit2 => 1, KeyCode::Digit3 => 2, @@ -11482,6 +11487,13 @@ impl Game<'_> { KeyCode::Digit8 => 7, _ => 8, }; + // Minecraft.handleKeybinds: a spectator's number keys drive + // the spectator menu, not the hotbar. + if self.spectator() { + self.spectator_hotbar_key(slot as i32); + } else { + self.selected = slot; + } } _ => {} } @@ -11496,6 +11508,14 @@ impl Game<'_> { if self.sleeping.is_some() { return Ok(()); } + // key.spectatorHotbar (the middle button) opens the spectator menu + // and uses its selected item. + if button == MouseButton::Middle && self.spectator() { + if pressed { + self.spectator_action_key(); + } + return Ok(()); + } if self.remote.is_some() { return self.remote_mouse(button, pressed); } @@ -12014,7 +12034,9 @@ impl ApplicationHandler for Game<'_> { self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) { - if self.spectator() { + if self.spectator() && self.spectator_gui.is_menu_active() { + self.spectator_scroll(-wheel); + } else if self.spectator() { if let Some(player) = &mut self.player { player.flying_speed = horizon_client::mouse::spectator_flying_speed( player.flying_speed, @@ -12880,6 +12902,7 @@ impl<'a> Game<'a> { pack_ids: None, health_hud: hud_layout::HealthHud::default(), started: now, + spectator_gui: Default::default(), previous: now, last_input: now, pad: Default::default(), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..014b0d400 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -5,7 +5,9 @@ //! blocks, attacking and the commands all behave exactly as they do for the //! host, and every world change they cause reaches all players through the //! block log, the level events and the entity tracker. -use super::{Game, GuestUse, Hit, Mining, Screen, lan::LanHost, respawn_anchor::RespawnConfig}; +use super::{ + Dim, Game, GuestUse, Hit, Mining, Screen, lan::LanHost, respawn_anchor::RespawnConfig, +}; use horizon_client::{ command::vanilla, containers::BlockEntity, @@ -1324,6 +1326,9 @@ impl Game<'_> { } self.sync_rules(); } + // handleTeleportToEntityPacket: a spectator goes to the player, + // in whichever level they are. + S::TeleportToEntity(p) if spectator => self.guest_spectate_teleport(host, gi, p.uuid), S::ChangeGameMode(p) if host.hub.guests[gi].permission >= 2 => { if let Some(mode) = usize::try_from(p.mode) .ok() @@ -1402,6 +1407,51 @@ impl Game<'_> { /// and `Player.remove`'s `inventoryMenu.removed` drops what the cursor /// held (`dropOrPlaceInInventory` for a removed player). Respawning /// sooner removes it too. + /// `ServerGamePacketListenerImpl.handleTeleportToEntityPacket` for a + /// player: the host's own, or a guest in the world. + fn guest_spectate_teleport(&mut self, host: &mut LanHost, gi: usize, uuid: u128) { + let own = host.hub.guests[gi].conn; + let host_player = self + .player + .as_ref() + .filter(|_| self.options.dedicated.is_none() && uuid == host.host_uuid) + .map(|p| { + ( + [p.position.x, p.position.y, p.position.z], + self.yaw, + self.pitch, + self.dim, + ) + }); + let target = host_player.or_else(|| { + host.hub + .guests + .iter() + .find(|g| g.placed && g.conn != own && g.uuid == uuid) + .map(|g| (g.position, g.yaw, g.pitch, Dim::from_id(&g.dimension))) + }); + let Some((at, yaw, pitch, dim)) = target else { + return; + }; + if Dim::from_id(&host.hub.guests[gi].dimension) != dim { + // Only a dedicated server keeps its players in different levels. + if self.options.dedicated.is_some() { + self.level_teleports + .push(super::server_travel::LevelTeleport { + conn: own, + dim, + at, + rotation: Some([yaw, pitch]), + }); + } + return; + } + let g = &mut host.hub.guests[gi]; + (g.yaw, g.pitch) = (yaw, pitch); + // A new body there: no fall distance or motion carried over. + g.motion = None; + host.hub.teleport(gi, Some(at)); + } fn guest_tick_death(&mut self, host: &mut LanHost, gi: usize) { let g = &mut host.hub.guests[gi]; g.death_time += 1; diff --git a/crates/horizon-client/src/game/spectator.rs b/crates/horizon-client/src/game/spectator.rs new file mode 100644 index 000000000..98f2f3269 --- /dev/null +++ b/crates/horizon-client/src/game/spectator.rs @@ -0,0 +1,112 @@ +//! The spectator menu (`SpectatorGui`): its players and teams from the +//! server's player list and teams, and the teleport request. +use super::Game; +use horizon_client::{ + hud::HudBatch, + hud_layout, keybinds, + scoreboard::{comp_text, team_color_rgb}, + spectator_menu::{Member, Outcome, SpectatorMenu, Team}, + tab_list::{SPECTATOR, TabPlayer}, + text::Text, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +impl Game<'_> { + /// `Util.getMillis` for the menu's fade. + fn spectator_now(&self) -> i64 { + self.started.elapsed().as_millis() as i64 + } + /// `new SpectatorMenu`: the listed players, and the teams with a player + /// to go to (`TeleportToTeamMenuCategory.createTeamEntries`). + fn new_spectator_menu(&mut self) -> SpectatorMenu { + let tab: Vec = self + .remote_tab_players() + .map_or_else(Vec::new, |(players, _, _)| players); + let member = |p: &TabPlayer| Member { + uuid: p.uuid, + name: p.name.clone(), + skin: p.skin.clone(), + enabled: p.game_mode != SPECTATOR, + }; + let players: Vec = tab.iter().map(member).collect(); + let teams = self + .score + .board + .teams + .iter() + .filter_map(|team| { + let members: Vec = team + .players + .iter() + .filter_map(|name| tab.iter().find(|p| &p.name == name)) + .filter(|p| p.game_mode != SPECTATOR) + .map(member) + .collect(); + if members.is_empty() { + return None; + } + // A random member's face is the team's icon. + let pick = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.subsec_nanos() as usize) + % members.len(); + Some(Team { + name: comp_text(&team.display_name), + color: team.color.as_deref().and_then(team_color_rgb), + icon: members[pick].skin.clone(), + players: members, + }) + }) + .collect(); + SpectatorMenu::new(players, teams) + } + fn spectator_outcome(&mut self, outcome: Outcome) { + if let Outcome::Teleport(uuid) = outcome { + // PlayerMenuItem.selectItem. + self.send(S::TeleportToEntity(play::TeleportToEntity { uuid })); + } + } + /// A hotbar key as a spectator (`SpectatorGui.onHotbarSelected`). + pub(super) fn spectator_hotbar_key(&mut self, slot: i32) { + let now = self.spectator_now(); + let menu = self.spectator_menu_if_needed(); + let outcome = self.spectator_gui.on_hotbar_selected(slot, now, menu); + self.spectator_outcome(outcome); + } + /// `key.spectatorHotbar`: opens the menu, or uses the selected item. + pub(super) fn spectator_action_key(&mut self) { + let now = self.spectator_now(); + let menu = self.spectator_menu_if_needed(); + let outcome = self.spectator_gui.on_action_key(now, menu); + self.spectator_outcome(outcome); + } + /// The menu a press would open, built only when none is up. + fn spectator_menu_if_needed(&mut self) -> Option { + (!self.spectator_gui.is_menu_active()).then(|| self.new_spectator_menu()) + } + /// `MouseHandler.onScroll` in spectator mode with the menu up. + pub(super) fn spectator_scroll(&mut self, wheel: i32) { + let now = self.spectator_now(); + self.spectator_gui.on_mouse_scrolled(wheel, now); + } + /// `Hud.extractHotbar` for a spectator, and `extractAction`'s prompt. + pub(super) fn draw_spectator_hotbar(&mut self, batch: &mut HudBatch) { + let (w, h) = (batch.width as i32, batch.height as i32); + let now = self.spectator_now(); + let labels: Vec = (1..=9) + .map(|n| keybinds::display_name(self.settings.keys.get(&format!("key.hotbar.{n}")))) + .collect(); + let font = &self.gui.atlas.font; + let mut draws = self + .spectator_gui + .hotbar(w, h, now, &|slot| labels[slot].clone(), font); + draws.extend(self.spectator_gui.action( + w, + h, + now, + font, + self.settings.text_background(0.0), + )); + hud_layout::paint(batch, &self.gui.atlas, &draws); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index fa5ef1c4d..6593f8361 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -167,6 +167,7 @@ pub mod skins; pub mod sound_engine; pub mod sound_events; pub mod spans; +pub mod spectator_menu; pub mod sprint; pub mod sprites; pub mod stations; diff --git a/crates/horizon-client/src/spectator_menu.rs b/crates/horizon-client/src/spectator_menu.rs new file mode 100644 index 000000000..f15f72163 --- /dev/null +++ b/crates/horizon-client/src/spectator_menu.rs @@ -0,0 +1,419 @@ +//! The spectator menu: `SpectatorGui` (the faded hotbar and the prompt under +//! it) over `SpectatorMenu` with its root page, Teleport to Player and +//! Teleport to Team Member, laid out as [`GuiDraw`] calls. +use crate::{ + font::Font, + hud_layout::{Blend, GuiDraw, argb, color_from_float, fill, white, width}, + hud_overlays::text_with_backdrop, + text::Text, +}; +use std::borrow::Cow; + +/// `SpectatorGui.FADE_OUT_DELAY` and `FADE_OUT_TIME`, in milliseconds. +const FADE_OUT_DELAY: i64 = 5000; +const FADE_OUT_TIME: f32 = 2000.0; + +/// A player of the menu (`PlayerMenuItem`). +#[derive(Clone, Debug, PartialEq)] +pub struct Member { + pub uuid: u128, + pub name: String, + /// Skin texture path, as the tab list draws it. + pub skin: String, + /// `PlayerInfo.getGameMode() != GameType.SPECTATOR`. + pub enabled: bool, +} + +/// A team with players to go to (`TeamSelectionItem`). +#[derive(Clone, Debug, PartialEq)] +pub struct Team { + pub name: Text, + /// The team colour's RGB. + pub color: Option, + pub players: Vec, + /// The skin of the face drawn on the icon. + pub icon: String, +} + +/// A `SpectatorMenuItem`. +#[derive(Clone, Debug, PartialEq)] +pub enum Item { + Empty, + Close, + Scroll { left: bool, enabled: bool }, + TeleportToPlayer { enabled: bool }, + TeleportToTeam { enabled: bool }, + Player(Member), + Team(Team), +} +impl Item { + pub fn enabled(&self) -> bool { + match self { + Item::Empty => false, + Item::Close | Item::Team(_) => true, + Item::Scroll { enabled, .. } + | Item::TeleportToPlayer { enabled } + | Item::TeleportToTeam { enabled } => *enabled, + Item::Player(m) => m.enabled, + } + } + /// `SpectatorMenuItem.getName`. + pub fn name(&self) -> Text { + match self { + Item::Empty => Text::literal(""), + Item::Close => Text::translate("spectatorMenu.close", &[]), + Item::Scroll { left: true, .. } => Text::translate("spectatorMenu.previous_page", &[]), + Item::Scroll { .. } => Text::translate("spectatorMenu.next_page", &[]), + Item::TeleportToPlayer { .. } => Text::translate("spectatorMenu.teleport", &[]), + Item::TeleportToTeam { .. } => Text::translate("spectatorMenu.team_teleport", &[]), + Item::Player(m) => Text::literal(m.name.clone()), + Item::Team(t) => t.name.clone(), + } + } +} + +/// What a selected item asks the game to do. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Outcome { + None, + /// `SpectatorMenu.exit`. + Exit, + /// `ServerboundTeleportToEntityPacket` for this player. + Teleport(u128), +} + +enum Category { + Root, + Players, + Teams, + TeamPlayers(Vec), +} + +/// `TeleportToPlayerMenuCategory`: players that are not spectators, ordered +/// by `UUID.compareTo` (signed halves). +pub fn players_page(mut players: Vec) -> Vec { + players.retain(|m| m.enabled); + players.sort_by_key(|m| ((m.uuid >> 64) as i64, m.uuid as i64)); + players +} + +/// `SpectatorMenu`: the page, the selected slot and the page of its items. +pub struct SpectatorMenu { + players: Vec, + teams: Vec, + category: Category, + selected: i32, + page: i32, +} +impl SpectatorMenu { + /// `new SpectatorMenu`: the root page, whose categories take the players + /// and teams as they are now. + pub fn new(players: Vec, teams: Vec) -> Self { + Self { + players: players_page(players), + teams, + category: Category::Root, + selected: -1, + page: 0, + } + } + /// `SpectatorMenuCategory.getItems`. + fn category_items(&self) -> Vec { + match &self.category { + Category::Root => vec![ + Item::TeleportToPlayer { + enabled: !self.players.is_empty(), + }, + Item::TeleportToTeam { + enabled: !self.teams.is_empty(), + }, + ], + Category::Players => self.players.iter().cloned().map(Item::Player).collect(), + Category::Teams => self.teams.iter().cloned().map(Item::Team).collect(), + Category::TeamPlayers(list) => list.iter().cloned().map(Item::Player).collect(), + } + } + /// `SpectatorMenuCategory.getPrompt`. + fn prompt(&self) -> Text { + Text::translate( + match self.category { + Category::Root => "spectatorMenu.root.prompt", + Category::Teams => "spectatorMenu.team_teleport.prompt", + _ => "spectatorMenu.teleport.prompt", + }, + &[], + ) + } + /// `SpectatorMenu.getItem`: six items a page between the scroll arrows. + pub fn item(&self, slot: i32) -> Item { + let items = self.category_items(); + let index = slot + self.page * 6; + if self.page > 0 && slot == 0 { + Item::Scroll { + left: true, + enabled: true, + } + } else if slot == 7 { + Item::Scroll { + left: false, + enabled: index >= 0 && (index as usize) < items.len(), + } + } else if slot == 8 { + Item::Close + } else if index >= 0 && (index as usize) < items.len() { + items[index as usize].clone() + } else { + Item::Empty + } + } + pub fn selected_slot(&self) -> i32 { + self.selected + } + /// `SpectatorMenu.selectSlot`: a first press selects, a second uses it. + pub fn select_slot(&mut self, slot: i32) -> Outcome { + let item = self.item(slot); + if item == Item::Empty { + return Outcome::None; + } + if self.selected != slot || !item.enabled() { + self.selected = slot; + return Outcome::None; + } + match item { + Item::Close => return Outcome::Exit, + Item::Scroll { left, .. } => self.page += if left { -1 } else { 1 }, + Item::TeleportToPlayer { .. } => self.select_category(Category::Players), + Item::TeleportToTeam { .. } => self.select_category(Category::Teams), + Item::Team(t) => self.select_category(Category::TeamPlayers(players_page(t.players))), + Item::Player(m) => return Outcome::Teleport(m.uuid), + Item::Empty => {} + } + Outcome::None + } + /// `SpectatorMenu.selectCategory`. + fn select_category(&mut self, category: Category) { + self.category = category; + self.selected = -1; + self.page = 0; + } +} + +/// `SpectatorGui`: the menu while it is up and when it was last used. +#[derive(Default)] +pub struct SpectatorGui { + menu: Option, + last_selection: i64, +} +impl SpectatorGui { + pub fn is_menu_active(&self) -> bool { + self.menu.is_some() + } + fn apply(&mut self, outcome: Outcome) -> Outcome { + if outcome == Outcome::Exit { + // onSpectatorMenuClosed. + self.menu = None; + self.last_selection = 0; + } + outcome + } + /// `SpectatorGui.onHotbarSelected`: a number key. + /// `fresh` is the menu to open when none is up. + pub fn on_hotbar_selected( + &mut self, + slot: i32, + now: i64, + fresh: Option, + ) -> Outcome { + self.last_selection = now; + match &mut self.menu { + Some(menu) => { + let outcome = menu.select_slot(slot); + self.apply(outcome) + } + None => { + self.menu = fresh; + Outcome::None + } + } + } + /// `SpectatorGui.onHotbarActionKeyPressed`: the key that opens the menu + /// and uses the selected item. + pub fn on_action_key(&mut self, now: i64, fresh: Option) -> Outcome { + self.last_selection = now; + match &mut self.menu { + Some(menu) => { + let slot = menu.selected_slot(); + if slot == -1 { + return Outcome::None; + } + let outcome = menu.select_slot(slot); + self.apply(outcome) + } + None => { + self.menu = fresh; + Outcome::None + } + } + } + /// `SpectatorGui.onMouseScrolled`: the next usable slot that way. + pub fn on_mouse_scrolled(&mut self, wheel: i32, now: i64) { + let Some(menu) = &mut self.menu else { + return; + }; + let usable = |menu: &SpectatorMenu, slot: i32| { + let item = menu.item(slot); + item != Item::Empty && item.enabled() + }; + let mut slot = menu.selected_slot() + wheel; + while (0..=8).contains(&slot) && !usable(menu, slot) { + slot += wheel; + } + if (0..=8).contains(&slot) { + menu.select_slot(slot); + self.last_selection = now; + } + } + /// `SpectatorGui.getHotbarAlpha`. + fn alpha(&self, now: i64) -> f32 { + let delta = self.last_selection - now + FADE_OUT_DELAY; + (delta as f32 / FADE_OUT_TIME).clamp(0.0, 1.0) + } + /// `SpectatorGui.extractHotbar`: the page's nine slots; a menu that has + /// faded out exits instead. `key_label` is the hotbar key of a slot. + pub fn hotbar( + &mut self, + w: i32, + h: i32, + now: i64, + key_label: &dyn Fn(usize) -> Text, + font: &Font, + ) -> Vec { + let mut out = Vec::new(); + let alpha = self.alpha(now); + if self.menu.is_some() && alpha <= 0.0 { + self.apply(Outcome::Exit); + } + let Some(menu) = &self.menu else { + return out; + }; + let center = w / 2; + let y = (h as f32 - 22.0 * alpha).floor() as i32; + let color = white(alpha); + out.push(sprite("hud/hotbar", center - 91, y, 182, 22, color)); + if menu.selected_slot() >= 0 { + out.push(sprite( + "hud/hotbar_selection", + center - 91 - 1 + menu.selected_slot() * 20, + y - 1, + 24, + 23, + color, + )); + } + for slot in 0..9 { + let item = menu.item(slot); + if item == Item::Empty { + continue; + } + let x = center - 90 + slot * 20 + 2; + let brightness = if item.enabled() { 1.0 } else { 0.25 }; + icon(&mut out, &item, x, y + 3, brightness, alpha); + if item.enabled() { + let label = key_label(slot as usize); + let lw = width(font, &label); + out.push(GuiDraw::Text { + text: label, + x: x + 19 - 2 - lw, + y: y + 3 + 6 + 3, + color, + shadow: true, + }); + } + } + out + } + /// `SpectatorGui.extractAction`: the selected item's name, or the + /// page's prompt, over the hotbar. + pub fn action(&self, w: i32, h: i32, now: i64, font: &Font, background: u32) -> Vec { + let mut out = Vec::new(); + let alpha = self.alpha(now); + let Some(menu) = &self.menu else { + return out; + }; + if alpha <= 0.0 { + return out; + } + let item = menu.item(menu.selected_slot()); + let action = if item == Item::Empty { + menu.prompt() + } else { + item.name() + }; + let str_width = width(font, &action); + text_with_backdrop( + &mut out, + action, + (w - str_width) / 2, + h - 35, + str_width, + white(alpha), + background, + ); + out + } +} + +fn sprite(name: &'static str, x: i32, y: i32, w: i32, h: i32, color: u32) -> GuiDraw { + GuiDraw::Sprite { + sprite: Cow::Borrowed(name), + x, + y, + w, + h, + region: None, + color, + blend: Blend::Textured, + } +} + +/// `SpectatorMenuItem.extractIcon` at the slot's corner. +fn icon(out: &mut Vec, item: &Item, x: i32, y: i32, brightness: f32, alpha: f32) { + let tint = color_from_float(alpha, brightness, brightness, brightness); + match item { + Item::Empty => {} + Item::Close => out.push(sprite("spectator/close", x, y, 16, 16, tint)), + Item::Scroll { left, .. } => out.push(sprite( + if *left { + "spectator/scroll_left" + } else { + "spectator/scroll_right" + }, + x, + y, + 16, + 16, + tint, + )), + Item::TeleportToPlayer { .. } => { + out.push(sprite("spectator/teleport_to_player", x, y, 16, 16, tint)); + } + Item::TeleportToTeam { .. } => { + out.push(sprite("spectator/teleport_to_team", x, y, 16, 16, tint)); + } + Item::Player(m) => crate::tab_list::face(out, &m.skin, x + 2, y + 2, 12, true, false, tint), + Item::Team(t) => { + if let Some(rgb) = t.color { + // ARGB.scaleRGB. + let c = |s: u32| (((rgb >> s) & 255) as f32 * brightness) as u32; + out.push(fill( + x + 1, + y + 1, + x + 15, + y + 15, + argb(255, c(16), c(8), c(0)), + )); + } + crate::tab_list::face(out, &t.icon, x + 2, y + 2, 12, true, false, tint); + } + } +} diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs index 0374e3fc2..b6d5f3dbd 100644 --- a/crates/horizon-client/src/tab_list.rs +++ b/crates/horizon-client/src/tab_list.rs @@ -96,7 +96,17 @@ fn sprite(name: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw { /// `PlayerFaceExtractor.extractRenderState`: the skin's face, then its hat /// layer, upside down for Dinnerbone and Grumm. -fn face(out: &mut Vec, skin: &str, x: i32, y: i32, size: i32, hat: bool, flip: bool) { +#[allow(clippy::too_many_arguments)] +pub fn face( + out: &mut Vec, + skin: &str, + x: i32, + y: i32, + size: i32, + hat: bool, + flip: bool, + color: u32, +) { let (v, height) = if flip { (16.0, -8) } else { (8.0, 8) }; for u in [8.0, 40.0].into_iter().take(if hat { 2 } else { 1 }) { out.push(GuiDraw::Blit { @@ -109,7 +119,7 @@ fn face(out: &mut Vec, skin: &str, x: i32, y: i32, size: i32, hat: bool uv: [u, v], src: [8, height], tex: [64, 64], - color: WHITE, + color, }); } } @@ -448,6 +458,7 @@ impl TabList { 8, p.show_hat, (i.upside_down)(p.uuid), + WHITE, ); xo += 9; } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 7ab82720d..a39fdb816 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2043,6 +2043,7 @@ impl Codec for TrackedWaypoint { packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float }); packet!(Attack { id: i32 => VarInt }); +packet!(TeleportToEntity { uuid: u128 => Uuid }); packet!( /// GameType ids: 0 survival, 1 creative, 2 adventure, 3 spectator. ChangeGameMode { mode: i32 => VarInt } @@ -2283,6 +2284,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { SetGameRule(SetGameRule) = SET_GAME_RULE, AcceptTeleportation(AcceptTeleportation) = ACCEPT_TELEPORTATION, Attack(Attack) = ATTACK, + TeleportToEntity(TeleportToEntity) = TELEPORT_TO_ENTITY, ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE, Chat(Chat) = CHAT, ChatAck(ChatAck) = CHAT_ACK, From b22c42ea8579785b8bb7539b8e32b1ad1890119b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:34:37 +0100 Subject: [PATCH 166/221] Stop jockey spiders attacking and shove hoglin targets like vanilla --- crates/horizon-client/src/mobs.rs | 3 ++ crates/horizon-client/src/mobs/hostile.rs | 3 +- crates/horizon-client/src/mobs/piglin.rs | 35 +++++++++++++++++++---- 3 files changed, 35 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..325e19c58 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1324,6 +1324,8 @@ pub struct Seen { pub sitting: bool, /// `Entity.isVehicle` or `isPassenger`. pub ridden: bool, + /// `Attributes.KNOCKBACK_RESISTANCE`. + pub knockback_resistance: f64, /// The active effects, without namespace (`slowness`, `poison`...). pub effects: Vec<&'static str>, } @@ -1406,6 +1408,7 @@ impl Mob { ], sitting: m.extra.sitting, ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(), + knockback_resistance: m.attrs.knockback_resistance, effects: m .extra .effects diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index f1c990c48..50d08b147 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -77,7 +77,8 @@ impl Goal for SpiderAttack { self.0.flags() } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { - self.0.can_use(m, cx) + // SpiderAttackGoal.canUse: not while it carries a rider. + self.0.can_use(m, cx) && m.extra.rider.is_none() } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { if mob_brightness(m, cx.w) >= 0.5 && m.random.next_int_bound(100).unwrap_or(1) == 0 { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index b62262bb0..84c23a923 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -466,6 +466,35 @@ fn find_piglin_repellent(m: &Mob, w: &MobWorld) -> Option<[i32; 3]> { || w.prop(p[0], p[1], p[2], "lit") == Some("true")) }) } +/// `HoglinBase.throwTarget`: a shove away and up of the attack knockback less +/// the target's knockback resistance (none at all when that is used up). +fn throw_target(m: &mut Mob, who: Who, cx: &mut Cx) { + let resistance = match who { + Who::Mob(id) => cx.w.seen(id).map_or(0.0, |s| s.knockback_resistance), + Who::Player => 0.0, + }; + let power = m.kind.attack_knockback - resistance; + let Some(t) = cx.w.target_info(who) else { + return; + }; + if power <= 0.0 { + return; + } + let away = Vec3::new( + t.position.x - m.position.x, + 0.0, + t.position.z - m.position.z, + ); + // `yRot` takes the random whole number of degrees as radians, as vanilla does. + let angle = (m.random.next_int_bound(21).unwrap_or(10) - 10) as f32; + let scale = power * f64::from(m.random.next_float() * 0.5 + 0.2); + let push = away.normalize().scale(scale).rotate_y(angle); + let up = power * f64::from(m.random.next_float()) * 0.5; + cx.events.push(MobEvent::Push { + target: who, + velocity: [push.x, up, push.z], + }); +} /// `HoglinBase.hurtAndThrowTarget`. pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { m.extra.anim_ticks = 10; @@ -485,11 +514,7 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { }), } if !m.is_baby() { - // throwTarget: a strong shove up and away. - cx.events.push(MobEvent::Launch { - target: who, - up: 0.5 * f64::from(m.random.next_float()) + 0.3, - }); + throw_target(m, who, cx); } let sound = if m.species() == Species::Zoglin { "entity.zoglin.attack" From e2a48d1c36b04f0349326dee852bad403a88d92b Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:36:00 +0100 Subject: [PATCH 167/221] Implement the spear's use action: charge, stab, knockback, dismount --- crates/horizon-client/src/first_person.rs | 17 + crates/horizon-client/src/game.rs | 34 ++ .../src/game/commands/world_cmds.rs | 3 +- crates/horizon-client/src/game/creatures.rs | 1 + .../src/game/dispense_fixture.rs | 1 + .../src/game/enchant_effects.rs | 6 +- crates/horizon-client/src/game/item_draw.rs | 3 + crates/horizon-client/src/game/lan.rs | 21 +- crates/horizon-client/src/game/lan_actions.rs | 6 + crates/horizon-client/src/game/mace.rs | 24 +- crates/horizon-client/src/game/remote.rs | 12 +- crates/horizon-client/src/game/spear.rs | 330 ++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 10 + crates/horizon-client/src/mobs/anim.rs | 49 ++- crates/horizon-client/src/mobs/creaking.rs | 1 + crates/horizon-client/src/mobs/guardian.rs | 5 +- crates/horizon-client/src/mobs/render.rs | 18 +- crates/horizon-client/src/mobs/sulfur_cube.rs | 1 + crates/horizon-client/src/spear.rs | 351 ++++++++++++++++++ 20 files changed, 878 insertions(+), 16 deletions(-) create mode 100644 crates/horizon-client/src/game/spear.rs create mode 100644 crates/horizon-client/src/spear.rs diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 0735ce2ba..12c97dfa0 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -26,6 +26,13 @@ pub enum ItemPose { Bow { ticks_used: f32, }, + /// A spear being charged (`ItemUseAnimation.SPEAR`): the time held and + /// the ticks since its last hit's feedback. + Spear { + kinetic: crate::spear::Kinetic, + time_held: f32, + ticks_since_hit: f32, + }, Crossbow { ticks_used: Option, charge_duration: f32, @@ -69,6 +76,16 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + // The spear's own place in the hand, without the equip height. + if let ItemPose::Spear { + kinetic, + time_held, + ticks_since_hit, + } = pose + { + return Mat4::from_translation(Vec3::new(invert * 0.56, -0.52, -0.72)) + * crate::spear::first_person_use(&kinetic, ticks_since_hit, time_held, !left); + } if matches!(pose, ItemPose::SpinAttack) { return m * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..da8db2cb7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -165,6 +165,7 @@ mod shield; mod sign_edit; mod sniffers; mod spawner; +mod spear; mod spill; mod startup_menu; mod station_control; @@ -1681,6 +1682,18 @@ struct Game<'a> { lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// Successful crits (attacking guest, hit entity), queued while the hub is taken. lan_critical_hits: Vec<(Option, i32, bool)>, + /// Spear stabs that landed (the stabbing guest), queued while the hub is + /// taken: `broadcastEntityEvent(player, 2)`. + lan_kinetic_hits: Vec>, + /// `LivingEntity.recentKineticEnemies`: when each player (a guest, or the + /// window's own) last stabbed each entity this use. + stabbed: HashMap<(Option, u32), i64>, + /// The movement a guest's client reported this tick + /// (`ServerPlayer.getKnownMovement`), for their turn. + known_movement: Vec3, + /// `LivingEntity.lastKineticHitFeedbackTime` of the entities that felt a + /// spear's hit (`spear::OWN` is this window's player), in game time. + kinetic_feedback: HashMap, /// Global level events for every guest (`ServerLevel.globalLevelEvent`). lan_global_events: Vec<(i32, [i32; 3], i32)>, /// `ContainerOpenersCounter`: how many players (the host and the guests) @@ -3926,6 +3939,7 @@ impl Game<'_> { || self.use_fishing_rod(&stack) || self.use_crossbow(&stack) || self.use_trident(&stack) + || self.use_spear(&stack) || self.boost_firework(&stack) || self.use_empty_map(&stack) || self.use_book(&stack) @@ -4199,6 +4213,12 @@ impl Game<'_> { self.using = Some((slot, ticks + 1)); return; } + // ItemStack.onUseTick: a spear stabs what its speed allows, until released. + if horizon_client::spear::Kinetic::of(&stack.item).is_some() { + self.spear_tick(&stack, ticks); + self.using = Some((slot, ticks + 1)); + return; + } if &*stack.item == "minecraft:spyglass" { // SpyglassItem.USE_DURATION, then finishUsingItem. if ticks + 1 >= 1200 { @@ -9953,7 +9973,17 @@ impl Game<'_> { let ticks_used = owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0); use horizon_client::first_person::ItemPose; + // ItemUseAnimation.SPEAR. + let spear = using + .then(|| horizon_client::spear::Kinetic::of(&stack.item)) + .flatten() + .map(|kinetic| ItemPose::Spear { + kinetic, + time_held: ticks_used, + ticks_since_hit: self.kinetic_hit_ticks(a), + }); let pose = match &*stack.item { + _ if let Some(pose) = spear => pose, "minecraft:bow" if using => ItemPose::Bow { ticks_used }, "minecraft:crossbow" => { let charged = stack.data().is_some_and(|d| !d.charged.is_empty()); @@ -13096,6 +13126,10 @@ impl<'a> Game<'a> { lan_block_events: Vec::new(), lan_entity_events: Vec::new(), lan_critical_hits: Vec::new(), + lan_kinetic_hits: Vec::new(), + stabbed: HashMap::new(), + known_movement: Vec3::ZERO, + kinetic_feedback: HashMap::new(), lan_global_events: Vec::new(), lid_openers: HashMap::new(), lan_acting: None, diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 559d30db4..2e84769ed 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -105,6 +105,7 @@ impl Game<'_> { match ty.trim_start_matches("minecraft:") { "player_attack" => DamageKind::PlayerAttack, "mace_smash" => DamageKind::MaceSmash, + "spear" => DamageKind::Spear, "mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack, "arrow" => DamageKind::Arrow, "thrown" | "trident" | "mob_projectile" => DamageKind::Thrown, @@ -1218,7 +1219,7 @@ impl Game<'_> { /// LivingEntity.stopRiding for a mob: off its vehicle /// (Entity.removePassenger), then to where the vehicle lets it out /// (LivingEntity.dismountVehicle). - fn dismount_mob(&mut self, rider: u32) { + pub(in crate::game) fn dismount_mob(&mut self, rider: u32) { let Some(i) = self.mobs.iter().position(|m| m.id == rider) else { return; }; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..772d1caf4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3683,6 +3683,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) match kind { K::PlayerAttack => "minecraft:player_attack", K::MaceSmash => "minecraft:mace_smash", + K::Spear => "minecraft:spear", K::MobAttack => "minecraft:mob_attack", K::Arrow => "minecraft:arrow", K::Thrown => "minecraft:thrown", diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 33da8b5ce..88e56819a 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -672,6 +672,7 @@ impl Game<'_> { } let source = match source.kind { horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash", + horizon_client::mobs::DamageKind::Spear => "minecraft:spear", _ => "minecraft:player_attack", }; out.push(format!( diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index b24a62520..5f021a43f 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -69,7 +69,7 @@ impl Game<'_> { } /// `getEnchantedDamage - base`: damage bonus of the held weapon against a mob type. pub(super) fn enchant_damage_bonus(&mut self, target: &str) -> f32 { - let Some(held) = self.inventory[self.selected].clone() else { + let Some(held) = self.held().cloned() else { return 0.0; }; let ctx = EffectContext { @@ -102,7 +102,7 @@ impl Game<'_> { /// whether the hit is that knockback attack. pub(super) fn extra_knockback(&mut self, target_kind: &str, scale: f32) -> (f32, bool) { let knockback_attack = scale > 0.9 && self.player.as_ref().is_some_and(|p| p.sprinting); - let enchanted = match self.inventory[self.selected].clone() { + let enchanted = match self.held().cloned() { Some(held) => { let ctx = EffectContext { this: Some(target_kind), @@ -144,7 +144,7 @@ impl Game<'_> { } /// After a successful melee hit: fire aspect and wind burst. pub(super) fn post_attack(&mut self, mob: usize) { - let Some(held) = self.inventory[self.selected].clone() else { + let Some(held) = self.held().cloned() else { return; }; let Some(m) = self.mobs.get(mob) else { return }; diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..9df59281a 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -170,6 +170,9 @@ fn use_duration(components: &Components) -> i32 { let seconds = c["consume_seconds"].as_f64().unwrap_or(1.6); return (seconds * 20.0) as i32; } + if components.get("minecraft:kinetic_weapon").is_some() { + return 72_000; + } let item_model = components .get("minecraft:item_model") .and_then(Value::as_str) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..e2ce34e19 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1330,6 +1330,7 @@ impl Game<'_> { /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { let critical_hits = std::mem::take(&mut self.lan_critical_hits); + let kinetic_hits = std::mem::take(&mut self.lan_kinetic_hits); for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { if kind == 2001 { host.broken @@ -1381,7 +1382,12 @@ impl Game<'_> { // A projectile is the direct entity of its hit: not tracked here. let melee = matches!( source.kind, - K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom + K::PlayerAttack + | K::MaceSmash + | K::Spear + | K::MobAttack + | K::Sting + | K::SonicBoom ); let direct = cause.filter(|_| melee); host.hub.damage_event(m.id as i32, kind, cause, direct, at); @@ -1402,6 +1408,19 @@ impl Game<'_> { seen.insert(m.id, (m.hurt_time, dead, swing)); } host.mob_state.insert(self.dim, seen); + // Level.broadcastEntityEvent(player, 2) of a spear's stab. + for attacker in kinetic_hits { + let hit = match attacker { + None => self + .player + .as_ref() + .map(|p| (host.host_entity, [p.position.x, p.position.y, p.position.z])), + Some(conn) => host.hub.guest(conn).map(|g| (g.entity_id, g.position)), + }; + if let Some((id, at)) = hit { + host.hub.entity_event(id, 2, at); + } + } for (attacker, target, magic) in critical_hits { let Some(attacker) = attacker.map_or(Some(host.host_entity), |conn| { host.hub.guest(conn).map(|g| g.entity_id) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..4aeb25563 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1935,7 +1935,13 @@ impl Game<'_> { let using = play.using.is_some(); let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100; if digging.is_some() || using || delayed { + // ServerPlayer.getKnownMovement: the move their client just sent. + let movement = host.hub.guests[gi] + .moves + .last() + .map_or(Vec3::ZERO, |m| Vec3::new(m.0[0], m.0[1], m.0[2])); self.as_guest(host, conn, |g| { + g.known_movement = movement; g.attack_ticks = g.attack_ticks.saturating_add(1); if let Some((pos, face)) = digging { g.forced_hit = Some(Hit { diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 34c968980..87868d636 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -6,6 +6,7 @@ use super::Game; use horizon_client::{ enchant::EffectContext, + items::ItemStack, mobs::{Damage, Mob, Species}, particles::{ParticleOptions, ParticleType}, }; @@ -100,7 +101,7 @@ impl Game<'_> { /// `LivingEntity.hurtServer` of the mob at `index` by the player's hit: /// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor. pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool { - let held = self.inventory[self.selected].clone(); + let held = self.held().cloned(); let kind = self.mobs[index].kind.id.clone(); let ctx = EffectContext { this: Some(&kind), @@ -109,6 +110,7 @@ impl Game<'_> { is_direct: true, damage_type: Some(match source.kind { horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash", + horizon_client::mobs::DamageKind::Spear => "minecraft:spear", _ => "minecraft:player_attack", }), items: Some(self.res.items()), @@ -138,7 +140,7 @@ impl Game<'_> { /// the post-attack enchantments, then `postHurtEnemy` with the weapon's /// wear. pub(super) fn weapon_hit(&mut self, index: usize) { - let Some(stack) = self.inventory[self.selected].clone() else { + let Some(stack) = self.held().cloned() else { return; }; let weapon = self @@ -158,16 +160,26 @@ impl Game<'_> { if smash && let Some(p) = self.player.as_mut() { p.fall_distance = 0.0; } - // ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack). + self.weapon_wear(&stack); + } + /// `ItemStack.postHurtEnemy`: `hurtAndBreak(weapon.itemDamagePerAttack)` of + /// the weapon in the acting hand. + pub(super) fn weapon_wear(&mut self, stack: &ItemStack) { + let weapon = self + .res + .items() + .get(&stack.item) + .and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage))); if let Some((per_attack, max)) = weapon && max > 0 && !self.creative { - let loss = self.durability_loss(&stack, per_attack); - if let Some(held) = self.inventory[self.selected].as_mut() { + let loss = self.durability_loss(stack, per_attack); + let cell = self.held_mut(); + if let Some(held) = cell.as_mut() { held.damage += loss; if held.damage >= max { - self.inventory[self.selected] = None; + *cell = None; } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..3707b9945 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2123,6 +2123,10 @@ impl Game<'_> { self.remote_firework_explosion(p.id); } self.remote_fangs_event(p.id as u32, p.event); + // LivingEntity.handleEntityEvent 2: a spear's hit felt. + if p.event == 2 { + self.remote_kinetic_hit(p.id); + } // LocalPlayer.setPermissions also refreshes an open World Options screen. if (24..=28).contains(&p.event) && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -4394,6 +4398,8 @@ impl Game<'_> { } // SpyglassItem.use (its sound is the server's). "minecraft:spyglass" => true, + // Item.use: a kinetic weapon starts being used. + id if horizon_client::spear::Kinetic::of(id).is_some() => true, // ShieldItem.use: anything that blocks attacks, off cooldown. _ => { self.raise_shield(self.held_slot()); @@ -4410,7 +4416,8 @@ impl Game<'_> { matches!( &*stack.item, "minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" - ) || self.blocks_attacks(stack).is_some() + ) || horizon_client::spear::Kinetic::of(&stack.item).is_some() + || self.blocks_attacks(stack).is_some() } /// The rest of Minecraft.startUseItem once the main hand's target passed: @@ -5516,7 +5523,8 @@ fn hand_id(hand: Hand) -> i32 { /// server decides; this is the client's guess of whether to go on. fn item_has_use(info: &horizon_client::items::ItemInfo) -> bool { let id = info.id.trim_start_matches("minecraft:"); - info.consumable.is_some() + id.ends_with("_spear") + || info.consumable.is_some() || info.equip_slot.is_some() || info.blocks_attacks.is_some() || horizon_client::items::bucket_contents(&info.id).is_some() diff --git a/crates/horizon-client/src/game/spear.rs b/crates/horizon-client/src/game/spear.rs new file mode 100644 index 000000000..13df3aed9 --- /dev/null +++ b/crates/horizon-client/src/game/spear.rs @@ -0,0 +1,330 @@ +//! Spears (`KineticWeapon`): holding the use button charges the spear, and +//! from `delay_ticks` on every living entity along the view that the +//! player's speed allows is stabbed: the damage grows with the speed +//! relative to the target, the knockback and the dismount need the +//! attacker's own speed, and each condition runs out after its time +//! (`Item.use`, `ItemStack.onUseTick`, `KineticWeapon.damageEntities`, +//! `Player.stabAttack`). The hit's feedback (`onKineticHit`) reaches the +//! players around as entity event 2. +use super::{Game, view_vector}; +use horizon_client::{ + collisions::SceneCollisions, + items::ItemStack, + mobs::Damage, + spear::{HIT_FEEDBACK_TICKS, Kinetic, REACH}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3, traverse_blocks}, + position::BlockPos, +}; + +/// The key of this window's own player in `Game::kinetic_feedback`. +pub(super) const OWN: i32 = i32::MIN; + +impl Game<'_> { + /// `Item.use` of a kinetic weapon: `startUsingItem` with a new + /// `recentKineticEnemies`, and `KineticWeapon.makeSound` at the user. + pub(super) fn use_spear(&mut self, stack: &ItemStack) -> bool { + let Some(kinetic) = Kinetic::of(&stack.item) else { + return false; + }; + if self.using.is_none() { + self.using = Some((self.held_slot(), 0)); + let actor = self.lan_acting; + self.stabbed.retain(|(who, _), _| *who != actor); + if let Some(p) = &self.player { + let at = [p.position.x, p.position.y, p.position.z]; + self.audio.play(kinetic.sound, Some(at), 1.0, 1.0); + } + } + true + } + + /// `ServerPlayer.getKnownMovement` of the acting player: what they moved + /// in the last tick. A guest's comes with their moves. + fn known_player_movement(&self) -> Vec3 { + if self.lan_acting.is_some() { + return self.known_movement; + } + self.player + .as_ref() + .map_or(Vec3::ZERO, |p| p.position.subtract(self.previous_position)) + } + + /// `Entity.getKnownSpeed` of the mob at `index`, per second: its root + /// vehicle's (`KineticWeapon.getMotion`). + fn mob_speed(&self, index: usize) -> Vec3 { + let mut mob = &self.mobs[index]; + while let Some(vehicle) = mob + .extra + .mount + .and_then(|v| self.mobs.iter().find(|m| m.id == v)) + { + mob = vehicle; + } + mob.position.subtract(mob.previous).scale(20.0) + } + + /// `Level.clip` with COLLIDER shapes and no fluids: where the segment + /// first meets a block, if it does (tall grass lets a stab through). + fn clip_collider(&self, from: Vec3, to: Vec3) -> Option { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + traverse_blocks(from, to, 512, |p: BlockPos| { + let state = self.world.block(p.x, p.y, p.z); + if self.res.facts().is_air(state) { + return None; + } + let shape = self + .collision + .collision_shape(&mut scene, state, [p.x, p.y, p.z]) + .ok()?; + shape.clip(from, to, p).map(|hit| hit.location) + }) + .ok() + .flatten() + } + + /// `ProjectileUtil.getHitEntitiesAlong` for the mobs: those whose box the + /// segment `from`..`to` meets, or comes within the margin of with no + /// block between. + fn mobs_along(&self, from: Vec3, to: Vec3, margin: f64) -> Vec { + let grow = Vec3::new(margin, margin, margin); + let mut hits = Vec::new(); + for (i, m) in self.mobs.iter().enumerate() { + // PiercingWeapon.canHitEntity: alive, and not the vehicle ridden. + if !m.alive() || m.removed || self.riding == Some(m.id) { + continue; + } + let bounds: Aabb = m.bounds(); + let hit = bounds.contains(from) + || bounds.clip(from, to).is_some() + || (margin > 0.0 + && bounds.inflate(grow).clip(from, to).is_some_and(|outside| { + let centre = bounds.center(); + let toward = self.clip_collider(outside, centre).unwrap_or(centre); + bounds.clip(outside, toward).is_some() + })); + if hit { + hits.push(i); + } + } + hits + } + + /// `KineticWeapon.damageEntities`: one tick of the spear in use, `ticks` + /// ticks into the use. + pub(super) fn spear_tick(&mut self, stack: &ItemStack, ticks: u32) { + let Some(kinetic) = Kinetic::of(&stack.item) else { + return; + }; + let used = ticks as i32 - kinetic.delay_ticks; + let (Some(eye), Some(feet)) = ( + self.eye_position(), + self.player.as_ref().map(|p| p.position), + ) else { + return; + }; + if used < 0 || self.spectator() { + return; + } + let eye = Vec3::new(eye[0], eye[1], eye[2]); + let look = view_vector(self.yaw, self.pitch); + let look = Vec3::new(look[0], look[1], look[2]); + let movement = self.known_player_movement(); + let attacker_speed = look.dot(movement.scale(20.0)); + // AttackRange.effectiveMinRange and effectiveMaxRange for a player. + let (min, max) = if self.creative { + (REACH.min_creative, REACH.max_creative) + } else { + (REACH.min, REACH.max) + }; + let from = eye.add_vector(look.scale(f64::from(min))); + let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0))); + // A block closer than the minimum reach takes the whole stab. + if let Some(block) = self.clip_collider(eye, to) { + to = block; + if eye.distance_squared(to) < eye.distance_squared(from) { + return; + } + } + let now = self.world.game_time; + let actor = self.lan_acting; + let mut affected = false; + for i in self.mobs_along(from, to, f64::from(REACH.hitbox_margin)) { + let key = (actor, self.mobs[i].id); + let recent = self + .stabbed + .get(&key) + .is_some_and(|&t| now - t < i64::from(kinetic.contact_cooldown_ticks)); + if recent { + continue; + } + self.stabbed.insert(key, now); + let target_speed = look.dot(self.mob_speed(i)); + let relative = (attacker_speed - target_speed).max(0.0); + // An entity factor of 1 for a player. + let dismounts = kinetic.dismount.test(used, attacker_speed, relative, 1.0); + let pushes = kinetic.knockback.test(used, attacker_speed, relative, 1.0); + let damages = kinetic.damage.test(used, attacker_speed, relative, 1.0); + if dismounts || pushes || damages { + // The attack damage attribute's base value (1) and the speed. + let amount = 1.0 + (relative * f64::from(kinetic.damage_multiplier)).floor() as f32; + affected |= self.stab_mob(i, amount, damages, pushes, dismounts); + } + } + if affected { + // Level.broadcastEntityEvent(player, 2), felt by the player too. + if self.audio.capture.is_some() { + self.lan_kinetic_hits.push(actor); + } + let who = actor.map_or(OWN, |conn| conn as i32); + self.kinetic_hit_feedback(who, &kinetic, [feet.x, feet.y, feet.z]); + } + } + + /// `Player.stabAttack` on the mob at `index`: whether it was affected. + fn stab_mob( + &mut self, + index: usize, + base_damage: f32, + deals_damage: bool, + deals_knockback: bool, + dismounts: bool, + ) -> bool { + let kind = format!( + "minecraft:{}", + self.mobs[index].kind.id.trim_start_matches("minecraft:") + ); + let id = self.mobs[index].id; + let Some(p) = self.player.as_ref() else { + return false; + }; + let from = [p.position.x, p.position.y, p.position.z]; + // The enchantments' share, with no attack strength scaling for a + // weapon in use. + let magic_boost = self.enchant_damage_bonus(&kind); + let total = if deals_damage { + base_damage + magic_boost + } else { + 0.0 + }; + let old_health = self.mobs[index].health; + let hurt = deals_damage && self.hurt_by_player(index, total, Damage::spear(from)); + // causeExtraKnockback: a push of 0.4, then the weapon's Knockback. + if deals_knockback { + let (xd, zd) = self.extra_knockback_direction(); + self.mobs[index].knockback(0.4, xd, zd); + let (strength, _) = self.extra_knockback(&kind, 0.0); + self.mobs[index].knockback(f64::from(strength), xd, zd); + } + let dismounted = dismounts && self.mobs[index].extra.mount.is_some(); + if dismounted { + self.dismount_mob(id); + } + if !hurt && !deals_knockback && !dismounted { + return false; + } + let mob = &self.mobs[index]; + let (feet, width, height) = ( + [mob.position.x, mob.position.y, mob.position.z], + mob.kind.width, + mob.kind.height, + ); + // attackVisualEffects: no attack sound, the enchantments' magic crit. + if magic_boost > 0.0 { + self.critical_hit(self.lan_acting, id as i32, feet, width, height, true); + } + self.combat.last_hurt_mob = Some((id, self.world.game_time)); + // itemAttackInteraction: hurtEnemy (statistic, wear), and the + // post-attack enchantments when the target was hurt. + if let Some(stack) = self.held().cloned() { + self.stats.add("used", &stack.item, 1); + if hurt { + self.post_attack(index); + } + self.weapon_wear(&stack); + } + // damageStatsAndHearts. + let actual = old_health - self.mobs[index].health; + self.stats + .custom("damage_dealt", (actual * 10.0).round() as i32); + if actual > 2.0 { + let indicator = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::DamageIndicator, + ); + self.particles.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, + ); + } + if hurt { + self.last_hurt_by_player.insert(id, self.lan_acting); + } + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } + true + } + + /// `LivingEntity.onKineticHit` for `entity`: the hit feels (the spear + /// moves back, `kinetic_hit_ticks`) and sounds, at most once every ten + /// ticks. + pub(super) fn kinetic_hit_feedback(&mut self, entity: i32, kinetic: &Kinetic, at: [f64; 3]) { + let now = self.world.game_time; + if self + .kinetic_feedback + .get(&entity) + .is_none_or(|&t| now - t > HIT_FEEDBACK_TICKS) + { + self.kinetic_feedback.insert(entity, now); + self.audio + .play_unshared(kinetic.hit_sound, Some(at), 1.0, 1.0); + } + } + + /// `getTicksSinceLastKineticHitFeedback` of this window's player. + pub(super) fn kinetic_hit_ticks(&self, partial: f32) -> f32 { + self.kinetic_feedback + .get(&OWN) + .map_or(0.0, |&t| (self.world.game_time - t) as f32 + partial) + } + + /// `LivingEntity.handleEntityEvent(2)` on a server's client: the + /// player `id` (this one, or another) was hit by the spear it uses. + pub(super) fn remote_kinetic_hit(&mut self, id: i32) { + let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id); + let (item, at) = if own { + let item = self + .using + .and_then(|(slot, _)| self.stack_in(slot)) + .map(|s| s.item.clone()); + let at = self.player.as_ref().map(|p| p.position); + (item, at) + } else { + let mob = self + .mobs + .iter() + .find(|m| m.id == id as u32 && m.extra.using_item > 0); + let item = mob.and_then(|m| { + if m.extra.using_off_hand { + m.extra.off_hand.clone() + } else { + m.extra.main_hand.clone() + } + }); + (item, mob.map(|m| m.position)) + }; + if let (Some(kinetic), Some(at)) = (item.as_deref().and_then(Kinetic::of), at) { + self.kinetic_hit_feedback(if own { OWN } else { id }, &kinetic, [at.x, at.y, at.z]); + } + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index fa5ef1c4d..fdbd4ce8d 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -167,6 +167,7 @@ pub mod skins; pub mod sound_engine; pub mod sound_events; pub mod spans; +pub mod spear; pub mod sprint; pub mod sprites; pub mod stations; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..fffcad823 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -507,6 +507,8 @@ pub enum DamageKind { PlayerAttack, /// `mace_smash`: a mace hit after a fall (the player attack tags too). MaceSmash, + /// `spear`: a stab of a spear (the player attack tags too). + Spear, MobAttack, Arrow, Thrown, @@ -567,6 +569,14 @@ impl Damage { from: Some(from), } } + /// `DamageSources.spear`: a player's stab with a spear. + pub fn spear(from: [f64; 3]) -> Self { + Self { + kind: DamageKind::Spear, + attacker: Some(Who::Player), + from: Some(from), + } + } pub fn mob(id: u32, from: [f64; 3]) -> Self { Self { kind: DamageKind::MobAttack, diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index a4c27960e..2eccd31f0 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -244,6 +244,8 @@ pub enum ArmPose { CrossbowCharge, /// Raising a trident to throw it (or to launch with Riptide). ThrowTrident, + /// A spear held out (`HumanoidModel.ArmPose.SPEAR`), at rest or charging. + Spear, } /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { @@ -295,6 +297,10 @@ pub struct Hum { pub swing_right_arm: Option, /// `mainArm` is the left one (`Mob.isLeftHanded`): a mob's swing uses it. pub left_main: bool, + /// The spear each arm (right, left) holds, and how long that arm has + /// been using it (`ticksUsingItem(arm)`, 0 when it is not). + pub spear: [Option; 2], + pub spear_ticks: [f32; 2], } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -313,6 +319,8 @@ impl Hum { using_item: false, swing_right_arm: None, left_main: false, + spear: [None; 2], + spear_ticks: [0.0; 2], } } } @@ -388,6 +396,23 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { } ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right), ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right), + // SpearAnimations.thirdPersonHandUse. + ArmPose::Spear => { + let side = usize::from(!right); + let Some(kinetic) = h.spear[side] else { + return; + }; + let (x, y, z) = crate::spear::third_person_arm( + &kinetic, + h.spear_ticks[side], + right, + (hx, hy), + h.fall_flying || h.swim > 0.0, + ); + p.xrot(arm, x); + p.yrot(arm, y); + p.get(arm)[5] += z; + } } } /// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`). @@ -687,6 +712,14 @@ pub fn setup( ArmPose::Empty }; let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand; + // AvatarRenderer.getArmPose: an arm holding a spear (at rest too). + let spear_in = |hand: &Option>| { + hand.as_deref() + .filter(|_| player) + .and_then(crate::spear::Kinetic::of) + }; + let (main_spear, off_spear) = + (spear_in(&m.extra.main_hand), spear_in(&m.extra.off_hand)); let pose = if player { match m.extra.main_hand.as_deref() { Some(_) if using_main && m.extra.blocking => ArmPose::Block, @@ -698,6 +731,7 @@ pub fn setup( Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => { ArmPose::CrossbowHold } + Some(_) if main_spear.is_some() => ArmPose::Spear, Some(_) => ArmPose::Item, None => ArmPose::Empty, } @@ -705,7 +739,9 @@ pub fn setup( right }; let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() { - if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking { + if off_spear.is_some() { + ArmPose::Spear + } else if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking { ArmPose::Block } else { ArmPose::Item @@ -731,6 +767,17 @@ pub fn setup( h.using_item = m.extra.using_item > 0; h.swing_right_arm = m.extra.swing_right_arm; h.left_main = m.main_arm_left(); + let main_side = usize::from(m.main_arm_left()); + h.spear[main_side] = main_spear; + h.spear[1 - main_side] = off_spear; + if m.extra.using_item > 0 { + let using_side = if m.extra.using_off_hand { + 1 - main_side + } else { + main_side + }; + h.spear_ticks[using_side] = m.extra.using_item as f32 + s.partial; + } humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. diff --git a/crates/horizon-client/src/mobs/creaking.rs b/crates/horizon-client/src/mobs/creaking.rs index fd6248d2b..e32136703 100644 --- a/crates/horizon-client/src/mobs/creaking.rs +++ b/crates/horizon-client/src/mobs/creaking.rs @@ -118,6 +118,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool { source.kind, DamageKind::PlayerAttack | DamageKind::MaceSmash + | DamageKind::Spear | DamageKind::MobAttack | DamageKind::Arrow | DamageKind::Thrown diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 880655361..8f543e2b4 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -294,7 +294,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { && let Some((d, _)) = m.last_damage && matches!( d.kind, - DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack + DamageKind::PlayerAttack + | DamageKind::MaceSmash + | DamageKind::Spear + | DamageKind::MobAttack ) { let from = [m.position.x, m.position.y, m.position.z]; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..7303ea9d2 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1292,7 +1292,23 @@ pub fn held_item_transform( .unwrap_or_else(|| m.kind.model.clone()); let mut poses = Poses::new(&model); anim::setup(m, &s, &mut poses, &data.animations); - hand_base(m, &model, base, &poses, left) + let mut t = hand_base(m, &model, base, &poses, left)?; + // ItemInHandLayer: a spear in use (ArmPose.SPEAR's animateUseItem). + let off_hand = left != m.main_arm_left(); + if m.extra.using_item > 0 + && m.extra.using_off_hand == off_hand + && let Some(kinetic) = (if off_hand { + &m.extra.off_hand + } else { + &m.extra.main_hand + }) + .as_deref() + .and_then(crate::spear::Kinetic::of) + { + let time_held = m.extra.using_item as f32 + s.partial; + t *= crate::spear::third_person_use_item(&kinetic, time_held, s.swing, 0.0, !left); + } + Some(t) } #[cfg(test)] diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index 00b846b86..f479bf076 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -290,6 +290,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool { source.kind, DamageKind::PlayerAttack | DamageKind::MaceSmash + | DamageKind::Spear | DamageKind::MobAttack | DamageKind::Arrow | DamageKind::Thrown diff --git a/crates/horizon-client/src/spear.rs b/crates/horizon-client/src/spear.rs new file mode 100644 index 000000000..ae6d8f80d --- /dev/null +++ b/crates/horizon-client/src/spear.rs @@ -0,0 +1,351 @@ +//! Spears: `KineticWeapon` (what holding the use button does: the speed +//! conditions of a stab, `Item.Properties.spear`'s numbers) and +//! `SpearAnimations` (how the spear is held in first and third person while +//! it charges). +use glam::{Mat4, Vec3}; +use horizon_core::{geometry::trig::Mth, jmath::pow}; +use std::f32::consts::PI; + +/// `KineticWeapon.Condition`. +#[derive(Clone, Copy, Debug)] +pub struct Condition { + pub max_duration_ticks: i32, + pub min_speed: f32, + pub min_relative_speed: f32, +} +impl Condition { + pub fn test( + self, + ticks_used: i32, + attacker_speed: f64, + relative_speed: f64, + entity_factor: f64, + ) -> bool { + ticks_used <= self.max_duration_ticks + && attacker_speed >= f64::from(self.min_speed) * entity_factor + && relative_speed >= f64::from(self.min_relative_speed) * entity_factor + } +} + +/// `KineticWeapon`: a spear's charge. +#[derive(Clone, Copy, Debug)] +pub struct Kinetic { + pub contact_cooldown_ticks: i32, + pub delay_ticks: i32, + pub dismount: Condition, + pub knockback: Condition, + pub damage: Condition, + pub forward_movement: f32, + pub damage_multiplier: f32, + pub sound: &'static str, + pub hit_sound: &'static str, +} + +/// `AttackRange` of a spear: the reach of its stabs. +pub struct Reach { + pub min: f32, + pub max: f32, + pub min_creative: f32, + pub max_creative: f32, + pub hitbox_margin: f32, + pub mob_factor: f32, +} +pub const REACH: Reach = Reach { + min: 2.0, + max: 4.5, + min_creative: 2.0, + max_creative: 6.5, + hitbox_margin: 0.125, + mob_factor: 0.5, +}; + +impl Kinetic { + /// The `kinetic_weapon` of a spear item (`Item.Properties.spear`). + pub fn of(item: &str) -> Option { + // (damage multiplier, delay, dismount time and speed, knockback time + // and speed, damage time and speed): seconds and blocks per second. + let (multiplier, delay, dismount, knockback, damage) = match item { + "minecraft:wooden_spear" => (0.7, 0.75, (5.0, 14.0), (10.0, 5.1), (15.0, 4.6)), + "minecraft:stone_spear" => (0.82, 0.7, (4.5, 13.0), (9.0, 5.1), (13.75, 4.6)), + "minecraft:copper_spear" => (0.82, 0.65, (4.0, 12.0), (8.25, 5.1), (12.5, 4.6)), + "minecraft:iron_spear" => (0.95, 0.6, (2.5, 11.0), (6.75, 5.1), (11.25, 4.6)), + "minecraft:golden_spear" => (0.7, 0.7, (3.5, 13.0), (8.5, 5.1), (13.75, 4.6)), + "minecraft:diamond_spear" => (1.075, 0.5, (3.0, 10.0), (6.5, 5.1), (10.0, 4.6)), + "minecraft:netherite_spear" => (1.2, 0.4, (2.5, 9.0), (5.5, 5.1), (8.75, 4.6)), + _ => return None, + }; + let wood = item == "minecraft:wooden_spear"; + let ticks = |seconds: f32| (seconds * 20.0) as i32; + Some(Self { + contact_cooldown_ticks: 10, + delay_ticks: ticks(delay), + // `Condition.ofAttackerSpeed`, and `ofRelativeSpeed` for the damage. + dismount: Condition { + max_duration_ticks: ticks(dismount.0), + min_speed: dismount.1, + min_relative_speed: 0.0, + }, + knockback: Condition { + max_duration_ticks: ticks(knockback.0), + min_speed: knockback.1, + min_relative_speed: 0.0, + }, + damage: Condition { + max_duration_ticks: ticks(damage.0), + min_speed: 0.0, + min_relative_speed: damage.1, + }, + forward_movement: 0.38, + damage_multiplier: multiplier, + sound: if wood { + "minecraft:item.spear_wood.use" + } else { + "minecraft:item.spear.use" + }, + hit_sound: if wood { + "minecraft:item.spear_wood.hit" + } else { + "minecraft:item.spear.hit" + }, + }) + } +} + +/// `KineticWeapon.HIT_FEEDBACK_TICKS`. +pub const HIT_FEEDBACK_TICKS: i64 = 10; + +/// `Mth.clamp` on floats (a NaN stays one). +fn clamp(v: f32, lo: f32, hi: f32) -> f32 { + if v < lo { lo } else { v.min(hi) } +} +/// `SpearAnimations.progress`. +fn progress(time: f32, start: f32, end: f32) -> f32 { + clamp((time - start) / (end - start), 0.0, 1.0) +} +fn square(x: f32) -> f32 { + x * x +} +fn cube(x: f32) -> f32 { + x * x * x +} +fn p(x: f32, y: f64) -> f64 { + pow(f64::from(x), y) +} + +// `net.minecraft.util.Ease`. +fn in_quad(x: f32) -> f32 { + x * x +} +fn out_quart(x: f32) -> f32 { + 1.0 - square(square(1.0 - x)) +} +fn out_cubic(x: f32) -> f32 { + 1.0 - cube(1.0 - x) +} +fn out_back(x: f32) -> f32 { + 1.0 + 2.70158 * cube(x - 1.0) + 1.70158 * square(x - 1.0) +} +fn in_out_sine(x: f32) -> f32 { + -((PI * x).mcos() - 1.0) / 2.0 +} +fn in_out_expo(x: f32) -> f32 { + if x < 0.5 { + if x == 0.0 { + 0.0 + } else { + (p(2.0, f64::from(20.0 * x - 10.0)) / 2.0) as f32 + } + } else if x == 1.0 { + 1.0 + } else { + ((2.0 - p(2.0, f64::from(-20.0 * x + 10.0))) / 2.0) as f32 + } +} +fn in_out_back(x: f32) -> f32 { + if x < 0.5 { + return 4.0 * x * x * (7.189_819 * x - 2.594_909_4) / 2.0; + } + let dt = 2.0 * x - 2.0; + (dt * dt * (3.594_909_4 * dt + 2.594_909_4) + 2.0) / 2.0 +} +fn in_out_elastic(x: f32) -> f32 { + if x == 0.0 { + return 0.0; + } + if x == 1.0 { + return 1.0; + } + let sin = (f64::from(20.0 * x - 11.125) * f64::from(PI * 4.0 / 9.0)).sin(); + if x < 0.5 { + (-(p(2.0, f64::from(20.0 * x - 10.0)) * sin) / 2.0) as f32 + } else { + (p(2.0, f64::from(-20.0 * x + 10.0)) * sin / 2.0 + 1.0) as f32 + } +} +fn out_circ(x: f32) -> f32 { + f64::from(1.0 - square(x - 1.0)).sqrt() as f32 +} +fn in_circ(x: f32) -> f32 { + (-f64::from(1.0 - x * x).sqrt()) as f32 + 1.0 +} + +/// `SpearAnimations.UseParams`. +struct UseParams { + raise: f32, + raise_start: f32, + raise_middle: f32, + raise_end: f32, + sway: f32, + lower: f32, + raise_back: f32, + sway_intensity: f32, + sway_slow: f32, + sway_fast: f32, +} +impl UseParams { + fn of(k: &Kinetic, time: f32) -> Self { + let finish_raising = k.delay_ticks; + let finish_swaying = k.dismount.max_duration_ticks + finish_raising; + let start_swaying = finish_swaying - 20; + let finish_lowering = k.knockback.max_duration_ticks + finish_raising; + let start_lowering = finish_lowering - 40; + let finish_raising_back = k.damage.max_duration_ticks + finish_raising; + let raise = progress(time, 0.0, finish_raising as f32); + let sway = progress(time, start_swaying as f32, finish_swaying as f32); + let lower = out_cubic(in_out_elastic(progress( + time - 20.0, + start_lowering as f32, + finish_lowering as f32, + ))); + let raise_back = progress( + time, + (finish_raising_back - 5) as f32, + finish_raising_back as f32, + ); + let sway_intensity = 2.0 * out_circ(sway) - 2.0 * in_circ(raise_back); + let degrees = PI / 180.0; + Self { + raise, + raise_start: progress(raise, 0.0, 0.5), + raise_middle: progress(raise, 0.5, 0.8), + raise_end: progress(raise, 0.8, 1.0), + sway, + lower, + raise_back, + sway_intensity, + sway_slow: (time * 19.0 * degrees).msin() * sway_intensity, + sway_fast: (time * 30.0 * degrees).msin() * sway_intensity, + } + } +} + +/// `SpearAnimations.hitFeedbackAmount`. +fn hit_feedback(ticks_since: f32) -> f32 { + 0.4 * (out_quart(progress(ticks_since, 1.0, 3.0)) + - in_out_sine(progress(ticks_since, 3.0, 10.0))) +} + +/// `PoseStack.rotateAround`. +fn rotate_around(rotation: Mat4, about: Vec3) -> Mat4 { + Mat4::from_translation(about) * rotation * Mat4::from_translation(-about) +} + +/// `SpearAnimations.firstPersonUse`, after the hand's own +/// `translate(invert * 0.56, -0.52, -0.72)`. +pub fn first_person_use(k: &Kinetic, ticks_since_hit: f32, time_held: f32, right: bool) -> Mat4 { + let u = UseParams::of(k, time_held); + let invert = if right { 1.0 } else { -1.0 }; + let degrees = |d: f32| d.to_radians(); + let mut m = Mat4::from_translation(Vec3::new( + invert * (u.raise * 0.15 + u.raise_end * -0.05 + u.sway * -0.1 + u.sway_slow * 0.005), + u.raise * -0.075 + u.raise_middle * 0.075 + u.sway_fast * 0.01, + u.raise_start * 0.05 + u.raise_end * -0.05 + u.sway_slow * 0.005, + )); + m *= rotate_around( + Mat4::from_rotation_x(degrees( + -65.0 * in_out_back(u.raise) - 35.0 * u.lower + + 100.0 * u.raise_back + + -0.5 * u.sway_fast, + )), + Vec3::new(0.0, 0.1, 0.0), + ); + // Axis.YN: a turn the other way round. + m *= rotate_around( + Mat4::from_rotation_y(-degrees( + invert * (-90.0 * progress(u.raise, 0.5, 0.55) + 90.0 * u.sway + 2.0 * u.sway_slow), + )), + Vec3::new(invert * 0.15, 0.0, 0.0), + ); + m * Mat4::from_translation(Vec3::new(0.0, -hit_feedback(ticks_since_hit), 0.0)) +} + +/// `SpearAnimations.thirdPersonHandUse`: the angles (x, y and the z added to +/// the arm's own) of the arm holding a spear. `ticks_using` is the time the +/// item has been in use by this arm (0 when it is not). +pub fn third_person_arm( + k: &Kinetic, + ticks_using: f32, + right: bool, + head: (f32, f32), + gliding_or_swimming: bool, +) -> (f32, f32, f32) { + let invert = if right { 1.0 } else { -1.0 }; + let degrees = PI / 180.0; + let mut y = -0.1 * invert + head.1; + let mut x = -PI / 2.0 + head.0 + 0.8; + if gliding_or_swimming { + x -= 0.959_931_1; + } + y = degrees * clamp(180.0 / PI * y, -60.0, 60.0); + x = degrees * clamp(180.0 / PI * x, -120.0, 30.0); + let mut z = 0.0; + if ticks_using > 0.0 { + let u = UseParams::of(k, ticks_using); + y += -invert * u.sway_fast * degrees * u.sway_intensity; + z = -invert * u.sway_slow * degrees * u.sway_intensity * 0.5; + x += degrees + * (-40.0 * u.raise_start + + 30.0 * u.raise_middle + + -20.0 * u.raise_end + + 20.0 * u.lower + + 10.0 * u.raise_back + + 0.6 * u.sway_slow * u.sway_intensity); + } + (x, y, z) +} + +/// `SpearAnimations.thirdPersonUseItem`: the spear's own pose in the hand +/// held for `time_held` ticks, `swing` into the current swing. +pub fn third_person_use_item( + k: &Kinetic, + time_held: f32, + swing: f32, + ticks_since_hit: f32, + right: bool, +) -> Mat4 { + if time_held == 0.0 { + return Mat4::IDENTITY; + } + let attack = in_quad(progress(swing, 0.05, 0.2)); + let retract = in_out_expo(progress(swing, 0.4, 1.0)); + let u = UseParams::of(k, time_held); + let invert = if right { 1.0 } else { -1.0 }; + let raise_modified = 1.0 - out_back(1.0 - u.raise); + let hit = hit_feedback(ticks_since_hit); + let degrees = |d: f32| d.to_radians(); + Mat4::from_translation(Vec3::new( + 0.0, + -hit * 0.4, + -k.forward_movement * (raise_modified - u.raise_back) + hit, + )) * rotate_around( + Mat4::from_rotation_x(-degrees( + 70.0 * (u.raise - u.raise_back) - 40.0 * (attack - retract), + )), + Vec3::new(0.0, -0.031_25, 0.125), + ) * rotate_around( + Mat4::from_rotation_y(degrees( + invert * 90.0 * (u.raise - u.sway + 3.0 * retract + attack), + )), + Vec3::new(0.0, 0.0, 0.125), + ) +} From 713de31f64aa701ce70805219a4cc8fb441266ea Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:36:04 +0100 Subject: [PATCH 168/221] Slow mobs in cobwebs and make magma cubes jump out of lava --- crates/horizon-client/src/mobs/living.rs | 51 ++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index e9cd42798..351524eb6 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -370,7 +370,14 @@ impl Mob { /// Entity.move with block collisions and step-up; updates collision flags /// and fall distance (Entity.checkFallDamage). pub fn do_move(&mut self, w: &MobWorld, events: &mut Vec) { - let wanted = self.velocity; + let mut wanted = self.velocity; + // Entity.move: standing in a cobweb (`WebBlock.entityInside` ends in + // `makeStuckInBlock`) scales the move, stops the mob and ends its fall. + if let Some(stuck) = self.web_multiplier(w) { + self.fall_distance = 0.0; + wanted = Vec3::new(wanted.x * stuck.x, wanted.y * stuck.y, wanted.z * stuck.z); + self.velocity = Vec3::ZERO; + } let step = self.kind.step_height as f32; let mut scene = SceneCollisions { world: w.world, @@ -429,6 +436,35 @@ impl Mob { self.supporting = self.supporting_block(w, moved); self.movement_emission(w, moved, events); } + /// `WebBlock.entityInside`: the speed multiplier of a mob whose box (shrunk + /// by `1.0E-5`, as in `checkInsideBlocks`) touches a cobweb, half as + /// strong with Weaving. Spiders' `makeStuckInBlock` ignores cobwebs and the + /// wither's ignores every block. + fn web_multiplier(&self, w: &MobWorld) -> Option { + use super::Species; + if matches!( + self.species(), + Species::Spider | Species::CaveSpider | Species::Wither + ) { + return None; + } + let b = self.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + let (min, max) = (b.min_position(), b.max_position()); + for x in min.x.floor() as i32..=max.x.floor() as i32 { + for y in min.y.floor() as i32..=max.y.floor() as i32 { + for z in min.z.floor() as i32..=max.z.floor() as i32 { + if &*w.facts.get(w.world.block(x, y, z)).name == "minecraft:cobweb" { + return Some(if self.has_effect("minecraft:weaving") { + Vec3::new(0.5, 0.25, 0.5) + } else { + Vec3::new(0.25, f64::from(0.05_f32), 0.25) + }); + } + } + } + } + None + } /// LivingEntity.checkFallDamage: the fluid state refreshed out of water /// (touching water resets the fall), then Entity.checkFallDamage. fn check_fall_damage(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec) { @@ -846,17 +882,24 @@ impl Mob { self.ai.no_jump_delay = 10; } } else { - self.jump_in_liquid(); + self.jump_in_liquid(true); } } else { - self.jump_in_liquid(); + self.jump_in_liquid(false); } } else { self.ai.no_jump_delay = 0; } } /// Mob.jumpInLiquid: floaters rise 0.04 per tick, others 0.3; bees 0.01. - fn jump_in_liquid(&mut self) { + /// A magma cube in lava rises to `0.22 + size * 0.05` instead + /// (`MagmaCube.jumpInLiquid`). + fn jump_in_liquid(&mut self, lava: bool) { + if lava && self.species() == super::Species::MagmaCube { + self.velocity.y = f64::from(0.22_f32 + self.extra.size as f32 * 0.05); + self.needs_sync = true; + return; + } self.velocity.y += if self.species() == super::Species::Bee { 0.01 } else if self.ai.nav.can_float { From cece5aca30e032ffb68897297bc2533459d99073 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:36:13 +0100 Subject: [PATCH 169/221] Send more mob state to the single player window A client of a server only draws what the server sends. Send and read the synched data for sleeping villagers (pose and bed), horses grazing and rearing, invisible mobs, a carried enderman block, swimming drowned, zombie villager cures, the villager head shake, zombie drowning conversion, hoglin and piglin conversion, charged blazes, turtle eggs, baby zoglins and the wither's side head targets. A wither's side heads also need a line of sight to shoot, as in vanilla. --- crates/horizon-client/src/game.rs | 4 +- crates/horizon-client/src/game/lan.rs | 108 ++++++++++++++++-- crates/horizon-client/src/game/remote.rs | 46 ++++++++ .../src/game/remote_mob_data.rs | 68 ++++++++++- crates/horizon-client/src/mobs/ai.rs | 3 + crates/horizon-client/src/mobs/anim.rs | 23 ++++ crates/horizon-client/src/mobs/equine.rs | 21 ++++ crates/horizon-client/src/mobs/illusioner.rs | 9 ++ crates/horizon-client/src/mobs/piglin.rs | 7 ++ crates/horizon-client/src/mobs/render.rs | 11 ++ crates/horizon-client/src/mobs/sync.rs | 11 +- crates/horizon-client/src/mobs/undead.rs | 11 ++ crates/horizon-client/src/mobs/wither.rs | 34 ++++-- .../src/mobs/zombie_villager.rs | 8 ++ 14 files changed, 346 insertions(+), 18 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7596ee871..d53aab8e2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7132,7 +7132,9 @@ impl Game<'_> { self.yaw }; for m in &self.mobs { - if m.fire_ticks > 0 && !m.removed { + // Blaze.isOnFire: a charged blaze burns. + let blazing = m.species() == horizon_client::mobs::Species::Blaze && m.extra.flag; + if (m.fire_ticks > 0 || blazing) && !m.removed { let at = m.previous.lerp(m.position, alpha); horizon_client::fire_render::flames( [at.x, at.y, at.z], diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 6e00df8fe..96b7c1ae7 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -14,7 +14,7 @@ use horizon_client::{ hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, - mobs::{Mob, Who, leash::Holder}, + mobs::{Mob, Species, Who, leash::Holder}, text::Text, }; use horizon_core::geometry::Vec3; @@ -140,6 +140,7 @@ pub(super) fn baby_index(kind: &str) -> Option { | "minecraft:zombie_villager" | "minecraft:zombified_piglin" | "minecraft:hoglin" + | "minecraft:zoglin" | "minecraft:goat" | "minecraft:ocelot" | "minecraft:turtle" @@ -166,8 +167,13 @@ fn mob_meta( defaults: &mut Vec<(u8, i32, Value)>, ) { let kind = m.kind.id.as_str(); - if m.fire_ticks > 0 { - meta.push((0, serializer::BYTE, Value::Byte(1))); + // Entity.DATA_SHARED_FLAGS_ID: on fire 1, swimming 16 (a drowned under + // water, `Drowned.setSwimming`) and invisible 32 (the effect's flag). + let flags = i8::from(m.fire_ticks > 0) + | i8::from(m.species() == Species::Drowned && m.extra.flag) << 4 + | i8::from(m.invisible || horizon_client::mobs::trader::is_invisible(m)) << 5; + if flags != 0 { + meta.push((0, serializer::BYTE, Value::Byte(flags))); } // Entity.DATA_POSE: the pose the species keeps in its own fields (a // pose back at standing goes out by the entity's own default). @@ -175,6 +181,12 @@ fn mob_meta( if pose != 0 { meta.push((6, serializer::POSE, Value::Id(i32::from(pose)))); } + // LivingEntity.DATA_SLEEPING_POS_ID: the bed a sleeping villager lies in. + if horizon_client::mobs::villager::sleeping(m) + && let Some(bed) = m.extra.bed + { + meta.push((14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(Some(bed)))); + } if let Some(name) = &m.custom_name { meta.push(( 2, @@ -288,10 +300,16 @@ fn mob_meta( | "minecraft:skeleton_horse" | "minecraft:zombie_horse" | "minecraft:camel" => { - // AbstractHorse.DATA_ID_FLAGS: tame 2. - if e.tame { - meta.push((18, serializer::BYTE, Value::Byte(2))); + // AbstractHorse.DATA_ID_FLAGS: tame 2, eating 16 (grazing), standing + // 32 (rearing). + let grazes = horizon_client::mobs::equine::grazes(m.species()); + let flags = if e.tame { 2 } else { 0 } + | if grazes && e.flag { 16 } else { 0 } + | if grazes && e.counter > 0 { 32 } else { 0 }; + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags))); } + defaults.push((18, serializer::BYTE, Value::Byte(0))); if kind == "minecraft:horse" { let v = i32::from(e.variant) | i32::from(e.variant2) << 8; if v != 0 { @@ -316,6 +334,15 @@ fn mob_meta( // Villager.DATA_VILLAGER_DATA and ZombieVillager's (after Zombie's three). "minecraft:villager" | "minecraft:zombie_villager" => { use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; + if kind == "minecraft:villager" { + unhappy_counter(m, meta, defaults); + } else { + // ZombieVillager.DATA_CONVERTING_ID: the cure's shaking. + if horizon_client::mobs::zombie_villager::is_converting(m) { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } let villager_type = VILLAGER_TYPES[e.variant as usize % VILLAGER_TYPES.len()]; let profession = PROFESSIONS[e.variant2 as usize % PROFESSIONS.len()]; if let (Some(t), Some(p)) = ( @@ -399,7 +426,7 @@ fn mob_meta( } defaults.push((18, serializer::BYTE, Value::Byte(16))); } - // Enderman.DATA_CARRY_STATE. + // Enderman.DATA_CARRY_STATE (0 for none). "minecraft:enderman" => { if let Some(state) = e.carried { meta.push(( @@ -408,6 +435,60 @@ fn mob_meta( Value::Id(state.0 as i32), )); } + defaults.push((16, serializer::OPTIONAL_BLOCK_STATE, Value::Id(0))); + } + // Zombie.DATA_DROWNED_CONVERSION_ID (after DATA_BABY_ID and + // DATA_SPECIAL_TYPE_ID): the shaking of the conversion under water. + "minecraft:zombie" | "minecraft:husk" => { + if e.counter2 > 0 { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + } + // AbstractVillager.DATA_UNHAPPY_COUNTER (after AgeableMob's two). + "minecraft:wandering_trader" => unhappy_counter(m, meta, defaults), + // Hoglin.DATA_IMMUNE_TO_ZOMBIFICATION (after AgeableMob's two) and + // AbstractPiglin's, the first entry of its subclasses: with the + // dimension it makes them shake. + "minecraft:hoglin" | "minecraft:piglin" | "minecraft:piglin_brute" => { + let index = if kind == "minecraft:hoglin" { 18 } else { 16 }; + if e.flag2 { + meta.push((index, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((index, serializer::BOOLEAN, Value::Bool(false))); + } + // Blaze.DATA_FLAGS_ID: charged 1, which makes it burn. + "minecraft:blaze" => { + if e.flag { + meta.push((16, serializer::BYTE, Value::Byte(1))); + } + defaults.push((16, serializer::BYTE, Value::Byte(0))); + } + // Turtle.HAS_EGG and LAYING_EGG (after AgeableMob's two). + "minecraft:turtle" => { + if e.flag { + meta.push((18, serializer::BOOLEAN, Value::Bool(true))); + } + if e.flag2 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((18, serializer::BOOLEAN, Value::Bool(false))); + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } + // WitherBoss.DATA_TARGET_B and DATA_TARGET_C (after DATA_TARGET_A, the + // main target): the entities the side heads look at, by id. + "minecraft:wither" => { + for (k, index) in [(0, 17), (1, 18)] { + let target = match e.ints[k] { + 0 => None, + -1 => player_entity, + id => Some(id), + }; + if let Some(target) = target { + meta.push((index, serializer::INT, Value::Int(target))); + } + defaults.push((index, serializer::INT, Value::Int(0))); + } } _ => {} } @@ -425,6 +506,19 @@ fn mob_meta( } } +/// AbstractVillager.DATA_UNHAPPY_COUNTER (after AgeableMob's two): the head +/// shake of a villager saying no counts it down from 40. +fn unhappy_counter( + m: &Mob, + meta: &mut Vec<(u8, i32, Value)>, + defaults: &mut Vec<(u8, i32, Value)>, +) { + if m.extra.ints[0] > 0 { + meta.push((18, serializer::INT, Value::Int(m.extra.ints[0]))); + } + defaults.push((18, serializer::INT, Value::Int(0))); +} + /// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, /// off hand, feet, legs, chest, head, body, saddle). fn mob_equipment( diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5994af375..fef1ba398 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3489,6 +3489,34 @@ impl Game<'_> { } } let game_time = self.world.game_time; + // `AbstractPiglin.isConverting`: the dimension is not piglin safe. + let nether = self.dim == super::Dim::Nether; + // What a wither's side heads can look at, by network entity id: the + // mobs and the player (position and eye height). + let wither_targets: Vec<(i32, [f64; 3], f64)> = if self + .mobs + .iter() + .any(|m| m.species() == horizon_client::mobs::Species::Wither) + { + let own = self + .remote + .as_ref() + .zip(self.eye_position()) + .map(|(r, eye)| (r.entity_id, eye, eye[1])); + self.mobs + .iter() + .map(|m| { + ( + m.id as i32, + [m.position.x, m.position.y, m.position.z], + m.eye_y(), + ) + }) + .chain(own) + .collect() + } else { + Vec::new() + }; let Some(r) = self.remote.as_mut() else { return; }; @@ -3596,6 +3624,24 @@ impl Game<'_> { } // The animation states a server computes in its own `ai_step`. horizon_client::mobs::sync::client_tick(m, game_time); + match m.species() { + // WitherBoss.aiStep: the side heads turn toward their targets. + horizon_client::mobs::Species::Wither => { + horizon_client::mobs::wither::client_tick(m, |id| { + wither_targets + .iter() + .find(|t| t.0 == id) + .map(|t| (t.1, t.2)) + }); + } + // Hoglin and piglin `isConverting` outside the Nether. + horizon_client::mobs::Species::Hoglin + | horizon_client::mobs::Species::Piglin + | horizon_client::mobs::Species::PiglinBrute => { + horizon_client::mobs::piglin::client_converting(m, nether); + } + _ => {} + } } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index bd452ba85..7ec09a3b2 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,9 +4,12 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, camel, sniffer, sync, tame}; +use horizon_client::mobs::{ + Mob, Species, Who, bat, camel, equine, illusioner, sniffer, sync, tame, zombie_villager, +}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; +use horizon_world::registry::BlockStateId; /// The values `apply` takes from one SetEntityData packet, by vanilla's entry /// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses). @@ -19,7 +22,21 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // Entity.DATA_SHARED_FLAGS_ID's FLAG_ONFIRE: Entity.isOnFire on a // client, which draws the flames. A client doesn't count the // fire down: the flag goes off when the server's fire is out. - (0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1), + (0, Value::Byte(flags)) => { + m.fire_ticks = i32::from(flags & 1); + // Drowned.setSwimming: the shared flag of swimming. + if species == Species::Drowned { + m.extra.flag = flags & 16 != 0; + } + // The shared flag of invisibility: Entity.isInvisible hides + // the model (an illusioner shows its mirror images). + let invisible = flags & 32 != 0; + if species == Species::Illusioner { + illusioner::set_invisible(m, invisible); + } else if &*m.kind.id != "minecraft:player" { + m.invisible = invisible; + } + } // Entity.DATA_POSE: the pose the species animates by. (6, Value::Id(pose)) => sync::set_pose(m, (*pose).clamp(0, 17) as u8), // LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the @@ -104,6 +121,42 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Camel | Species::CamelHusk, 20, Value::Long(tick)) => { camel::set_synced_pose_tick(m, *tick); } + // AbstractHorse.DATA_ID_FLAGS: eating 16 and standing 32 (the + // graze and the rear), which `sync::client_tick` animates. + (s, 18, Value::Byte(flags)) if equine::grazes(s) => equine::set_flags(m, *flags as u8), + // Enderman.DATA_CARRY_STATE (0 for none): the block it holds. + (Species::Enderman, 16, Value::Id(state)) => { + m.extra.carried = (*state > 0).then_some(BlockStateId(*state as u32)); + } + // Zombie.DATA_DROWNED_CONVERSION_ID (after DATA_BABY_ID and + // DATA_SPECIAL_TYPE_ID): the conversion's shaking. + (Species::Zombie | Species::Husk, 18, Value::Bool(converting)) => { + m.extra.counter2 = i32::from(*converting); + } + // ZombieVillager.DATA_CONVERTING_ID (before its villager data). + (Species::ZombieVillager, 19, Value::Bool(converting)) => { + zombie_villager::set_converting(m, *converting); + } + // AbstractVillager.DATA_UNHAPPY_COUNTER (after AgeableMob's two): + // the head shake of `no`, which the server counts down. + (Species::Villager | Species::WanderingTrader, 18, Value::Int(ticks)) => { + m.extra.ints[0] = *ticks; + } + // Hoglin.DATA_IMMUNE_TO_ZOMBIFICATION (after AgeableMob's two) and + // AbstractPiglin's: `sync`'s conversion shake reads it. + (Species::Hoglin, 18, Value::Bool(immune)) + | (Species::Piglin | Species::PiglinBrute, 16, Value::Bool(immune)) => { + m.extra.flag2 = *immune; + } + // Blaze.DATA_FLAGS_ID: charged 1, which makes it burn. + (Species::Blaze, 16, Value::Byte(flags)) => m.extra.flag = flags & 1 != 0, + // Turtle.HAS_EGG and LAYING_EGG (after AgeableMob's two). + (Species::Turtle, 18, Value::Bool(has_egg)) => m.extra.flag = *has_egg, + (Species::Turtle, 19, Value::Bool(laying)) => m.extra.flag2 = *laying, + // WitherBoss.DATA_TARGET_B and _C (after DATA_TARGET_A): the + // entities the side heads turn toward in `wither::client_tick`. + (Species::Wither, 17, Value::Int(id)) => m.extra.ints[0] = *id, + (Species::Wither, 18, Value::Int(id)) => m.extra.ints[1] = *id, // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, @@ -153,8 +206,19 @@ impl Game<'_> { let Some(r) = &self.remote else { return; }; + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): a villager lies + // in its bed the way the bed faces, or gets up. + let bed = values.iter().find_map(|v| match v { + (14, _, Value::OptPos(bed)) => Some(bed.map_or(0, |b| self.bed_facing(b))), + _ => None, + }); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { apply(m, values, &r.builtin, r.entity_id); + if let Some(code) = bed + && m.species() == Species::Villager + { + m.extra.ints[1] = code; + } } } } diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 258c1ccc7..b2e7a0128 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -448,6 +448,9 @@ pub fn tick_swing(m: &mut Mob) { fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.was_eye_in_water = m.fluids.eye_in_water; m.update_fluids(w, events); + if m.species() == Species::Drowned { + super::undead::drowned_update_swimming(m, w); + } let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds()); if fire > 0.0 { m.ticks_frozen = 0; diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index b81f224ae..122867121 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -501,6 +501,26 @@ fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 { } from + a * diff } +/// `DrownedModel.setupSwimAnimation`: the arms reach up and sway, the legs +/// kick and the head lies straight. +fn drowned_swim(p: &mut Poses, s: &State, amount: f32) { + if amount <= 0.0 { + return; + } + let sway = amount * 0.35 * (0.1 * s.age).msin(); + let kick = amount * 0.55 * (0.1 * s.age).msin(); + let reach = -PI * 4.0 / 5.0; + let (right_x, left_x) = (p.get("right_arm")[3], p.get("left_arm")[3]); + let (right_z, left_z) = (p.get("right_arm")[5], p.get("left_arm")[5]); + p.xrot("right_arm", rot_lerp_rad(amount, right_x, reach) + sway); + p.xrot("left_arm", rot_lerp_rad(amount, left_x, reach) - sway); + p.zrot("right_arm", rot_lerp_rad(amount, right_z, -0.15)); + p.zrot("left_arm", rot_lerp_rad(amount, left_z, 0.15)); + let (left_leg, right_leg) = (p.get("left_leg")[3], p.get("right_leg")[3]); + p.xrot("left_leg", left_leg - kick); + p.xrot("right_leg", right_leg + kick); + p.xrot("head", 0.0); +} /// `HumanoidModel.setupSwimAnimation`: the stroke of both arms over 26 /// walk-animation units, the head down and a slow flutter kick. The left arm /// eases the short way round, the right one linearly, as in vanilla. @@ -657,6 +677,9 @@ pub fn setup( h.crouching = m.extra.crouching; h.passenger = m.extra.passenger; humanoid(p, s, &h); + if m.kind.anim == Anim::Drowned { + drowned_swim(p, s, m.extra.swim.amount(s.partial)); + } if m.kind.anim == Anim::ZombifiedPiglin { super::piglin::ears(p, s); } diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 5bb5faf53..5f0a7d912 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -455,6 +455,11 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.extra.counter > 0 { m.extra.counter -= 1; } + animate(m); +} +/// `AbstractHorse.tick`'s eat, stand and mouth animations, which follow the +/// eating and standing flags (`flag` and `counter > 0`). +pub fn animate(m: &mut Mob) { let (eating, standing) = (m.extra.flag, m.extra.counter > 0); let v = &mut m.anim.v; if standing { @@ -472,6 +477,22 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } v[MOUTH] = (v[MOUTH] - v[MOUTH] * 0.7 - 0.05).max(0.0); } +/// `AbstractHorse.tick` on a client that is not the server: the animations +/// follow the flags of the synched data (`set_flags`). +pub fn client_tick(m: &mut Mob) { + m.anim.vo = m.anim.v; + animate(m); +} +/// `AbstractHorse.DATA_ID_FLAGS` on a client: eating 16 and standing 32. +pub fn set_flags(m: &mut Mob, flags: u8) { + m.extra.flag = flags & 16 != 0; + m.extra.counter = i32::from(flags & 32 != 0); +} +/// Whether `ai_step` above runs this species' grazing and rearing, so that +/// the server's flags 16 and 32 mean eating and standing. +pub fn grazes(s: Species) -> bool { + is_equine(s) && !super::camel::is_camel(s) && !super::llama::is_llama(s) +} /// Body texture and the markings overlay. pub fn texture(m: &Mob) -> String { let baby = if m.is_baby() { "_baby" } else { "" }; diff --git a/crates/horizon-client/src/mobs/illusioner.rs b/crates/horizon-client/src/mobs/illusioner.rs index ec17abad7..b32b15998 100644 --- a/crates/horizon-client/src/mobs/illusioner.rs +++ b/crates/horizon-client/src/mobs/illusioner.rs @@ -146,6 +146,15 @@ impl Goal for Spell { } } +/// `Entity.isInvisible` of an illusioner on a client: the shared flag stands +/// in for the effect the server holds, which draws the mirror images. +pub fn set_invisible(m: &mut Mob, on: bool) { + m.extra.effects.retain(|e| e.0 != INVISIBILITY); + if on { + m.extra.effects.push((INVISIBILITY, i32::MAX, 0)); + } +} + /// The client-side half of `Illusioner.aiStep`: new image offsets when /// hurt and once a minute, with a puff of cloud and a sound. pub fn tick(m: &mut Mob, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/piglin.rs b/crates/horizon-client/src/mobs/piglin.rs index de9ba42dd..d7328cb9c 100644 --- a/crates/horizon-client/src/mobs/piglin.rs +++ b/crates/horizon-client/src/mobs/piglin.rs @@ -294,6 +294,13 @@ fn hoglin_repellent(m: &mut Mob, w: &MobWorld) { m.ai.target = None; } } +/// `Hoglin.isConverting` and `AbstractPiglin.isConverting` on a client: in a +/// dimension that is not piglin safe (`nether` is false), a mob that is not +/// immune (`flag2`) and has AI shakes. `counter2 > 0` draws the shake, as it +/// does on the server while the zombification counts up. +pub fn client_converting(m: &mut Mob, nether: bool) { + m.extra.counter2 = i32::from(!nether && !m.extra.flag2 && !m.no_ai); +} /// Per-tick piglin and hoglin state: admiring, anger, zombification and the /// hoglin attack animation. Returns a conversion when it happens. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..05bf4fd57 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -813,6 +813,17 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 (sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32, ); } + } else if m.species() == Species::Drowned { + // DrownedRenderer.setupRotations: tip toward the look pitch about + // the middle of the box while swimming. + let amount = m.extra.swim.amount(alpha); + if amount > 0.0 { + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + let middle = glam::Vec3::new(0.0, m.height() / 2.0, 0.0); + base *= glam::Mat4::from_translation(middle) + * glam::Mat4::from_rotation_x((amount * (-10.0 - pitch)).to_radians()) + * glam::Mat4::from_translation(-middle); + } } else if m.extra.swim.amount(alpha) > 0.0 { // AvatarRenderer.setupRotations: tip forward with the swim amount, // following the pitch in water, then lie along the swimming box. diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs index d1c5b6609..7f806d5e2 100644 --- a/crates/horizon-client/src/mobs/sync.rs +++ b/crates/horizon-client/src/mobs/sync.rs @@ -15,10 +15,13 @@ //! them in `entity_event`; //! - run its client side animation in `client_tick`, sharing the function //! with the server's `ai_step` where the server computes the same. -use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; +use super::{ + Mob, Species, breeze, camel, equine, illusioner, shulker, sniffer, undead, villager, warden, +}; // `Pose.id` of the poses mobs take. pub const STANDING: u8 = 0; +pub const SLEEPING: u8 = 2; pub const LONG_JUMPING: u8 = 6; pub const SITTING: u8 = 10; pub const ROARING: u8 = 11; @@ -36,6 +39,8 @@ pub fn pose_id(m: &Mob) -> u8 { Species::Warden => warden::pose_id(m), Species::Breeze => breeze::pose_id(m), Species::Camel | Species::CamelHusk if camel::sitting(m) => SITTING, + // LivingEntity.startSleeping: the pose, with the bed in index 14. + Species::Villager if villager::sleeping(m) => SLEEPING, _ => STANDING, } } @@ -60,6 +65,10 @@ pub fn client_tick(m: &mut Mob, game_time: i64) { Species::Breeze => breeze::ai_step(m), Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), Species::Shulker => shulker::client_tick(m), + s if equine::grazes(s) => equine::client_tick(m), + Species::Drowned => undead::drowned_client_tick(m), + // Illusioner.aiStep runs on a client: the mirror images move there. + Species::Illusioner => illusioner::tick(m, &mut Vec::new()), _ => {} } } diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 52efea3c4..926770e11 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -181,6 +181,17 @@ fn drowned_ok_target(m: &Mob, w: &super::MobWorld) -> bool { pub fn drowned_wants_to_swim(m: &Mob, w: &super::MobWorld) -> bool { m.extra.flag2 || m.target_info(w).is_some_and(|t| in_water_at(w, t.position)) } +/// `Drowned.updateSwimming`: swimming under water while it wants to. `flag` +/// holds `isSwimming`, which clients take from the entity's shared flags. +pub fn drowned_update_swimming(m: &mut Mob, w: &super::MobWorld) { + m.extra.flag = + !m.no_ai && m.was_eye_in_water && m.fluids.in_water && drowned_wants_to_swim(m, w); +} +/// A drowned on a client: `LivingEntity.updateSwimAmount` follows the +/// swimming flag (`Drowned.isVisuallySwimming`). +pub fn drowned_client_tick(m: &mut Mob) { + m.extra.swim.tick(m.extra.flag, m.fluids.in_water); +} /// Drowned.DrownedMoveControl pub fn drowned_move_control(m: &mut Mob, w: &super::MobWorld) { let target = m.target_info(w); diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6702686c5..165ba53b5 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -169,13 +169,12 @@ fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> { .map(|s| ([s.position.x, s.position.y, s.position.z], s.eye_y, false)), } } -/// `WitherBoss.aiStep` after `super.aiStep()`: the side heads turn, smoke -/// rises from the heads (the particle offsets are drawn on the server too). -pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { - // Side heads turn toward their targets, else back to the body. +/// The side heads turn toward their targets, else back to the body. `find` +/// gives the position and eye height of the entity a head's target id names. +fn turn_heads(m: &mut Mob, find: impl Fn(i32) -> Option<([f64; 3], f64)>) { for i in 0..2 { - match target_pos(w, m.extra.ints[i]) { - Some((p, eye, _)) => { + match find(m.extra.ints[i]) { + Some((p, eye)) => { let h = head_pos(m, i + 1); let (xd, yd, zd) = (p[0] - h[0], eye - h[1], p[2] - h[2]); let sd = (xd * xd + zd * zd).sqrt(); @@ -187,6 +186,18 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { None => m.anim.v[i] = rotlerp(m.anim.v[i], m.body_yaw, 10.0), } } +} +/// `WitherBoss.aiStep` on a client that is not the server: the side heads +/// turn toward the targets of the synched data (`DATA_TARGET_B` and `_C`, +/// kept in `ints[0]` and `ints[1]` as network entity ids). +pub fn client_tick(m: &mut Mob, find: impl Fn(i32) -> Option<([f64; 3], f64)>) { + m.anim.vo = m.anim.v; + turn_heads(m, find); +} +/// `WitherBoss.aiStep` after `super.aiStep()`: the side heads turn, smoke +/// rises from the heads (the particle offsets are drawn on the server too). +pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + turn_heads(m, |id| target_pos(w, id).map(|(p, eye, _)| (p, eye))); let powered = powered(m); for i in 0..3 { let h = head_pos(m, i); @@ -263,11 +274,20 @@ pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec + <= 900.0 + && m.sees( + w, + if id == -1 { + Who::Player + } else { + Who::Mob(id as u32) + }, + ) => { let at = [p[0], p[1] + (eye - p[1]) * 0.5, p[2]]; shoot(m, i + 1, at, false, events); diff --git a/crates/horizon-client/src/mobs/zombie_villager.rs b/crates/horizon-client/src/mobs/zombie_villager.rs index 51fb33c6d..c5fae726a 100644 --- a/crates/horizon-client/src/mobs/zombie_villager.rs +++ b/crates/horizon-client/src/mobs/zombie_villager.rs @@ -24,6 +24,14 @@ pub struct Cure { pub fn cure(m: &Mob) -> Option<&Cure> { villager::ext(m).and_then(|e| e.cure.as_ref()) } +/// `ZombieVillager.DATA_CONVERTING_ID` on a client: only `is_converting` +/// (the cure's shaking) reads the cure, so its time does not matter. +pub fn set_converting(m: &mut Mob, on: bool) { + villager::ext_mut(m).cure = on.then_some(Cure { + time: 0, + starter: None, + }); +} pub fn is_converting(m: &Mob) -> bool { m.species() == Species::ZombieVillager && cure(m).is_some() } From 28b72d46c593284804f7c9c4883ce95a24052d95 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:36:15 +0100 Subject: [PATCH 170/221] Give turtles vanilla's goals: panic, tempt, go to water, travel and stroll --- crates/horizon-client/src/mobs/ai.rs | 8 +- crates/horizon-client/src/mobs/goals.rs | 18 +- crates/horizon-client/src/mobs/nav.rs | 5 + crates/horizon-client/src/mobs/turtle.rs | 232 ++++++++++++++++++++++- 4 files changed, 253 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 26b94eeac..4f17dc580 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -180,14 +180,13 @@ pub fn register(m: &mut Mob) { Family::Undead => undead::register(m), Family::Hostile => hostile::register(m), Family::Aquatic => aquatic::register(m), + // Turtle.registerGoals has its own list, none of the generic goals. + Family::Generic if m.species() == Species::Turtle => super::turtle::register(m), Family::Generic => { generic(m); if m.species() == Species::Rabbit { super::rabbit::register(m); } - if m.species() == Species::Turtle { - super::turtle::register(m); - } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -1298,6 +1297,9 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { if m.species() == Species::Strider { return super::strider::walk_target_value(m, w, p); } + if m.species() == Species::Turtle { + return super::turtle::walk_target_value(m, w, p, light()); + } // Hoglin.getWalkTargetValue: nowhere near a repellent, crimson nylium best. if m.species() == Species::Hoglin { let near = m.extra.repellent.is_some_and(|r| { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index d0b784166..135a57fb0 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -654,15 +654,24 @@ impl Goal for Float { #[derive(Clone, Debug)] pub struct Panic { pub speed: f64, + /// `TurtlePanicGoal`: always look for water this far away, not only + /// when on fire. + pub water_range: Option, pos: [f64; 3], } impl Panic { pub fn new(speed: f64) -> Self { Self { speed, + water_range: None, pos: [0.0; 3], } } + /// `TurtlePanicGoal`. + pub fn looking_for_water(mut self, range: i32) -> Self { + self.water_range = Some(range); + self + } } pub fn should_panic(m: &Mob) -> bool { m.last_damage @@ -678,18 +687,19 @@ impl Goal for Panic { if !should_panic(m) { return false; } - if m.fire_ticks > 0 { + let range = self.water_range.or((m.fire_ticks > 0).then_some(5)); + if let Some(range) = range { let (bx, by, bz) = ( m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32, ); if cx.w.data.state(cx.w.world.block(bx, by, bz)).top == 0.0 { - // findBlocksInBoxByManhattanDistance(pos, 5, 1) for water. + // findBlocksInBoxByManhattanDistance(pos, range, 1) for water. let mut best: Option<([i32; 3], i32)> = None; for dy in -1i32..=1 { - for dx in -5i32..=5 { - for dz in -5i32..=5 { + for dx in -range..=range { + for dz in -range..=range { let d = dx.abs() + dy.abs() + dz.abs(); if cx.w.fluid(bx + dx, by + dy, bz + dz) == crate::blocks::Fluid::Water && best.is_none_or(|b| d < b.1) diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index 178751ff6..d63035a61 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -580,6 +580,11 @@ impl Mob { if self.species() == super::Species::Bee { return super::bee::stable_destination(w, p); } + if self.species() == super::Species::Turtle + && let Some(stable) = super::turtle::stable_destination(self, w, p) + { + return stable; + } // StriderPathNavigation: lava too. if self.kind.flags.lava_walker && w.block_name(p[0], p[1], p[2]) == "minecraft:lava" { return true; diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs index 98dd5b558..324a84a3a 100644 --- a/crates/horizon-client/src/mobs/turtle.rs +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -1,18 +1,73 @@ //! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her //! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand //! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, -//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +//! `extra.counter` `layEggCounter`, `extra.home` `homePos`, `extra.counter2` +//! `goingHome` and `extra.point` `travelPos`. use super::{ Mob, MobEvent, MobWorld, - goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, + goals::{ + Breed, Cx, Goal, JUMP, LookAtPlayer, MOVE, MoveToBlock, Panic, Stroll, Tempt, goal_clone, + reduced, + }, + nav::NavKind, + path::PathType, }; +use crate::blocks::Fluid; use horizon_core::random::RandomSource; +/// `Turtle.registerGoals`, and the path maluses and navigation `Turtle` and +/// `TurtlePathNavigation` give it. pub fn register(m: &mut Mob) { + m.set_malus(PathType::Water, 0.0); + for t in [ + PathType::DoorIronClosed, + PathType::DoorWoodClosed, + PathType::DoorOpen, + ] { + m.set_malus(t, -1.0); + } + m.ai.nav.kind = NavKind::Amphibious; + let food = m.kind.food.clone(); let g = &mut m.ai.goals; + g.add(0, Panic::new(1.2).looking_for_water(7)); g.add(1, Breed::new(1.0)); g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1))); + g.add(2, Tempt::new(1.1, food, false)); + g.add( + 3, + GoToWater(MoveToBlock { + vertical_start: -1, + ..MoveToBlock::new(1.0, 24, 1) + }), + ); g.add(4, GoHome::default()); + g.add(7, Travel::default()); + g.add(8, LookAtPlayer::new(8.0)); + g.add(9, RandomStroll(Stroll::new(1.0).interval(100))); +} +/// `Turtle.goingHome`. +fn going_home(m: &Mob) -> bool { + m.extra.counter2 != 0 +} +fn set_going_home(m: &mut Mob, on: bool) { + m.extra.counter2 = i32::from(on); +} +/// `Turtle.getWalkTargetValue`; `light` is `getPathfindingCostFromLightLevels`. +pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3], light: f32) -> f32 { + if !going_home(m) && w.fluid(p[0], p[1], p[2]) == Fluid::Water + || is_sand(w, [p[0], p[1] - 1, p[2]]) + { + 10.0 + } else { + light + } +} +/// `TurtlePathNavigation.isStableDestination` while travelling: water only. +/// `None` without a `travelPos`, the amphibious rule then. +pub fn stable_destination(m: &Mob, w: &MobWorld, p: [i32; 3]) -> Option { + m.extra + .point + .map(|_| w.block_name(p[0], p[1], p[2]) == "minecraft:water") } /// `Turtle.hasEgg`. pub fn has_egg(m: &Mob) -> bool { @@ -165,10 +220,14 @@ impl Goal for GoHome { m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0) } } - fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) { + fn start(&mut self, m: &mut Mob, _cx: &mut Cx) { + set_going_home(m, true); self.stuck = false; self.close_to_home_try_ticks = 0; } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + set_going_home(m, false); + } fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { !close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600) } @@ -207,3 +266,170 @@ impl Goal for GoHome { } } } + +/// `Turtle.TurtleGoToWaterGoal`: a turtle on land walks to water within 24 +/// blocks, unless it is going home or carries an egg. +#[derive(Clone, Debug)] +struct GoToWater(MoveToBlock); +impl GoToWater { + fn valid(w: &MobWorld, p: [i32; 3]) -> bool { + w.block_name(p[0], p[1], p[2]) == "minecraft:water" + } +} +impl Goal for GoToWater { + goal_clone!(); + fn flags(&self) -> u8 { + MOVE | JUMP + } + fn name(&self) -> &'static str { + "TurtleGoToWaterGoal" + } + fn every_tick(&self) -> bool { + true + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + let wanted = if m.is_baby() && !m.fluids.in_water { + true + } else { + !going_home(m) && !m.fluids.in_water && !has_egg(m) + }; + if !wanted { + return false; + } + // MoveToBlockGoal.canUse. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } + self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); + self.0.find_nearest(m, cx.w, Self::valid) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !m.fluids.in_water && self.0.try_ticks <= 1200 && Self::valid(cx.w, self.0.block) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx.w); + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + // MoveToBlockGoal.tick, with shouldRecalculatePath every 160 ticks. + let b = self.0.block; + let d = [ + f64::from(b[0]) + 0.5 - m.position.x, + f64::from(b[1] + 1) + 0.5 - m.position.y, + f64::from(b[2]) + 0.5 - m.position.z, + ]; + if d[0] * d[0] + d[1] * d[1] + d[2] * d[2] >= 1.0 { + self.0.reached = false; + self.0.try_ticks += 1; + if self.0.try_ticks % 160 == 0 { + let at = [ + f64::from(b[0]) + 0.5, + f64::from(b[1] + 1), + f64::from(b[2]) + 0.5, + ]; + m.nav_move_to(cx.w, at, self.0.speed); + } + } else { + self.0.reached = true; + self.0.try_ticks -= 1; + } + } +} + +/// `Turtle.TurtleTravelGoal`: a turtle in water swims towards a spot up to +/// 512 blocks away, a leg at a time. +#[derive(Clone, Debug, Default)] +struct Travel { + stuck: bool, +} +impl Goal for Travel { + goal_clone!(); + fn flags(&self) -> u8 { + 0 + } + fn name(&self) -> &'static str { + "TurtleTravelGoal" + } + fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !going_home(m) && !has_egg(m) && m.fluids.in_water + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + let xt = m.random.next_int_bound(1025).unwrap_or(0) - 512; + let mut yt = m.random.next_int_bound(9).unwrap_or(0) - 4; + let zt = m.random.next_int_bound(1025).unwrap_or(0) - 512; + if f64::from(yt) + m.position.y > f64::from(cx.w.sea_level - 1) { + yt = 0; + } + m.extra.point = Some([ + (f64::from(xt) + m.position.x).floor(), + (f64::from(yt) + m.position.y).floor(), + (f64::from(zt) + m.position.z).floor(), + ]); + self.stuck = false; + } + fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { + !m.ai.nav.is_done() && !self.stuck && !going_home(m) && m.extra.in_love <= 0 && !has_egg(m) + } + fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) { + m.extra.point = None; + } + fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { + let Some(travel) = m.extra.point else { + self.stuck = true; + return; + }; + if !m.ai.nav.is_done() { + return; + } + // Vec3.atBottomCenterOf(travelPos). + let to = [travel[0] + 0.5, travel[1], travel[2] + 0.5]; + let tenth = f64::from((std::f64::consts::PI / 10.0) as f32); + let half = f64::from(std::f32::consts::FRAC_PI_2); + let mut next = m + .default_random_pos_towards(cx.w, 16, 3, to, tenth) + .or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, half)); + if let Some(n) = next { + let (xc, zc) = (n[0].floor() as i32, n[2].floor() as i32); + // Level.hasChunksAt(xc - 34, zc - 34, xc + 34, zc + 34). + let loaded = ((xc - 34) >> 4..=(xc + 34) >> 4).all(|chunk_x| { + ((zc - 34) >> 4..=(zc + 34) >> 4) + .all(|chunk_z| cx.w.world.chunks.contains_key(&(chunk_x, chunk_z))) + }); + if !loaded { + next = None; + } + } + match next { + Some(at) => { + m.nav_move_to(cx.w, at, 1.0); + } + None => self.stuck = true, + } + } +} + +/// `Turtle.TurtleRandomStrollGoal`: no stroll in water, going home or with an +/// egg. +#[derive(Clone, Debug)] +struct RandomStroll(Stroll); +impl Goal for RandomStroll { + goal_clone!(); + fn flags(&self) -> u8 { + self.0.flags() + } + fn name(&self) -> &'static str { + "TurtleRandomStrollGoal" + } + fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + !m.fluids.in_water && !going_home(m) && !has_egg(m) && self.0.can_use(m, cx) + } + fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + self.0.can_continue(m, cx) + } + fn start(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.start(m, cx); + } + fn stop(&mut self, m: &mut Mob, cx: &mut Cx) { + self.0.stop(m, cx); + } +} From bca4513187c8697ced3a13d709ae75d74498b5ee Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:37:08 +0100 Subject: [PATCH 171/221] Keep withers out of Peaceful, raiders out of the spawn count, and use local difficulty for skeleton traps --- crates/horizon-client/src/game/lightning.rs | 8 ++++++-- crates/horizon-client/src/game/natural_spawning.rs | 4 +++- crates/horizon-client/src/game/wither.rs | 3 ++- crates/horizon-client/src/mobs/raider.rs | 4 ++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 8a3ac2745..ef3bef611 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -46,8 +46,12 @@ impl Game<'_> { if !self.with_level(|b, level, _| b.is_raining_at(level, p)) { continue; } - // Skeleton trap: effective difficulty / 100 (regional difficulty approximated). - let difficulty = f64::from(self.ui.difficulty) * 0.75; + // Skeleton trap: the local effective difficulty / 100 + // (`getCurrentDifficultyAt(pos)`). + let difficulty = f64::from( + self.local_difficulty([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]) + .effective, + ); let below = &self .res .facts() diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 0035f5082..6a2cbcb70 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -504,7 +504,9 @@ impl<'a> Game<'a> { m.position.z.floor() as i32, ], is_mob: true, - persistent: m.persistent, + // isPersistenceRequired or requiresCustomPersistence + // (a raider in a raid). + persistent: m.persistent || horizon_client::mobs::raider::in_raid(m), }) .collect(); let players = players diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 8084425ca..ed9b97aa9 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -29,7 +29,8 @@ impl Game<'_> { /// After a wither skeleton skull is placed: the T of soul sand (or soul /// soil) under three skulls, upright along X or Z, becomes a wither. pub(super) fn check_wither_spawn(&mut self, placed: [i32; 3]) -> horizon_client::Result<()> { - if !self.is_wither_skull(placed) { + // Nothing is built in Peaceful (`level.getDifficulty() != PEACEFUL`). + if self.ui.difficulty == 0 || !self.is_wither_skull(placed) { return Ok(()); } // Pattern rows top to bottom: "^^^", "###", "~#~" ('~' air). diff --git a/crates/horizon-client/src/mobs/raider.rs b/crates/horizon-client/src/mobs/raider.rs index d2ed62374..011ac2006 100644 --- a/crates/horizon-client/src/mobs/raider.rs +++ b/crates/horizon-client/src/mobs/raider.rs @@ -100,6 +100,10 @@ pub fn state(m: &Mob) -> Option<&State> { pub fn state_mut(m: &mut Mob) -> &mut State { m.extra.raider.get_or_insert_with(Box::default) } +/// `Raider.getCurrentRaid() != null`. +pub fn in_raid(m: &Mob) -> bool { + state(m).is_some_and(|s| s.raid_id.is_some()) +} pub fn has_active_raid(m: &Mob) -> bool { state(m).is_some_and(|s| s.active_raid) } From 2f6d259615028dd45859893d29936db1aa7ec4f5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:38:17 +0100 Subject: [PATCH 172/221] Put books into a chiseled bookshelf and take them out Horizon only kept a chiseled bookshelf's saved data, so using it did nothing. It is now a block entity with six slots and lastInteractedSlot: - ChiseledBookShelfBlock.useItemOn / useWithoutItem: the slot comes from the hit position on the front face (getHitSlot, 3x2). A #bookshelf_books item goes into an empty slot (one book, the insert sounds, the used statistic), a book comes out to the inventory or the ground, with the pickup sounds. The slot_N_occupied states follow (ChiseledBookShelfBlockEntity.updateState) and reach a server's clients with the block update; the client's prediction ends the click the same way. - Hoppers and droppers use its container: books only, one to a slot, and the occupied state and last slot follow what they moved. - The comparator reads lastInteractedSlot from the block entity. --- crates/horizon-client/src/containers.rs | 23 +++ crates/horizon-client/src/game.rs | 13 +- .../src/game/chiseled_bookshelf.rs | 178 ++++++++++++++++++ crates/horizon-client/src/game/machines.rs | 26 ++- crates/horizon-client/src/save.rs | 12 ++ crates/horizon-world/src/level/data.rs | 6 + crates/horizon-world/src/level/interact.rs | 59 ++++++ crates/horizon-world/src/level/mod.rs | 2 +- 8 files changed, 310 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/game/chiseled_bookshelf.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 8ca9af0ad..765c6b343 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -101,6 +101,22 @@ pub enum BlockEntity { /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, + /// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots. + ChiseledBookshelf(Box), +} +/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChiseledBookshelf { + pub items: [Option; 6], + pub last_slot: i32, +} +impl Default for ChiseledBookshelf { + fn default() -> Self { + Self { + items: Default::default(), + last_slot: -1, + } + } } /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). @@ -381,6 +397,9 @@ impl BlockEntity { if name == "minecraft:campfire" || name == "minecraft:soul_campfire" { return Some(Self::Campfire(Box::default())); } + if name == "minecraft:chiseled_bookshelf" { + return Some(Self::ChiseledBookshelf(Box::default())); + } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, @@ -420,6 +439,7 @@ impl BlockEntity { Self::Skull(_) => "minecraft:skull", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", + Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf", } } pub fn contents(&self) -> Vec { @@ -443,6 +463,7 @@ impl BlockEntity { Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), Self::Campfire(c) => c.items.iter().flatten().cloned().collect(), + Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -459,6 +480,7 @@ impl BlockEntity { | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, + Self::ChiseledBookshelf(b) => &b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) @@ -483,6 +505,7 @@ impl BlockEntity { | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, + Self::ChiseledBookshelf(b) => &mut b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 087b15dc7..0435b6043 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -23,6 +23,7 @@ mod campfire; mod campfire_douse; mod cartography; mod chat; +mod chiseled_bookshelf; mod client_ambient; mod clipboard; mod combat; @@ -3822,6 +3823,12 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if let Some(swings) = self.use_chiseled_bookshelf(hit, held.as_ref()) { + if swings { + self.swing_arm(); + } + return Ok(true); + } if self.use_composter(hit.pos, held.as_ref()) { self.swing_arm(); return Ok(true); @@ -5657,7 +5664,8 @@ impl Game<'_> { | BlockEntity::CommandBlock(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5929,7 +5937,8 @@ impl Game<'_> { | BlockEntity::CommandBlock(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { diff --git a/crates/horizon-client/src/game/chiseled_bookshelf.rs b/crates/horizon-client/src/game/chiseled_bookshelf.rs new file mode 100644 index 000000000..5d383b4ea --- /dev/null +++ b/crates/horizon-client/src/game/chiseled_bookshelf.rs @@ -0,0 +1,178 @@ +//! Chiseled bookshelves: `ChiseledBookShelfBlock.useItemOn` / `useWithoutItem` +//! (a book into the slot under the crosshair, or out of it) and +//! `ChiseledBookShelfBlockEntity.updateState`, which also follows the books a +//! hopper or dropper moved (`machines::container_changed`). The slots' books +//! show through the block state's `slot_N_occupied`, which reaches a server's +//! clients with the block update. +use super::{Game, Hit, machines::dir_from_name}; +use horizon_client::{containers::BlockEntity, items::ItemStack, mobs::Who}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::level::{flags, hit_slot}; + +const BLOCK: &str = "minecraft:chiseled_bookshelf"; + +impl Game<'_> { + /// `useItemOn` with `held` in the acting hand, then `useWithoutItem` on + /// the main hand's turn: None when the block passes the click, else + /// whether the use succeeded and the arm swings (a click on an empty slot + /// without a book only consumes it). + pub(super) fn use_chiseled_bookshelf( + &mut self, + hit: &Hit, + held: Option<&ItemStack>, + ) -> Option { + let pos = hit.pos; + let state = self.world.block(pos[0], pos[1], pos[2]); + let info = self + .pack + .assets + .registry + .state(state) + .filter(|s| s.name == BLOCK)?; + let facing = info + .properties + .get("facing") + .and_then(|f| dir_from_name(f))?; + let face = Direction::ALL + .into_iter() + .find(|d| d.normal() == hit.face)?; + let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let slot = hit_slot( + facing, + face, + BlockPos::new(pos[0], pos[1], pos[2]), + at, + 2, + 3, + )?; + let occupied = info + .properties + .get(&format!("slot_{slot}_occupied")) + .map(String::as_str) + == Some("true"); + let book = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*s.item)) + }); + let centre = pos.map(|v| f64::from(v) + 0.5); + if let Some(book) = book + && !occupied + { + // addBook: one book goes in (a creative player keeps theirs). + let book = book.clone(); + self.stats.add("used", &book.item, 1); + let sound = if &*book.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.insert.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.insert" + }; + self.bookshelf_items(pos)?[slot] = Some(ItemStack { + count: 1, + ..book.clone() + }); + self.consume_held(); + self.chiseled_bookshelf_update_state(pos, slot); + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.trigger_block("minecraft:item_used_on_block", pos, &book); + return Some(true); + } + // TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem. + if self.hand != horizon_client::first_person::Hand::Main { + return None; + } + if !occupied { + return Some(false); + } + // removeBook: the book goes to the inventory, or is dropped. + let retrieved = self.bookshelf_items(pos)?[slot].take()?; + self.chiseled_bookshelf_update_state(pos, slot); + let sound = if &*retrieved.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.pickup.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.pickup" + }; + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.give_or_drop(retrieved); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + Some(true) + } + + /// The bookshelf's six slots (made if the block has no block entity yet). + fn bookshelf_items(&mut self, pos: [i32; 3]) -> Option<&mut [Option; 6]> { + let entity = self + .world + .block_entities + .get_or_insert_with((pos[0], pos[1], pos[2]), || { + BlockEntity::ChiseledBookshelf(Box::default()) + }); + match entity { + BlockEntity::ChiseledBookshelf(b) => Some(&mut b.items), + _ => None, + } + } + + /// `ChiseledBookShelfBlockEntity.updateState`: `slot` becomes the last + /// one touched, the block state takes the slots' occupancy + /// (`setBlockAndUpdate`) and `BLOCK_CHANGE` goes out. + fn chiseled_bookshelf_update_state(&mut self, pos: [i32; 3], slot: usize) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get_mut(&key) + else { + return; + }; + b.last_slot = slot as i32; + let occupied: Vec = b.items.iter().map(Option::is_some).collect(); + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .cloned() + else { + return; + }; + for (i, occupied) in occupied.into_iter().enumerate() { + state + .properties + .insert(format!("slot_{i}_occupied"), occupied.to_string()); + } + let Some(new) = registry.id(&state) else { + return; + }; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, new, flags::UPDATE_ALL)); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.post_block_game_event("minecraft:block_change", pos, None, Some(new)); + } + + /// The books a hopper or dropper put in or took out: the slot whose + /// occupancy no longer matches the block state is the one `setItem` or + /// `removeItem` updated. + pub(super) fn chiseled_bookshelf_synced(&mut self, pos: (i32, i32, i32)) { + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get(&pos) else { + return; + }; + let Some(info) = self + .pack + .assets + .registry + .state(self.world.block(pos.0, pos.1, pos.2)) + else { + return; + }; + let moved = (0..6).rev().find(|i| { + let shown = info + .properties + .get(&format!("slot_{i}_occupied")) + .map(String::as_str); + b.items[*i].is_some() != (shown == Some("true")) + }); + if let Some(slot) = moved { + self.chiseled_bookshelf_update_state([pos.0, pos.1, pos.2], slot); + } + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index f398f4511..fe1b64f65 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -41,6 +41,8 @@ enum Kind { Crafter, /// `BrewingStandBlockEntity` (a `WorldlyContainer`). Brewing, + /// `ChiseledBookShelfBlockEntity`: books only, one to a slot. + Bookshelf, /// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder` /// without a block entity): input below 7, empty at 7, bone meal at 8. Composter(i32), @@ -82,7 +84,7 @@ impl View { } } -fn dir_from_name(name: &str) -> Option { +pub(super) fn dir_from_name(name: &str) -> Option { Some(match name { "down" => Direction::Down, "up" => Direction::Up, @@ -169,6 +171,7 @@ impl Containers<'_> { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, (BlockEntity::Brewing(_), _) => Kind::Brewing, + (BlockEntity::ChiseledBookshelf(_), _) => Kind::Bookshelf, (_, "minecraft:hopper") => Kind::Hopper, _ => Kind::Generic, }; @@ -250,6 +253,16 @@ impl Containers<'_> { _ => false, }; } + if view.kind == Kind::Bookshelf { + // ListBackedContainer.canPlaceItem: `acceptsItemType` (the books) + // and a free slot, as `getMaxStackSize` is 1. + return self + .items + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*stack.item)) + && self.get(view, slot).is_none(); + } if view.kind == Kind::Brewing { // BrewingStandBlockEntity.canPlaceItem return match slot { @@ -415,14 +428,14 @@ pub(super) fn shelf_signal( if !chiseled && !info.name.ends_with("_shelf") { return None; } - let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); if chiseled { // The last slot touched, plus one (`lastInteractedSlot` starts at -1). - let last = tag - .as_ref() - .and_then(|t| horizon_client::save::number(t.get("last_interacted_slot"))); - return Some(last.map_or(0, |slot| slot as i32 + 1)); + return Some(match world.block_entities.get(&(pos.x, pos.y, pos.z)) { + Some(BlockEntity::ChiseledBookshelf(b)) => b.last_slot + 1, + _ => 0, + }); } + let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); // Only read from the back: a bit for each of the three slots in use. let facing = info.properties.get("facing").and_then(|f| dir_from_name(f)); if facing.map(Direction::opposite) != Some(direction) { @@ -472,6 +485,7 @@ impl Game<'_> { if pos.1 == super::minecarts::CART_KEY_Y { return; } + self.chiseled_bookshelf_synced(pos); // A double chest's other half changes with it. let halves: Vec = std::iter::once(pos) .chain(self.chest_other_half(pos)) diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dc08d90b0..df2aebc87 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -599,6 +599,11 @@ pub fn encode_block_entity( } } BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), + // ChiseledBookShelfBlockEntity.saveAdditional. + BlockEntity::ChiseledBookshelf(b) => { + entries.push(("Items", encode_items(&b.items))); + entries.push(("last_interacted_slot", Tag::Int(b.last_slot))); + } // CampfireBlockEntity.saveAdditional. BlockEntity::Campfire(c) => { entries.push(("Items", encode_items(&c.items))); @@ -814,6 +819,13 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain } BlockEntity::Sign(sign) => sign.decode(tag), BlockEntity::Sculk(s) => s.load(tag), + // ChiseledBookShelfBlockEntity.loadAdditional. + BlockEntity::ChiseledBookshelf(b) => { + for (slot, item) in decode_items(tag.get("Items"), 6).into_iter().enumerate() { + b.items[slot] = item; + } + b.last_slot = int("last_interacted_slot").unwrap_or(-1); + } // CampfireBlockEntity.loadAdditional: missing time arrays stay zeros. BlockEntity::Campfire(c) => { for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() { diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 4635e8b05..cda834217 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -571,6 +571,12 @@ props! { orientation = "orientation", crafting = "crafting", side_chain = "side_chain", + slot_0_occupied = "slot_0_occupied", + slot_1_occupied = "slot_1_occupied", + slot_2_occupied = "slot_2_occupied", + slot_3_occupied = "slot_3_occupied", + slot_4_occupied = "slot_4_occupied", + slot_5_occupied = "slot_5_occupied", copper_golem_pose = "copper_golem_pose", sculk_sensor_phase = "sculk_sensor_phase", shrieking = "shrieking", diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 831dea544..ccf4c69a2 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -24,6 +24,44 @@ impl InteractionResult { } } +/// `SelectableSlotContainer.getHitSlot`: the slot of a block with `rows` by +/// `columns` slots on its front face (the way it `facing`) that the click at +/// `hit` on `face` of the block at `pos` lands in, if it is the front face. +pub fn hit_slot( + facing: Direction, + face: Direction, + pos: BlockPos, + hit: Vec3, + rows: i32, + columns: i32, +) -> Option { + if facing != face { + return None; + } + // The location relative to the block in front of the face, which only + // moves the axis the face points along: the others are the block's own. + let (dx, dy, dz) = ( + hit.x - f64::from(pos.x), + hit.y - f64::from(pos.y), + hit.z - f64::from(pos.z), + ); + let (x, y) = match face { + Direction::North => ((1.0 - dx) as f32, dy as f32), + Direction::South => (dx as f32, dy as f32), + Direction::West => (dz as f32, dy as f32), + Direction::East => ((1.0 - dz) as f32, dy as f32), + Direction::Down | Direction::Up => return None, + }; + // getSection + let section = |relative: f32, sections: i32| { + let size = 16.0f32 / sections as f32; + ((relative * 16.0f32 / size).floor() as i32).clamp(0, sections - 1) + }; + let row = section(1.0 - y, rows); + let column = section(x, columns); + Some((column + row * columns) as usize) +} + /// The interacting player, as far as block behaviour needs it. #[derive(Clone, Copy, Debug)] pub struct PlayerContext { @@ -326,6 +364,27 @@ impl Sim<'_, L> { Consume } } + Class::ChiseledBookShelf => { + // useItemOn and useWithoutItem agree on what a click takes: no + // slot under it passes, an empty slot consumes it, a book in + // it comes out (the block entity is the game's). + let Some(slot) = hit_slot(b.facing(state), face, pos, hit, 2, 3) else { + return Pass; + }; + let occupied = [ + p.slot_0_occupied, + p.slot_1_occupied, + p.slot_2_occupied, + p.slot_3_occupied, + p.slot_4_occupied, + p.slot_5_occupied, + ]; + if table.bool(state, occupied[slot]) { + Success + } else { + Consume + } + } Class::Bell => { let click_y = hit.y - f64::from(pos.y); let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && { diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 0a8e160cd..39c6bb6f7 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -137,7 +137,7 @@ mod tests; pub use buckets::BucketContent; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; pub use falling::Landing; -pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; +pub use interact::{InteractionResult, PlayerContext, PlayerEffect, hit_slot}; pub use pistons::{BlockEventData, MovingPiston}; pub use place::{PlaceContext, PlaceOutcome}; pub use states::{BlockId, PropKey, StateTable}; From 97d119b4e8995800f9e0e1de497af4c460758760 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:39:31 +0100 Subject: [PATCH 173/221] Loop the bee buzz and the guardian attack hum like vanilla --- crates/horizon-client/src/game.rs | 7 ++ crates/horizon-client/src/game/creatures.rs | 3 + crates/horizon-client/src/game/lan.rs | 5 + crates/horizon-client/src/game/mob_sounds.rs | 82 +++++++++++++ crates/horizon-client/src/game/music.rs | 2 + crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/mobs.rs | 7 ++ crates/horizon-client/src/mobs/guardian.rs | 25 ++-- crates/horizon-client/src/sound_engine.rs | 123 +++++++++++++++++++ 9 files changed, 250 insertions(+), 8 deletions(-) create mode 100644 crates/horizon-client/src/game/mob_sounds.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..8e1de77e4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -103,6 +103,7 @@ mod maps; mod minecarts; mod mob_blocks; mod mob_gear; +mod mob_sounds; mod mod_browser; #[cfg(feature = "mods")] mod mod_browser_recipes; @@ -1379,6 +1380,10 @@ struct Game<'a> { cart_sounds: HashSet, /// The minecart the riding sounds were started for (`LocalPlayer.startRiding`). riding_cart_sounds: Option, + /// Bees whose buzz is playing, and whether it is the aggressive one. + bee_sounds: HashMap, + /// Guardians whose attack hum is playing. + guardian_sounds: HashSet, dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, @@ -12908,6 +12913,8 @@ impl<'a> Game<'a> { sound_paused: false, cart_sounds: HashSet::new(), riding_cart_sounds: None, + bee_sounds: HashMap::new(), + guardian_sounds: HashSet::new(), dropped: Vec::new(), next_entity: 0, particles, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..cf26174c5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -933,6 +933,9 @@ impl Game<'_> { match e { MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), + MobEvent::EntityEvent { mob, event, at } => { + self.lan_entity_event(mob as i32, event, at) + } MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..a29de78e6 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1302,6 +1302,11 @@ impl Game<'_> { if self.audio.capture.is_some() { self.lan_entity_events.push((id, event, at)); } + // Event 21: a window that simulates the world itself is its own + // client, and hears the guardian's hum too. + if event == 21 && self.options.execution_role.is_client() { + self.start_guardian_sound(id as u32); + } } /// `ServerPlayer.crit` (or `magicCrit` when `magic`): this window's /// emitter, and an animation for the attacker's client and observers once diff --git a/crates/horizon-client/src/game/mob_sounds.rs b/crates/horizon-client/src/game/mob_sounds.rs new file mode 100644 index 000000000..50065d94f --- /dev/null +++ b/crates/horizon-client/src/game/mob_sounds.rs @@ -0,0 +1,82 @@ +//! The looping sound instances of mobs: a bee's buzz +//! (`ClientPacketListener.postAddEntitySoundInstance`) and a guardian's +//! attack hum (entity event 21). The sound engine ticks them with what +//! `start_mob_sounds` reads off the mobs. +use super::Game; +use horizon_client::{ + mobs::{Species, bee, guardian}, + sound_engine::{MobSound, SoundEngine, SoundInstance, Sounds}, +}; + +impl Game<'_> { + /// Start the buzz of each bee that has none (or whose anger changed, which + /// swaps the flying loop for the aggressive one and back), forget the mobs + /// that are gone, and read what the instances follow. + pub(super) fn start_mob_sounds(&mut self) -> Vec { + let game_time = self.world.game_time; + let mobs: Vec = self + .mobs + .iter() + .filter(|m| { + !m.removed + && matches!( + m.species(), + Species::Bee | Species::Guardian | Species::ElderGuardian + ) + }) + .map(|m| MobSound { + id: m.id, + position: [m.position.x, m.position.y, m.position.z], + // Vec3.horizontalDistance. + speed: m.velocity.x.hypot(m.velocity.z), + baby: m.is_baby(), + // NeutralMob.isAngry: the anger end time is ahead. + angry: m.species() == Species::Bee + && bee::get(m).is_some_and(|b| b.anger_end > 0 && b.anger_end - game_time > 0), + silent: m.silent, + attack_scale: guardian::attack_scale(m), + }) + .collect(); + self.guardian_sounds + .retain(|id| mobs.iter().any(|m| m.id == *id)); + self.bee_sounds + .retain(|id, _| mobs.iter().any(|m| m.id == *id)); + for sound in &mobs { + let is_bee = self + .mobs + .iter() + .any(|m| m.id == sound.id && m.species() == Species::Bee); + if is_bee && self.bee_sounds.get(&sound.id) != Some(&sound.angry) { + self.bee_sounds.insert(sound.id, sound.angry); + let instance = SoundInstance::bee(sound, sound.angry, SoundEngine::unseeded()); + self.audio.play_instance(instance, false); + } + } + mobs + } + + /// `ClientPacketListener.handleEntityEvent` 21: a guardian's attack + /// hum starts (one loop per guardian; the loops of its earlier beams are + /// the same loop, as each one follows the guardian's charge). + pub(super) fn start_guardian_sound(&mut self, id: u32) { + let Some(m) = self.mobs.iter().find(|m| { + m.id == id && matches!(m.species(), Species::Guardian | Species::ElderGuardian) + }) else { + return; + }; + if !self.guardian_sounds.insert(id) { + return; + } + let sound = MobSound { + id, + position: [m.position.x, m.position.y, m.position.z], + speed: 0.0, + baby: false, + angry: false, + silent: m.silent, + attack_scale: guardian::attack_scale(m), + }; + let instance = SoundInstance::guardian_attack(&sound, SoundEngine::unseeded()); + self.audio.play_instance(instance, false); + } +} diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 97ca3763e..6e303e7d3 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -34,11 +34,13 @@ impl Game<'_> { self.sound_paused = self.pause; } let (vehicle, carts) = self.start_cart_sounds(); + let mobs = self.start_mob_sounds(); let ctx = TickContext { player_underwater: self.ambience.was_underwater(), player_removed: self.player.is_none(), vehicle, carts, + mobs, frozen: !self.clock.runs_normally(), }; self.audio.tick(self.pause, &ctx); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..9c0927d11 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2130,6 +2130,10 @@ impl Game<'_> { self.ui.registries.permission = (p.event - 24) as u8; self.remote_world_options_permission(p.event >= 26); } + // ClientPacketListener.handleEntityEvent 21: a guardian's hum. + if p.event == 21 { + self.start_guardian_sound(p.id as u32); + } if p.event == 1 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Rabbit diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..1cb338bee 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -903,6 +903,13 @@ pub enum MobEvent { mob: u32, at: [f64; 3], }, + /// `Level.broadcastEntityEvent` for a mob: guests run its + /// `handleEntityEvent`. + EntityEvent { + mob: u32, + event: i8, + at: [f64; 3], + }, Sound(&'static str, [f64; 3], f32, f32), /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the /// chest's opener count goes up or down (interaction range 3). diff --git a/crates/horizon-client/src/mobs/guardian.rs b/crates/horizon-client/src/mobs/guardian.rs index 880655361..fdd596b54 100644 --- a/crates/horizon-client/src/mobs/guardian.rs +++ b/crates/horizon-client/src/mobs/guardian.rs @@ -112,14 +112,14 @@ impl Goal for GuardianAttack { if self.attack_time == 0 { m.extra.flag = true; m.extra.counter2 = 0; - // Entity event 21: the attack sound loop starts. - let sound = "entity.guardian.attack"; - cx.events.push(MobEvent::Sound( - sound, - [m.position.x, m.position.y, m.position.z], - 1.0, - 1.0, - )); + // Entity event 21: the attack sound loop starts on the clients. + if !m.silent { + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event: 21, + at: [m.position.x, m.position.y, m.position.z], + }); + } } else if self.attack_time >= attack_duration(m) { // Indirect magic (1, +2 on Hard, +2 for the elder), then // doHurtTarget. @@ -459,3 +459,12 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) { p.yrot("tail1", tail.msin() * PI * 0.1); p.yrot("tail2", tail.msin() * PI * 0.15); } +/// `Guardian.getAttackAnimationScale(0)`: how far the beam has charged. A +/// beam that ended counts from zero again. +pub fn attack_scale(m: &Mob) -> f32 { + if m.extra.flag { + m.extra.counter2 as f32 / attack_duration(m) as f32 + } else { + 0.0 + } +} diff --git a/crates/horizon-client/src/sound_engine.rs b/crates/horizon-client/src/sound_engine.rs index 562b14100..f3e2dd75d 100644 --- a/crates/horizon-client/src/sound_engine.rs +++ b/crates/horizon-client/src/sound_engine.rs @@ -53,6 +53,11 @@ pub enum Ticking { Minecart { cart: u32 }, /// `RidingMinecartSoundInstance` for the player riding a minecart. RidingMinecart { cart: u32, underwater: bool }, + /// `BeeFlyingSoundInstance`, or `BeeAggressiveSoundInstance` when + /// `aggressive`. + Bee { bee: u32, aggressive: bool }, + /// `GuardianAttackSoundInstance`. + GuardianAttack { guardian: u32 }, } /// What a minecart's sound instances read about it. #[derive(Clone, Copy, Debug)] @@ -62,6 +67,21 @@ pub struct CartSound { /// `getDeltaMovement().horizontalDistance()`. pub speed: f64, } +/// What a bee's or a guardian's sound instance reads about it. +#[derive(Clone, Copy, Debug)] +pub struct MobSound { + pub id: u32, + pub position: [f64; 3], + /// `getDeltaMovement().horizontalDistance()`. + pub speed: f64, + pub baby: bool, + /// `Bee.isAngry`. + pub angry: bool, + /// `isSilent`. + pub silent: bool, + /// `Guardian.getAttackAnimationScale(0)`. + pub attack_scale: f32, +} /// What tickable instances read about the player and the entities they follow. #[derive(Clone, Debug, Default)] pub struct TickContext { @@ -71,6 +91,8 @@ pub struct TickContext { pub vehicle: Option, /// The minecarts in the level (a missing one has been removed). pub carts: Vec, + /// The bees and guardians in the level (a missing one has been removed). + pub mobs: Vec, /// `!tickRateManager().runsNormally()`. pub frozen: bool, } @@ -315,6 +337,59 @@ impl SoundInstance { }; s } + /// `new BeeFlyingSoundInstance(bee)` (or `BeeAggressiveSoundInstance`): + /// silent until the bee moves. + pub fn bee(bee: &MobSound, aggressive: bool, random: LegacyRandom) -> Self { + let id = if aggressive { + "minecraft:entity.bee.loop_aggressive" + } else { + "minecraft:entity.bee.loop" + }; + let [x, y, z] = bee.position; + let mut s = Self::new( + id, + NEUTRAL, + 0.0, + 1.0, + random, + true, + 0, + Attenuation::Linear, + [ + f64::from(x as f32), + f64::from(y as f32), + f64::from(z as f32), + ], + false, + ); + s.can_start_silent = true; + s.ticking = Ticking::Bee { + bee: bee.id, + aggressive, + }; + s + } + /// `new GuardianAttackSoundInstance(guardian)`: the guardian's own volume + /// and pitch until its first tick, heard everywhere. + pub fn guardian_attack(guardian: &MobSound, random: LegacyRandom) -> Self { + let id = "minecraft:entity.guardian.attack"; + let mut s = Self::new( + id, + crate::settings::sound_source(id), + 1.0, + 1.0, + random, + true, + 0, + Attenuation::None, + guardian.position, + false, + ); + s.ticking = Ticking::GuardianAttack { + guardian: guardian.id, + }; + s + } pub fn tickable(&self) -> bool { self.ticking != Ticking::No } @@ -389,6 +464,54 @@ impl SoundInstance { 0.0 }; } + Ticking::Bee { bee, aggressive } => { + let (id, aggressive) = (*bee, *aggressive); + // canPlaySound, then shouldSwitchSounds: the other kind of + // instance is started in this one's place. + let Some(bee) = ctx + .mobs + .iter() + .find(|m| m.id == id) + .filter(|m| !m.silent && m.angry == aggressive) + else { + self.stop(); + return; + }; + let [x, y, z] = bee.position; + self.position = [ + f64::from(x as f32), + f64::from(y as f32), + f64::from(z as f32), + ]; + let (min, max) = if bee.baby { (1.1, 1.5) } else { (0.7, 1.1) }; + let speed = bee.speed as f32; + if speed >= 0.01 { + // Mth.lerp(Mth.clamp(speed, min, max), min, max). + self.pitch = min + speed.clamp(min, max) * (max - min); + self.volume = speed.clamp(0.0, 0.5) * 1.2; + } else { + self.pitch = 0.0; + self.volume = 0.0; + } + } + Ticking::GuardianAttack { guardian } => { + let id = *guardian; + // The client's guardian never has a target of its own, so + // only its removal or silence ends the loop. + let Some(guardian) = ctx.mobs.iter().find(|m| m.id == id && !m.silent) else { + self.stop(); + return; + }; + let [x, y, z] = guardian.position; + self.position = [ + f64::from(x as f32), + f64::from(y as f32), + f64::from(z as f32), + ]; + let scale = guardian.attack_scale; + self.volume = 0.0 + 1.0 * scale * scale; + self.pitch = 0.7 + 0.5 * scale; + } Ticking::RidingMinecart { cart, underwater } => { let (id, underwater) = (*cart, *underwater); let found = ctx.carts.iter().find(|c| c.id == id); From e5e1b74fd89abf3e8b8263c3bf42039a5fec0ed8 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:44:37 +0100 Subject: [PATCH 174/221] Draw the enderman portal trail, phantom wing dust and bee nectar drips --- crates/horizon-client/src/game.rs | 5 ++ .../horizon-client/src/game/client_ambient.rs | 2 + .../src/game/level_particles.rs | 9 ++- crates/horizon-client/src/mobs/ambient.rs | 68 ++++++++++++++++++- crates/horizon-client/src/mobs/enderman.rs | 16 +++++ crates/horizon-client/src/particles.rs | 37 ++++++++++ 6 files changed, 134 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..527bd445a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3014,6 +3014,11 @@ impl Game<'_> { pos, data, } => self.consume_teleport_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2018, + pos, + data, + } => self.enderman_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2003, pos, .. } => { self.eye_break_particles([pos.x, pos.y, pos.z]); } diff --git a/crates/horizon-client/src/game/client_ambient.rs b/crates/horizon-client/src/game/client_ambient.rs index 1cf59733d..5efc86504 100644 --- a/crates/horizon-client/src/game/client_ambient.rs +++ b/crates/horizon-client/src/game/client_ambient.rs @@ -17,8 +17,10 @@ impl Game<'_> { return; } let mut events = Vec::new(); + let random = self.particles.level_random(); for m in self.mobs.iter_mut().filter(|m| !m.removed) { ambient::client_ai_step(m, &mut events); + ambient::client_particles(m, random, &mut events); } for event in events { match event { diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 9fa53eb25..98f62bfc3 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,7 +1,7 @@ //! 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). +//! consumable's teleport (2017), an enderman's (2018), electric sparks (3002), +//! waxing (3003), wax off (3004) and scraping (3005). use super::Game; use horizon_client::items::ItemStack; use horizon_client::particles::{self, ParticleOptions, ParticleType}; @@ -18,6 +18,11 @@ impl Game<'_> { self.particles .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); } + /// Event 2018: an enderman's portal trail. + pub(super) fn enderman_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .enderman_teleportation(pos, data, self.settings.particles); + } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. pub(super) fn block_particle_event(&mut self, id: i32, pos: BlockPos, data: i32) { diff --git a/crates/horizon-client/src/mobs/ambient.rs b/crates/horizon-client/src/mobs/ambient.rs index cb4146e08..94589ffab 100644 --- a/crates/horizon-client/src/mobs/ambient.rs +++ b/crates/horizon-client/src/mobs/ambient.rs @@ -2,8 +2,10 @@ //! `level().isClientSide()` branches of `aiStep`: nothing of it reaches the //! server or goes over the network, so the window's game runs it, whether it //! simulates the world (in-frame) or follows a server. -use super::{Mob, MobEvent, Species}; +use super::{Mob, MobEvent, Species, bee}; +use horizon_core::geometry::trig::Mth; use horizon_core::random::RandomSource; +use std::f32::consts::PI; /// `Enderman.aiStep`, `Endermite.aiStep` and `Blaze.aiStep` on a client: /// two portal particles a tick around endermen and endermites; two large @@ -53,3 +55,67 @@ pub fn client_ai_step(m: &mut Mob, out: &mut Vec) { out.push(MobEvent::ParticleAt { kind, at, velocity }); } } + +/// `Phantom.tick` and `Bee.tick` on a client, which draw from the client +/// level's random (`random`) and never from the mob's own, so a window that +/// simulates the world keeps the mob's draws as the server has them: a +/// phantom's wings leave mycelium dust, a bee carrying nectar now and then +/// drips it. +pub fn client_particles(m: &Mob, random: &mut impl RandomSource, out: &mut Vec) { + match m.species() { + Species::Phantom => { + // The wings flap every phantom in a different phase + // (`getUniqueFlapTickOffset`). + let flap = ((m.id.wrapping_mul(3).wrapping_add(m.age)) as i32 as f32 + * 7.448451 + * (PI / 180.0) + + PI) + .mcos(); + let width = m.width() * 1.48; + let yaw = m.yaw * (PI / 180.0); + let (c, s) = (yaw.mcos() * width, yaw.msin() * width); + let h = (0.3 + flap * 0.45) * m.height() * 2.5; + let p = m.position; + for (dx, dz) in [(c, s), (-c, -s)] { + out.push(MobEvent::ParticleAt { + kind: "mycelium", + at: [p.x + f64::from(dx), p.y + f64::from(h), p.z + f64::from(dz)], + velocity: [0.0; 3], + }); + } + } + Species::Bee => { + if !bee::has_nectar(m) + || !bee::get(m).is_some_and(|b| b.crops_grown < 10) + || random.next_float() >= 0.05 + { + return; + } + // `for (i = 0; i < nextInt(2) + 1; i++)` rolls the bound each time. + let mut i = 0; + while i < random.next_int_bound(2).unwrap_or(0) + 1 { + // Mth.lerp(level.random.nextDouble(), x - 0.3F, x + 0.3F). + let spread = f64::from(0.3_f32); + let lerp = |delta: f64, from: f64, to: f64| from + delta * (to - from); + let x = lerp( + random.next_double(), + m.position.x - spread, + m.position.x + spread, + ); + let z = lerp( + random.next_double(), + m.position.z - spread, + m.position.z + spread, + ); + out.push(MobEvent::ParticleAt { + kind: "falling_nectar", + // getY(0.5). + at: [x, m.position.y + f64::from(m.height()) * 0.5, z], + velocity: [0.0; 3], + }); + i += 1; + } + } + _ => {} + } +} diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 3ccd963a2..b05b15b94 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -97,10 +97,26 @@ pub fn teleport_to( return false; } let old = m.center(); + let old_block = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; m.position = Vec3::new(x, ny, z); m.previous = m.position; m.velocity = Vec3::ZERO; m.ai.nav.stop(); + if !m.silent { + // Level event 2018: the portal trail, from the old block to the new + // one, packed as `BlockUtil.clampedPackDifferenceInPosition` does. + let new_block = [x.floor() as i32, ny.floor() as i32, z.floor() as i32]; + let packed = |k: usize| ((new_block[k] - old_block[k]).clamp(-127, 127) + 127) & 255; + events.push(MobEvent::LevelEvent { + id: 2018, + pos: old_block, + data: packed(0) << 16 | packed(1) << 8 | packed(2), + }); + } events.push(MobEvent::Sound("entity.enderman.teleport", old, 1.0, 1.0)); events.push(MobEvent::Sound( "entity.enderman.teleport", diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 5efc83621..cd655e170 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1175,6 +1175,43 @@ impl ParticleEngine { } } } + /// `LevelEventHandler.levelEvent` 2018: an enderman's portal trail from + /// where it was (`from`) to where it went, which `data` packs within + /// (127, 127, 127). 128 portal particles along the way, spread about the + /// width and height of an enderman. + pub fn enderman_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) { + // EntityTypes.ENDERMAN's dimensions. + const WIDTH: f64 = 0.6_f32 as f64; + const HEIGHT: f64 = 2.9_f32 as f64; + let to = [ + from[0].wrapping_add(((data >> 16) & 255) - 127), + from[1].wrapping_add(((data >> 8) & 255) - 127), + from[2].wrapping_add((data & 255) - 127), + ] + .map(f64::from); + let from = from.map(f64::from); + let options = ParticleOptions::simple(ParticleType::Portal); + for _ in 0..128 { + let r = &mut self.level_random; + let t = r.next_double(); + let velocity = std::array::from_fn(|_| f64::from((r.next_float() - 0.5) * 0.2)); + // Mth.lerp(t, to, from). + let position = [ + to[0] + t * (from[0] - to[0]) + (r.next_double() - 0.5) * WIDTH * 2.0, + to[1] + t * (from[1] - to[1]) + r.next_double() * HEIGHT, + to[2] + t * (from[2] - to[2]) + (r.next_double() - 0.5) * WIDTH * 2.0, + ]; + // The option roll shares the level random and precedes the distance check. + let limited = match particle_level { + 1 => r.next_int_bound(3).unwrap_or(0) == 0, + 2 => true, + _ => false, + }; + if !limited { + self.add(&options, position, velocity); + } + } + } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the /// explosion particle (the emitter unless `ServerExplosion.isSmall`) and up /// to 512 poof/smoke particles thrown from air inside the radius. From fc06585938b4c0a4386e3c43b7ff8352158e35df Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:33:43 +0100 Subject: [PATCH 175/221] Send mob particles to clients the way vanilla does --- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/creatures.rs | 17 +++++ .../horizon-client/src/game/lan_particles.rs | 34 ++++++++++ crates/horizon-client/src/game/remote.rs | 17 +++++ .../src/game/remote_mob_particles.rs | 50 +++++++++++++++ crates/horizon-client/src/mobs.rs | 17 +++++ crates/horizon-client/src/mobs/ai.rs | 10 +-- crates/horizon-client/src/mobs/cube.rs | 62 +++++++++++-------- crates/horizon-client/src/mobs/illusioner.rs | 57 ++++++++++++----- crates/horizon-client/src/mobs/nautilus.rs | 19 ++++-- crates/horizon-client/src/mobs/ravager.rs | 9 ++- crates/horizon-client/src/mobs/undead.rs | 21 ++++--- crates/horizon-client/src/mobs/wither.rs | 20 ++++++ 13 files changed, 277 insertions(+), 57 deletions(-) create mode 100644 crates/horizon-client/src/game/remote_mob_particles.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..b371d1a50 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -143,6 +143,7 @@ mod recipe_book; mod remote; mod remote_chunks; mod remote_mob_data; +mod remote_mob_particles; mod remote_mob_use; mod remote_objects; mod remote_projectiles; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..02154e713 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -933,6 +933,23 @@ impl Game<'_> { match e { MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), + MobEvent::EntityEvent { mob, event, at } => { + self.lan_entity_event(mob as i32, event, at) + } + MobEvent::LevelParticles { + kind, + at, + spread, + speed, + count, + } => { + if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { + let options = horizon_client::particles::ParticleOptions::simple(ty); + self.particles + .send_particles(&options, at, spread, speed, count); + self.lan_level_particles(&options, at, spread, speed, count); + } + } MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 648cef962..909ef8c36 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -82,6 +82,40 @@ impl Game<'_> { } } + /// `ServerLevel.sendParticles` of a mob's particles: a packet to each + /// player within 32 blocks. The window draws its own copy. + pub(super) fn lan_level_particles( + &self, + options: &ParticleOptions, + at: [f64; 3], + spread: [f64; 3], + speed: f64, + count: u32, + ) { + let (Some(host), Some(particle)) = (&self.lan, self.network_particle(options, None)) else { + return; + }; + let packet = 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, + }); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + // ServerLevel compares the player's block centre, strictly within 32. + let distance: f64 = (0..3) + .map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2)) + .sum(); + if distance < 32.0 * 32.0 { + g.send(&packet); + } + } + } + /// `LivingEntity.checkFallDamage`'s `ServerLevel.sendParticles` of the /// landing block's crumbs: drawn in this window, when it has one, and /// sent to each player within 32 blocks. `host` is the hub of a guest's diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..7daffdc44 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2130,6 +2130,10 @@ impl Game<'_> { self.ui.registries.permission = (p.event - 24) as u8; self.remote_world_options_permission(p.event >= 26); } + // Ravager.handleEntityEvent 69: the roar's puff and push. + if p.event == 69 { + self.remote_ravager_roar(p.id); + } if p.event == 1 && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Rabbit @@ -3537,6 +3541,7 @@ impl Game<'_> { let head_lerps = &mut r.head_lerps; let players = &r.level_players; let mut using = Vec::new(); + let mut mob_fx = Vec::new(); for m in &mut self.mobs { let player = players.contains_key(&(m.id as i32)); if !running && !player { @@ -3576,6 +3581,17 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::PolarBear { horizon_client::mobs::polar_bear::client_tick(m); } + // The particles these mobs' own ticks draw on the client side. + { + use horizon_client::mobs::{Species as S, cube, illusioner, nautilus, wither}; + match m.species() { + S::Slime | S::MagmaCube | S::SulfurCube => cube::client_tick(m, &mut mob_fx), + S::Nautilus | S::ZombieNautilus => nautilus::client_tick(m, &mut mob_fx), + S::Illusioner => illusioner::client_tick(m, &mut mob_fx), + S::Wither => wither::client_tick(m, &mut mob_fx), + _ => {} + } + } if m.hurt_time > 0 { m.hurt_time -= 1; } @@ -3672,6 +3688,7 @@ impl Game<'_> { d.tick(world, facts, collision, false, &self.res.motion().fluids); } head_lerps.retain(|_, (_, steps)| *steps > 0); + let _ = self.handle_mob_events(mob_fx); for (item, ticks, at, eye, pitch, yaw) in using { self.remote_player_eating(&item, ticks, at, eye, pitch, yaw); } diff --git a/crates/horizon-client/src/game/remote_mob_particles.rs b/crates/horizon-client/src/game/remote_mob_particles.rs new file mode 100644 index 000000000..e3daf284d --- /dev/null +++ b/crates/horizon-client/src/game/remote_mob_particles.rs @@ -0,0 +1,50 @@ +//! Particles a client of a server draws for a mob's entity event, which the +//! server does not send as a particle packet. +use super::Game; +use horizon_client::{ + mobs::Species, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; + +impl Game<'_> { + /// `Ravager.handleEntityEvent(69)`: forty puffs of smoke from the middle + /// of its box, then `applyRoarKnockbackClient`: this client's own player + /// within 4 blocks is thrown away from it. + pub(super) fn remote_ravager_roar(&mut self, id: i32) { + let Some(m) = self + .mobs + .iter() + .find(|m| m.id == id as u32 && m.species() == Species::Ravager) + else { + return; + }; + let (center, at, area) = ( + m.center(), + m.position, + m.bounds().inflate(Vec3::new(4.0, 4.0, 4.0)), + ); + let options = ParticleOptions::simple(ParticleType::Poof); + for _ in 0..40 { + let r = self.particles.random(); + let v = [ + r.next_gaussian() * 0.2, + r.next_gaussian() * 0.2, + r.next_gaussian() * 0.2, + ]; + self.particles.add(&options, center, v); + } + if let Some(view) = self.player_view() + && view.alive + && view.bounds.intersects(area) + && let Some(p) = self.player.as_mut() + { + // strongKnockback. + let (xd, zd) = (p.position.x - at.x, p.position.z - at.z); + let dd = (xd * xd + zd * zd).max(0.001); + p.velocity = p + .velocity + .add_vector(Vec3::new(xd / dd * 4.0, 0.2, zd / dd * 4.0)); + } + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..cc9a34641 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -903,6 +903,23 @@ pub enum MobEvent { mob: u32, at: [f64; 3], }, + /// `Level.broadcastEntityEvent` for a mob: guests run its + /// `handleEntityEvent`. + EntityEvent { + mob: u32, + event: i8, + at: [f64; 3], + }, + /// `ServerLevel.sendParticles`: drawn here and sent to the players within + /// 32 blocks, which spread and speed the way the client does for a count + /// (a count of 0 is one particle moving by speed times spread). + LevelParticles { + kind: &'static str, + at: [f64; 3], + spread: [f64; 3], + speed: f64, + count: u32, + }, Sound(&'static str, [f64; 3], f32, f32), /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the /// chest's opener count goes up or down (interaction range 3). diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 26b94eeac..7790e2ce1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -727,8 +727,8 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.kind.flags.climber { m.climbing = m.horizontal_collision; } - // AgeableMob.aiStep: a forced age-up's particles (positions drawn on the - // server too), then the age. + // AgeableMob.aiStep: a forced age-up's particles (`sendParticles`, so the + // players are sent them), then the age. if m.extra.forced_age_timer > 0 { if m.extra.forced_age_timer % 4 == 0 { let (w, h) = (f64::from(m.width()), f64::from(m.height())); @@ -737,10 +737,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & let y = m.position.y + h * r.next_double() + 0.5; let z = m.position.z + w * (2.0 * r.next_double() - 1.0); // sendParticles(HAPPY_VILLAGER, x, y, z, 1, 0, 0, 0, 0): exactly there, at rest. - events.push(MobEvent::Particles { + events.push(MobEvent::LevelParticles { kind: "happy_villager", at: [x, y, z], - count: 0, + spread: [0.0; 3], + speed: 0.0, + count: 1, }); } m.extra.forced_age_timer -= 1; diff --git a/crates/horizon-client/src/mobs/cube.rs b/crates/horizon-client/src/mobs/cube.rs index ea8a05392..3cc16463c 100644 --- a/crates/horizon-client/src/mobs/cube.rs +++ b/crates/horizon-client/src/mobs/cube.rs @@ -151,37 +151,49 @@ pub fn jump(m: &mut Mob) { }; m.velocity.y = f64::from(m.jump_power() + boost); } +/// `AbstractCubeMob.tick`'s landing splash: crumbs of goo (or flames) around +/// the cube's feet, drawn by the side that ticks the mob. +fn landing_splash(m: &mut Mob, events: &mut Vec) { + let size = m.width() * 2.0; + let radius = size / 2.0; + let kind = match m.species() { + Species::MagmaCube => "flame", + Species::SulfurCube => "sulfur_cube_goo", + _ => "item_slime", + }; + let mut i = 0; + while (i as f32) < size * 16.0 { + let dir = m.random.next_float() * std::f64::consts::TAU as f32; + let d = m.random.next_float() * 0.5 + 0.5; + let xd = trig::sin(f64::from(dir)) * radius * d; + let zd = trig::cos(f64::from(dir)) * radius * d; + events.push(MobEvent::Particles { + kind, + at: [ + m.position.x + f64::from(xd), + m.position.y, + m.position.z + f64::from(zd), + ], + count: 0, + }); + i += 1; + } +} +/// `AbstractCubeMob.tick` on a client of a server: the landing splash follows +/// the on-ground flag the server sends. +pub fn client_tick(m: &mut Mob, events: &mut Vec) { + if m.on_ground && !m.extra.flag2 { + landing_splash(m, events); + } + m.extra.flag2 = m.on_ground; +} /// AbstractCubeMob.tick squish and landing sounds, plus contact damage. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let v = &mut m.anim.v; v[SQUISH] += (v[TARGET_SQUISH] - v[SQUISH]) * 0.5; let was = m.extra.flag2; if m.on_ground && !was { - // The landing splash: drawn on the server too, where it spawns nothing. - let size = m.width() * 2.0; - let radius = size / 2.0; - let kind = match m.species() { - Species::MagmaCube => "flame", - Species::SulfurCube => "sulfur_cube_goo", - _ => "item_slime", - }; - let mut i = 0; - while (i as f32) < size * 16.0 { - let dir = m.random.next_float() * std::f64::consts::TAU as f32; - let d = m.random.next_float() * 0.5 + 0.5; - let xd = trig::sin(f64::from(dir)) * radius * d; - let zd = trig::cos(f64::from(dir)) * radius * d; - events.push(MobEvent::Particles { - kind, - at: [ - m.position.x + f64::from(xd), - m.position.y, - m.position.z + f64::from(zd), - ], - count: 0, - }); - i += 1; - } + landing_splash(m, events); let squish = match (m.species(), tiny(m)) { (Species::SulfurCube, _) => super::sulfur_cube::squish_sound(m), (Species::MagmaCube, true) => "entity.magma_cube.squish_small", diff --git a/crates/horizon-client/src/mobs/illusioner.rs b/crates/horizon-client/src/mobs/illusioner.rs index ec17abad7..b98e56920 100644 --- a/crates/horizon-client/src/mobs/illusioner.rs +++ b/crates/horizon-client/src/mobs/illusioner.rs @@ -152,20 +152,7 @@ pub fn tick(m: &mut Mob, events: &mut Vec) { if !m.has_effect(INVISIBILITY) { return; } - let hurt = m.hurt_time; - let age = m.age; - let mut il = m.extra.illusions.take().unwrap_or_default(); - il.ticks = (il.ticks - 1).max(0); - if hurt == 1 || age.is_multiple_of(1200) { - il.ticks = 3; - for i in 0..COPIES { - il.offsets[0][i] = il.offsets[1][i]; - let r = &mut m.random; - let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; - let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64; - let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; - il.offsets[1][i] = [x, y, z]; - } + if step(m) { events.push(MobEvent::Particles { kind: "minecraft:cloud", at: [m.position.x, m.position.y + 0.9, m.position.z], @@ -177,6 +164,47 @@ pub fn tick(m: &mut Mob, events: &mut Vec) { 1.0, 1.0, )); + } +} + +/// `Illusioner.aiStep` on a client of a server: invisible is the synched +/// shared flag. The puff is drawn here exactly (sixteen `addParticle`s); the +/// sound comes from the server. +pub fn client_tick(m: &mut Mob, events: &mut Vec) { + if !m.invisible || !step(m) { + return; + } + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + for _ in 0..16 { + // getRandomX(0.5), getRandomY() and getZ(0.5), which is not random. + let x = m.position.x + w * (2.0 * m.random.next_double() - 1.0) * 0.5; + let y = m.position.y + h * m.random.next_double(); + events.push(MobEvent::ParticleAt { + kind: "cloud", + at: [x, y, m.position.z + w * 0.5], + velocity: [0.0; 3], + }); + } +} + +/// The image offsets' clock of an invisible illusioner. True when the images +/// jumped to new offsets (hurt, or once a minute), which the puff goes with. +fn step(m: &mut Mob) -> bool { + let hurt = m.hurt_time; + let age = m.age; + let mut il = m.extra.illusions.take().unwrap_or_default(); + il.ticks = (il.ticks - 1).max(0); + let jumped = hurt == 1 || age.is_multiple_of(1200); + if jumped { + il.ticks = 3; + for i in 0..COPIES { + il.offsets[0][i] = il.offsets[1][i]; + let r = &mut m.random; + let x = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; + let y = (r.next_int_bound(6).unwrap_or(0) - 4).max(0) as f64; + let z = (-6 + r.next_int_bound(13).unwrap_or(0)) as f64 * 0.5; + il.offsets[1][i] = [x, y, z]; + } } else if hurt == 9 { il.ticks = 3; for i in 0..COPIES { @@ -185,6 +213,7 @@ pub fn tick(m: &mut Mob, events: &mut Vec) { } } m.extra.illusions = Some(il); + jumped } /// `Illusioner.getIllusionOffsets`. diff --git a/crates/horizon-client/src/mobs/nautilus.rs b/crates/horizon-client/src/mobs/nautilus.rs index 2fcf7eb46..864865846 100644 --- a/crates/horizon-client/src/mobs/nautilus.rs +++ b/crates/horizon-client/src/mobs/nautilus.rs @@ -293,19 +293,28 @@ fn bubbles(m: &mut Mob, events: &mut Vec) { f64::from(yaw.cos() * pitch.cos()), ]; let spread = m.random.next_double() * 0.8 * (1.0 + speed); - for _ in 0..3 { - let _ = (f64::from(m.random.next_float()) - 0.5) * spread; - } - events.push(MobEvent::Particles { + let velocity = [ + (f64::from(m.random.next_float()) - 0.5) * spread, + (f64::from(m.random.next_float()) - 0.5) * spread, + (f64::from(m.random.next_float()) - 0.5) * spread, + ]; + events.push(MobEvent::ParticleAt { kind: "bubble", at: [ m.position.x - dir[0] * 1.1, m.position.y - dir[1] + 0.25, m.position.z - dir[2] * 1.1, ], - count: 1, + velocity, }); } +/// `AbstractNautilus.tick` on a client of a server: the bubbles of a nautilus +/// in the water, from the motion the server sent. +pub fn client_tick(m: &mut Mob, events: &mut Vec) { + if m.fluids.in_water { + bubbles(m, events); + } +} fn in_water_at(w: &MobWorld, p: Vec3) -> bool { w.fluid(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32) == Fluid::Water } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index 49bac4d9f..2db86e42a 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -197,7 +197,14 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { velocity: fling(s.position), }); } - // Entity event 69: a puff of smoke. + // Entity event 69: a puff of smoke, and the client's own push. A client + // of this server (the window of the server thread) gets the event; + // this window draws the puff itself. + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 69, + at: from, + }); events.push(MobEvent::Particles { kind: "poof", at: [ diff --git a/crates/horizon-client/src/mobs/undead.rs b/crates/horizon-client/src/mobs/undead.rs index 3707f4bbe..51a5cb0d2 100644 --- a/crates/horizon-client/src/mobs/undead.rs +++ b/crates/horizon-client/src/mobs/undead.rs @@ -978,16 +978,21 @@ impl Goal for AttackTurtleEgg { pos: eat, drop: false, }); + // `sendParticles(POOF, ..., 1, xa, ya, za, 0.15)`, twenty times. for _ in 0..20 { - m.random.next_gaussian(); - m.random.next_gaussian(); - m.random.next_gaussian(); + let spread = [ + m.random.next_gaussian() * 0.02, + m.random.next_gaussian() * 0.02, + m.random.next_gaussian() * 0.02, + ]; + cx.events.push(MobEvent::LevelParticles { + kind: "poof", + at: [center[0], f64::from(eat[1]), center[2]], + spread, + speed: 0.15, + count: 1, + }); } - cx.events.push(MobEvent::Particles { - kind: "poof", - at: [center[0], f64::from(eat[1]), center[2]], - count: 20, - }); // The break sound's pitch draws from the level random. cx.events.push(MobEvent::Sound( "block.turtle_egg.break", diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6702686c5..f962f574f 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -169,6 +169,26 @@ fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> { .map(|s| ([s.position.x, s.position.y, s.position.z], s.eye_y, false)), } } +/// `WitherBoss.aiStep` on a client of a server: the smoke about each head +/// (`radius` 0.3 of the wither's scale, which is 1 here). The heads' turning +/// and the coloured particles need the server's targets and invulnerable +/// ticks, which a client is not sent. +pub fn client_tick(m: &mut Mob, events: &mut Vec) { + for i in 0..3 { + let h = head_pos(m, i); + let r = &mut m.random; + let at = [ + h[0] + r.next_gaussian() * 0.3, + h[1] + r.next_gaussian() * 0.3, + h[2] + r.next_gaussian() * 0.3, + ]; + events.push(MobEvent::ParticleAt { + kind: "smoke", + at, + velocity: [0.0; 3], + }); + } +} /// `WitherBoss.aiStep` after `super.aiStep()`: the side heads turn, smoke /// rises from the heads (the particle offsets are drawn on the server too). pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { From 97dd6d982af10193972d0d136683616578d14b87 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 06:53:39 +0100 Subject: [PATCH 176/221] Leave the fox's type and the panda's genes to #2538 and #2551 Those PRs sync the fox's DATA_TYPE_ID with its flags and the panda's genes with its counters and flags; the same arms here would be unreachable once both land. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 17 ++++------------- .../horizon-client/src/game/remote_mob_data.rs | 9 ++------- 2 files changed, 6 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index aba1b2dc9..4b11bceae 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -390,24 +390,15 @@ fn mob_meta( meta.push((index, serializer, Value::Id(v))); } } - // Axolotl.DATA_VARIANT (after AgeableMob's two), Fox.DATA_TYPE_ID, - // Rabbit.DATA_TYPE_ID and Parrot.DATA_VARIANT_ID (after - // TamableAnimal's two and its flags and owner). - "minecraft:axolotl" | "minecraft:fox" | "minecraft:rabbit" | "minecraft:parrot" => { + // Axolotl.DATA_VARIANT and Rabbit.DATA_TYPE_ID (after AgeableMob's + // two), Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its + // flags and owner). The fox's type goes with its flags (#2538). + "minecraft:axolotl" | "minecraft:rabbit" | "minecraft:parrot" => { let index = if kind == "minecraft:parrot" { 20 } else { 18 }; if e.variant != 0 { meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); } } - // Panda.MAIN_GENE_ID and HIDDEN_GENE_ID (after its three counters). - "minecraft:panda" => { - if e.variant != 0 { - meta.push((21, serializer::BYTE, Value::Byte(e.variant as i8))); - } - if e.variant2 != 0 { - meta.push((22, serializer::BYTE, Value::Byte(e.variant2 as i8))); - } - } // Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and // DATA_ANGER_END_TIME: the texture shows the nectar and the anger. "minecraft:bee" => { diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 476b6556a..3837e939b 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -113,19 +113,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Llama | Species::TraderLlama, 21, Value::Int(variant)) => { m.extra.variant = (*variant).clamp(0, 3) as u8; } - // Axolotl.DATA_VARIANT (lucy 0 to blue 4), Fox.DATA_TYPE_ID (red - // 0, snow 1) and Parrot.DATA_VARIANT_ID (after TamableAnimal's - // flags and owner). + // Axolotl.DATA_VARIANT (lucy 0 to blue 4) and Parrot.DATA_VARIANT_ID + // (after TamableAnimal's flags and owner). (Species::Axolotl, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, - (Species::Fox, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 1) as u8, (Species::Parrot, 20, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8, // Rabbit.DATA_TYPE_ID: the killer bunny's 99 has no model here. (Species::Rabbit, 18, Value::Int(t)) if (0..=5).contains(t) => { m.extra.variant = *t as u8; } - // Panda.MAIN_GENE_ID and HIDDEN_GENE_ID (after the three counters). - (Species::Panda, 21, Value::Byte(gene)) => m.extra.variant = (*gene).clamp(0, 6) as u8, - (Species::Panda, 22, Value::Byte(gene)) => m.extra.variant2 = (*gene).clamp(0, 6) as u8, // Bee.DATA_FLAGS_ID and DATA_ANGER_END_TIME (after Animal's). (Species::Bee, 18, Value::Byte(flags)) => bee::set_synced(m, Some(*flags as u8), None), (Species::Bee, 19, Value::Long(end)) => bee::set_synced(m, None, Some(*end)), From 0f581c669eb133d5ab98dc422cff2dbb88690532 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:01:41 +0100 Subject: [PATCH 177/221] Send the axolotl's variant beside its own arm #2533 gives the axolotl an arm for DATA_PLAYING_DEAD: a second axolotl pattern here would be unreachable, so the variant goes before the match. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 4b11bceae..0201936b0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -221,6 +221,11 @@ fn mob_meta( } let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); + // Axolotl.DATA_VARIANT (after AgeableMob's two), outside the match so the + // axolotl's own arm keeps its other entries. + if kind == "minecraft:axolotl" && e.variant != 0 { + meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); + } match kind { "minecraft:guardian" | "minecraft:elder_guardian" => { // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET. @@ -390,10 +395,10 @@ fn mob_meta( meta.push((index, serializer, Value::Id(v))); } } - // Axolotl.DATA_VARIANT and Rabbit.DATA_TYPE_ID (after AgeableMob's - // two), Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its - // flags and owner). The fox's type goes with its flags (#2538). - "minecraft:axolotl" | "minecraft:rabbit" | "minecraft:parrot" => { + // Rabbit.DATA_TYPE_ID (after AgeableMob's two) and + // Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and + // owner). The fox's type goes with its flags (#2538). + "minecraft:rabbit" | "minecraft:parrot" => { let index = if kind == "minecraft:parrot" { 20 } else { 18 }; if e.variant != 0 { meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); From 48fd9f4ea58995dd8ac4706fdec87b6873e8a3af Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 07:03:55 +0100 Subject: [PATCH 178/221] Give the variant entries a match of their own The fox, panda, frog, axolotl and copper golem have arms for their other entries in other PRs (#2538, #2551, #2539, #2533): mob_variant_meta keeps the variants out of mob_meta's match, so neither arm is unreachable. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 228 ++++++++++++++------------ 1 file changed, 123 insertions(+), 105 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 0201936b0..3195f81fb 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -153,6 +153,128 @@ pub(super) fn baby_index(kind: &str) -> Option { } } +/// The variant and look entries of `mob_meta`'s mobs (registry holders, the +/// fish's, the bee's, the copper golem's weathering...), in a match of their +/// own: `mob_meta`'s arms hold these mobs' other entries. +fn mob_variant_meta( + m: &Mob, + hub: &Hub, + meta: &mut Vec<(u8, i32, Value)>, + defaults: &mut Vec<(u8, i32, Value)>, +) { + let (kind, e) = (m.kind.id.as_str(), &m.extra); + let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); + match kind { + // Axolotl.DATA_VARIANT (after AgeableMob's two). + "minecraft:axolotl" => { + if e.variant != 0 { + meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } + // Frog.DATA_VARIANT_ID, Pig's, Cow's, Chicken's and ZombieNautilus's + // (after the entries of their parents): registry holders. + "minecraft:frog" + | "minecraft:pig" + | "minecraft:cow" + | "minecraft:chicken" + | "minecraft:zombie_nautilus" => { + let (index, serializer, registry) = match kind { + "minecraft:frog" => (18, serializer::FROG_VARIANT, "minecraft:frog_variant"), + "minecraft:pig" => (19, serializer::PIG_VARIANT, "minecraft:pig_variant"), + "minecraft:cow" => (18, serializer::COW_VARIANT, "minecraft:cow_variant"), + "minecraft:chicken" => { + (18, serializer::CHICKEN_VARIANT, "minecraft:chicken_variant") + } + _ => ( + 21, + serializer::ZOMBIE_NAUTILUS_VARIANT, + "minecraft:zombie_nautilus_variant", + ), + }; + let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant); + if let Some(v) = id(registry, name.trim_start_matches("minecraft:")) { + meta.push((index, serializer, Value::Id(v))); + } + } + // Rabbit.DATA_TYPE_ID (after AgeableMob's two) and + // Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and + // owner). The fox's type goes with its flags (#2538). + "minecraft:rabbit" | "minecraft:parrot" => { + let index = if kind == "minecraft:parrot" { 20 } else { 18 }; + if e.variant != 0 { + meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); + } + } + // Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and + // DATA_ANGER_END_TIME: the texture shows the nectar and the anger. + "minecraft:bee" => { + let bee = horizon_client::mobs::bee::get(m); + let flags = bee.map_or(0, |b| b.flags); + if flags != 0 { + meta.push((18, serializer::BYTE, Value::Byte(flags as i8))); + } + defaults.push((18, serializer::BYTE, Value::Byte(0))); + let anger_end = bee.map_or(-1, |b| b.anger_end); + if anger_end != -1 { + meta.push((19, serializer::LONG, Value::Long(anger_end))); + } + defaults.push((19, serializer::LONG, Value::Long(-1))); + } + // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0, + // medium 1, large 2; medium is the data's default, so always sent), + // Pufferfish.PUFF_STATE and TropicalFish.DATA_ID_TYPE_VARIANT: the + // pattern's packed id (size, then index << 8), base colour << 16 and + // pattern colour << 24. + "minecraft:salmon" => { + meta.push((17, serializer::INT, Value::Int(i32::from(e.variant.min(2))))); + } + "minecraft:pufferfish" => { + if e.size > 0 { + meta.push((17, serializer::INT, Value::Int(e.size))); + } + defaults.push((17, serializer::INT, Value::Int(0))); + } + "minecraft:tropical_fish" => { + let pattern = e.variant.min(11); + let packed = i32::from(pattern >= 6) + | i32::from(pattern % 6) << 8 + | i32::from(e.variant2 & 15) << 16 + | i32::from(e.variant3 & 15) << 24; + if packed != 0 { + meta.push((17, serializer::INT, Value::Int(packed))); + } + } + // CopperGolem.DATA_WEATHER_STATE: unaffected 0 to oxidized 3, and it + // goes back down when the golem is scraped. + "minecraft:copper_golem" => { + if e.variant != 0 { + meta.push(( + 16, + serializer::WEATHERING_COPPER_STATE, + Value::Id(i32::from(e.variant.min(3))), + )); + } + defaults.push((16, serializer::WEATHERING_COPPER_STATE, Value::Id(0))); + } + // Ghast.DATA_IS_CHARGING: the shooting texture. + "minecraft:ghast" => { + if e.flag { + meta.push((16, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); + } + // WitherBoss.DATA_ID_INV (after the three head targets): the + // invulnerable ticks, the blinking texture and the growing scale. + "minecraft:wither" => { + if e.counter > 0 { + meta.push((19, serializer::INT, Value::Int(e.counter))); + } + defaults.push((19, serializer::INT, Value::Int(0))); + } + _ => {} + } +} + /// A mob's synched data as ServerEntity sends it (only the values that differ /// from the defaults the client constructs), with vanilla's entry indices: /// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses. @@ -221,11 +343,7 @@ fn mob_meta( } let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); - // Axolotl.DATA_VARIANT (after AgeableMob's two), outside the match so the - // axolotl's own arm keeps its other entries. - if kind == "minecraft:axolotl" && e.variant != 0 { - meta.push((18, serializer::INT, Value::Int(i32::from(e.variant)))); - } + mob_variant_meta(m, hub, meta, defaults); match kind { "minecraft:guardian" | "minecraft:elder_guardian" => { // Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET. @@ -370,106 +488,6 @@ fn mob_meta( )); } } - // Frog.DATA_VARIANT_ID, Pig's, Cow's, Chicken's and ZombieNautilus's - // (after the entries of their parents): registry holders. - "minecraft:frog" - | "minecraft:pig" - | "minecraft:cow" - | "minecraft:chicken" - | "minecraft:zombie_nautilus" => { - let (index, serializer, registry) = match kind { - "minecraft:frog" => (18, serializer::FROG_VARIANT, "minecraft:frog_variant"), - "minecraft:pig" => (19, serializer::PIG_VARIANT, "minecraft:pig_variant"), - "minecraft:cow" => (18, serializer::COW_VARIANT, "minecraft:cow_variant"), - "minecraft:chicken" => { - (18, serializer::CHICKEN_VARIANT, "minecraft:chicken_variant") - } - _ => ( - 21, - serializer::ZOMBIE_NAUTILUS_VARIANT, - "minecraft:zombie_nautilus_variant", - ), - }; - let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant); - if let Some(v) = id(registry, name.trim_start_matches("minecraft:")) { - meta.push((index, serializer, Value::Id(v))); - } - } - // Rabbit.DATA_TYPE_ID (after AgeableMob's two) and - // Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and - // owner). The fox's type goes with its flags (#2538). - "minecraft:rabbit" | "minecraft:parrot" => { - let index = if kind == "minecraft:parrot" { 20 } else { 18 }; - if e.variant != 0 { - meta.push((index, serializer::INT, Value::Int(i32::from(e.variant)))); - } - } - // Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and - // DATA_ANGER_END_TIME: the texture shows the nectar and the anger. - "minecraft:bee" => { - let bee = horizon_client::mobs::bee::get(m); - let flags = bee.map_or(0, |b| b.flags); - if flags != 0 { - meta.push((18, serializer::BYTE, Value::Byte(flags as i8))); - } - defaults.push((18, serializer::BYTE, Value::Byte(0))); - let anger_end = bee.map_or(-1, |b| b.anger_end); - if anger_end != -1 { - meta.push((19, serializer::LONG, Value::Long(anger_end))); - } - defaults.push((19, serializer::LONG, Value::Long(-1))); - } - // AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0, - // medium 1, large 2; medium is the data's default, so always sent), - // Pufferfish.PUFF_STATE and TropicalFish.DATA_ID_TYPE_VARIANT: the - // pattern's packed id (size, then index << 8), base colour << 16 and - // pattern colour << 24. - "minecraft:salmon" => { - meta.push((17, serializer::INT, Value::Int(i32::from(e.variant.min(2))))); - } - "minecraft:pufferfish" => { - if e.size > 0 { - meta.push((17, serializer::INT, Value::Int(e.size))); - } - defaults.push((17, serializer::INT, Value::Int(0))); - } - "minecraft:tropical_fish" => { - let pattern = e.variant.min(11); - let packed = i32::from(pattern >= 6) - | i32::from(pattern % 6) << 8 - | i32::from(e.variant2 & 15) << 16 - | i32::from(e.variant3 & 15) << 24; - if packed != 0 { - meta.push((17, serializer::INT, Value::Int(packed))); - } - } - // CopperGolem.DATA_WEATHER_STATE: unaffected 0 to oxidized 3, and it - // goes back down when the golem is scraped. - "minecraft:copper_golem" => { - if e.variant != 0 { - meta.push(( - 16, - serializer::WEATHERING_COPPER_STATE, - Value::Id(i32::from(e.variant.min(3))), - )); - } - defaults.push((16, serializer::WEATHERING_COPPER_STATE, Value::Id(0))); - } - // Ghast.DATA_IS_CHARGING: the shooting texture. - "minecraft:ghast" => { - if e.flag { - meta.push((16, serializer::BOOLEAN, Value::Bool(true))); - } - defaults.push((16, serializer::BOOLEAN, Value::Bool(false))); - } - // WitherBoss.DATA_ID_INV (after the three head targets): the - // invulnerable ticks, the blinking texture and the growing scale. - "minecraft:wither" => { - if e.counter > 0 { - meta.push((19, serializer::INT, Value::Int(e.counter))); - } - defaults.push((19, serializer::INT, Value::Int(0))); - } // AbstractCubeMob.ID_SIZE. "minecraft:slime" | "minecraft:magma_cube" => { if e.size > 1 { From 05d150349fabccf43cfee9e7ffe4f10bbd766a20 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:34:14 +0100 Subject: [PATCH 179/221] Goats: keep the ram cooldown a brain memory RAM_COOLDOWN_TICKS is a memory in vanilla (GoatAi.initMemories, CountDownCooldownTicks), saved with the others; as a field it was neither saved nor seen by finalize_spawn, which failed on every goat. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/finalize.rs | 2 +- crates/horizon-client/src/mobs/goat.rs | 40 +++++++++++++++++----- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index ce8ede539..6e5daff1f 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1677,7 +1677,7 @@ impl Ctx<'_, L, R> { let jump = self.uniform(600, 1200); set_memory(m, "long_jump_cooldown", i64::from(jump), i64::MAX); let ram = self.uniform(600, 6000); - m.extra.goat.ram_cooldown = ram; + set_memory(m, "ram_cooldown", i64::from(ram), i64::MAX); m.extra.screaming = self.random.next_double() < 0.02; age_boundary_reached(m); if !m.is_baby() && self.float() < 0.1 { diff --git a/crates/horizon-client/src/mobs/goat.rs b/crates/horizon-client/src/mobs/goat.rs index 647d6f789..058f0e697 100644 --- a/crates/horizon-client/src/mobs/goat.rs +++ b/crates/horizon-client/src/mobs/goat.rs @@ -38,11 +38,10 @@ struct Candidate { target: Who, } -/// `RAM_COOLDOWN_TICKS`, the lowered head and the ram behaviours' state. +/// The lowered head and the ram behaviours' state. `RAM_COOLDOWN_TICKS` is a +/// brain memory (`ram_cooldown`), saved with the others. #[derive(Clone, Debug, Default)] pub struct State { - /// `RAM_COOLDOWN_TICKS`: 0 when absent. - pub ram_cooldown: i32, lower_head_tick: i32, lowering_head: bool, phase: Phase, @@ -71,10 +70,33 @@ pub fn tick(m: &mut Mob) { let g = &mut m.extra.goat; g.lower_head_tick += if g.lowering_head { 1 } else { -2 }; g.lower_head_tick = g.lower_head_tick.clamp(0, 20); - if g.ram_cooldown > 0 { - g.ram_cooldown -= 1; + // `CountDownCooldownTicks(RAM_COOLDOWN_TICKS)`: one less each tick, erased + // once it runs out. + let cooldown = ram_cooldown(m); + if cooldown > 0 { + set_ram_cooldown(m, cooldown - 1); } } +/// `RAM_COOLDOWN_TICKS`: 0 when absent. +pub fn ram_cooldown(m: &Mob) -> i32 { + m.extra + .memories + .iter() + .find(|x| x.0 == RAM_COOLDOWN) + .map_or(0, |x| x.1 as i32) +} +fn set_ram_cooldown(m: &mut Mob, ticks: i32) { + let memories = &mut m.extra.memories; + match memories.iter().position(|x| x.0 == RAM_COOLDOWN) { + Some(i) if ticks > 0 => memories[i].1 = i64::from(ticks), + Some(i) => { + memories.remove(i); + } + None if ticks > 0 => memories.push((RAM_COOLDOWN, i64::from(ticks), i64::MAX)), + None => {} + } +} +const RAM_COOLDOWN: &str = "ram_cooldown"; /// `Goat.getRammingXHeadRot`. pub fn ramming_x_head_rot(m: &Mob) -> f32 { let max = if m.is_baby() { 52.5_f32 } else { 30.0 }; @@ -206,7 +228,7 @@ impl Goal for Ram { fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { // The ram activity needs the cooldown to be over (it also waits for // no tempting player and no breed target, which goats lack here). - m.extra.goat.ram_cooldown <= 0 + ram_cooldown(m) <= 0 } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { let g = &m.extra.goat; @@ -235,7 +257,8 @@ impl Goal for Ram { // up and the cooldown starts. Phase::Prepare => { lower_head(m, cx.events, false); - m.extra.goat.ram_cooldown = rams(m).0; + let wait = rams(m).0; + set_ram_cooldown(m, wait); } // RamTarget.finishRam (also what its timeout leaves undone). Phase::RamStart | Phase::Ram => finish_ram(m, cx.events), @@ -437,7 +460,8 @@ fn drop_horn(m: &mut Mob, events: &mut Vec) -> bool { fn finish_ram(m: &mut Mob, events: &mut Vec) { lower_head(m, events, false); let wait = rams(m); - m.extra.goat.ram_cooldown = between(m, wait); + let cooldown = between(m, wait); + set_ram_cooldown(m, cooldown); m.extra.goat.ram_target = None; m.extra.goat.phase = Phase::Done; } From beac63849ce65b81a5a6002e2339d4d4ddbe17d2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 08:42:36 +0100 Subject: [PATCH 180/221] refactor: move the client's input modules into horizon-client-input Key bindings and names, toggle keys, mouse options, controller settings, the clipboard and window options move to their own crate, re-exported under their old paths. Their unit tests now rebuild in about a second after an edit instead of rebuilding the client lib's test binary. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 5 ++-- Cargo.lock | 14 ++++++++++- Cargo.toml | 1 + crates/horizon-client-input/Cargo.toml | 23 +++++++++++++++++++ .../src/clipboard.rs | 0 .../src/gamepad.rs | 0 .../src/input.rs | 0 .../src/interaction_input.rs | 0 .../src/key_names.rs | 0 .../src/keybinds.rs | 0 .../src/keymapping.rs | 0 crates/horizon-client-input/src/lib.rs | 14 +++++++++++ .../src/mouse.rs | 0 .../src/window.rs | 0 crates/horizon-client/Cargo.toml | 4 ++-- crates/horizon-client/src/lib.rs | 18 +++++++-------- docs/controllers.md | 2 +- tools/test_frame_limiter_parity.py | 2 +- tools/test_interaction_input_parity.py | 2 +- tools/test_local_input_parity.py | 2 +- tools/test_options_parity.py | 4 ++-- tools/test_sprint_input_parity.py | 2 +- tools/test_toggle_keys_parity.py | 2 +- 23 files changed, 73 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client-input/Cargo.toml rename crates/{horizon-client => horizon-client-input}/src/clipboard.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/gamepad.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/input.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/interaction_input.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/key_names.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/keybinds.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/keymapping.rs (100%) create mode 100644 crates/horizon-client-input/src/lib.rs rename crates/{horizon-client => horizon-client-input}/src/mouse.rs (100%) rename crates/{horizon-client => horizon-client-input}/src/window.rs (100%) diff --git a/AGENTS.md b/AGENTS.md index 0eb1fe8b5..2f754ed53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,7 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se | `horizon-client` | The game: a lib (`src/lib.rs`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) | | `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` | | `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) | +| `horizon-client-input` | Key bindings and key names, toggle keys, mouse options, controller settings and glyphs, the clipboard, window options (`keybinds.rs`, `gamepad.rs`, `mouse.rs`, `window.rs`...). Re-exported under the old paths | | `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage | | `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) | | `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` | @@ -112,7 +113,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Subsystem | Files | |---|---| -| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `window.rs`, `spans.rs` | +| Game loop, tick, frame | `game.rs`: `fn run`, `impl ApplicationHandler for Game` (`window_event`, `about_to_wait`), `fn tick`, `fn tick_world`, `fn render`; L: `clock.rs`, `spans.rs`; `horizon-client-input/src/window.rs` | | Rendering | L: `gfx.rs` (`Renderer::new`, `Renderer::render`), `gfx/` (cull, occlusion, translucency, upload, timing, lod, weather, stars, end_sky), `*.wgsl`, `particles.rs`, `block_entity_render.rs`, `item_render.rs`, `fog.rs`, `clouds.rs`, `camera.rs`, `first_person.rs`; G: `render_tick.rs`, `item_draw.rs` | | Chunks, streaming, light | L: `streaming.rs` (worker pool: generate, light, mesh), `world.rs`, `chunk.rs`, `chunk_map.rs`, `light.rs`, `mesher.rs` + `mesher/`, `vanillagen.rs` (binds horizon-world's generator), `lod.rs` + `lod/`, `ticket_levels.rs`; G: `world_loading.rs`, `postprocess.rs`; game.rs `fn update_world` | | World generation | `crates/horizon-world/src/worldgen/` (`generator*.rs`, `feature_graph.rs`, `structure/`, `carver/`) | @@ -128,7 +129,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end | Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` | | Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` | | Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | -| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | +| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; crate `horizon-client-input` (`keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `clipboard.rs`); L: `osk.rs`; G: `pad.rs`, `pad_menu.rs` | | Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` | | Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` | | Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | diff --git a/Cargo.lock b/Cargo.lock index 0e0a39038..2af972983 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1363,7 +1363,6 @@ name = "horizon-client" version = "0.1.0" dependencies = [ "ab_glyph", - "arboard", "bytemuck", "chrono", "cpal", @@ -1373,6 +1372,7 @@ dependencies = [ "horizon-assets", "horizon-bench", "horizon-client-core", + "horizon-client-input", "horizon-command", "horizon-core", "horizon-dualsense", @@ -1413,6 +1413,18 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-client-input" +version = "0.1.0" +dependencies = [ + "arboard", + "horizon-client-core", + "horizon-dualsense", + "horizon-theme", + "png", + "winit", +] + [[package]] name = "horizon-command" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 933901dce..967ce08e8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,7 @@ members = [ "crates/horizon-world", "crates/horizon-client", "crates/horizon-client-core", + "crates/horizon-client-input", "crates/horizon-command", "crates/horizon-server-files", "crates/horizon-server", diff --git a/crates/horizon-client-input/Cargo.toml b/crates/horizon-client-input/Cargo.toml new file mode 100644 index 000000000..e1d7cf72b --- /dev/null +++ b/crates/horizon-client-input/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "horizon-client-input" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.90" +description = "The client's input layer: key bindings and their names, mouse, controllers, clipboard and window options" + +[dependencies] +horizon-client-core = { path = "../horizon-client-core" } +winit = "0.30.13" +# The window icon. +horizon-theme = { path = "../horizon-theme" } +png = "0.18" +arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } +# The DualSense's trigger effects (the `controllers` feature). +horizon-dualsense = { path = "../horizon-dualsense", optional = true } + +[features] +controllers = ["dep:horizon-dualsense"] + +[lints] +workspace = true diff --git a/crates/horizon-client/src/clipboard.rs b/crates/horizon-client-input/src/clipboard.rs similarity index 100% rename from crates/horizon-client/src/clipboard.rs rename to crates/horizon-client-input/src/clipboard.rs diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client-input/src/gamepad.rs similarity index 100% rename from crates/horizon-client/src/gamepad.rs rename to crates/horizon-client-input/src/gamepad.rs diff --git a/crates/horizon-client/src/input.rs b/crates/horizon-client-input/src/input.rs similarity index 100% rename from crates/horizon-client/src/input.rs rename to crates/horizon-client-input/src/input.rs diff --git a/crates/horizon-client/src/interaction_input.rs b/crates/horizon-client-input/src/interaction_input.rs similarity index 100% rename from crates/horizon-client/src/interaction_input.rs rename to crates/horizon-client-input/src/interaction_input.rs diff --git a/crates/horizon-client/src/key_names.rs b/crates/horizon-client-input/src/key_names.rs similarity index 100% rename from crates/horizon-client/src/key_names.rs rename to crates/horizon-client-input/src/key_names.rs diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client-input/src/keybinds.rs similarity index 100% rename from crates/horizon-client/src/keybinds.rs rename to crates/horizon-client-input/src/keybinds.rs diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client-input/src/keymapping.rs similarity index 100% rename from crates/horizon-client/src/keymapping.rs rename to crates/horizon-client-input/src/keymapping.rs diff --git a/crates/horizon-client-input/src/lib.rs b/crates/horizon-client-input/src/lib.rs new file mode 100644 index 000000000..53d8f889a --- /dev/null +++ b/crates/horizon-client-input/src/lib.rs @@ -0,0 +1,14 @@ +//! The client's input layer, below gameplay and screens: key bindings and their +//! names, toggle keys, mouse settings, controllers, the clipboard and window +//! options. horizon-client re-exports each module under its old path +//! (`horizon_client::keybinds`, ...). +#![forbid(unsafe_code)] +pub mod clipboard; +pub mod gamepad; +pub mod input; +pub mod interaction_input; +pub mod key_names; +pub mod keybinds; +pub mod keymapping; +pub mod mouse; +pub mod window; diff --git a/crates/horizon-client/src/mouse.rs b/crates/horizon-client-input/src/mouse.rs similarity index 100% rename from crates/horizon-client/src/mouse.rs rename to crates/horizon-client-input/src/mouse.rs diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client-input/src/window.rs similarity index 100% rename from crates/horizon-client/src/window.rs rename to crates/horizon-client-input/src/window.rs diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 5611edbc9..a3a047176 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -10,6 +10,7 @@ description = "Horizon native development client" [dependencies] horizon-assets = { path = "../horizon-assets" } horizon-client-core = { path = "../horizon-client-core" } +horizon-client-input = { path = "../horizon-client-input" } horizon-command = { path = "../horizon-command" } horizon-core = { path = "../horizon-core" } # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). @@ -54,7 +55,6 @@ horizon-theme = { path = "../horizon-theme" } # the anonymous "I'm playing" ping the game sends itself (`heartbeat.rs`). horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] } horizon-bench = { path = "../horizon-bench" } -arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } # Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input); the `controllers` feature. gilrs = { version = "0.11", optional = true } @@ -88,7 +88,7 @@ default = ["audio", "controllers"] # Linux: the server build (`--no-default-features`, released as horizon-engine; docs/server.md). audio = ["dep:cpal"] # Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. -controllers = ["dep:gilrs", "dep:horizon-dualsense"] +controllers = ["dep:gilrs", "dep:horizon-dualsense", "horizon-client-input/controllers"] # Runs code mods (wasmtime and cranelift: a quarter of a clean build). On in every release build # (release.yml); the tests and probes don't need it. Content mods load without it. mods = ["horizon-mods/runtime"] diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index fa5ef1c4d..f2ce492f5 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -32,7 +32,6 @@ pub mod cauldron; pub mod chat; pub mod chunk; pub mod chunk_map; -pub mod clipboard; pub mod clock; pub mod clouds; pub mod collisions; @@ -74,7 +73,6 @@ pub mod fog; pub mod font; pub mod friends_screen; pub mod game_mode_switcher; -pub mod gamepad; pub mod gfx; pub mod gizmos; pub mod gossip; @@ -88,8 +86,6 @@ pub mod hud; pub mod hud_layout; pub mod hud_overlays; pub mod hunger; -pub mod input; -pub mod interaction_input; pub mod inv_sort; pub mod inventory_effects; pub mod item_data; @@ -98,9 +94,6 @@ pub mod item_sync; pub mod item_tooltip; pub mod items; pub mod java_text; -pub mod key_names; -pub mod keybinds; -pub mod keymapping; pub mod lan; pub mod landing; pub mod level_loading; @@ -120,7 +113,6 @@ pub mod mod_list; mod model_library; pub mod models; pub mod motion; -pub mod mouse; pub mod moved_extras; pub mod multiplayer; pub mod music; @@ -190,7 +182,6 @@ pub mod vault; pub mod weather; pub mod widgets; pub mod win_screen; -pub mod window; pub mod world; pub mod world_spawn; pub mod worldborder; @@ -206,4 +197,13 @@ pub use horizon_client_core::nbt_path; pub use horizon_client_core::scoreboard; pub use horizon_client_core::snbt; pub use horizon_client_core::text; +pub use horizon_client_input::clipboard; +pub use horizon_client_input::gamepad; +pub use horizon_client_input::input; +pub use horizon_client_input::interaction_input; +pub use horizon_client_input::key_names; +pub use horizon_client_input::keybinds; +pub use horizon_client_input::keymapping; +pub use horizon_client_input::mouse; +pub use horizon_client_input::window; pub use horizon_command as command; diff --git a/docs/controllers.md b/docs/controllers.md index c2ac6b5d3..b94e07b9c 100644 --- a/docs/controllers.md +++ b/docs/controllers.md @@ -25,7 +25,7 @@ Select/Start). No second windowing or event stack: gilrs is polled once per loop iteration next to winit's events. - The pure logic (mapping table, deadzones and curves, button edges, the - settings file, glyph choice) lives in `crates/horizon-client/src/gamepad.rs` + settings file, glyph choice) lives in `crates/horizon-client-input/src/gamepad.rs` and is unit-tested. The game owns a thin gilrs backend and applies actions. - Controller actions go through the same path a keyboard key takes after rebinding: an action names a vanilla key mapping (`key.jump`, `key.attack`, diff --git a/tools/test_frame_limiter_parity.py b/tools/test_frame_limiter_parity.py index 1ff2099be..1e1fdfd75 100644 --- a/tools/test_frame_limiter_parity.py +++ b/tools/test_frame_limiter_parity.py @@ -62,7 +62,7 @@ def main(): 'real OS sleep accuracy is outside the comparison.') harness.differential( 'rust-frame-limiter-parity', 'VanillaFrameLimiterOracle', 'frame_limiter_probe', make_cases, scope, - sources=[lab.ROOT / 'crates/horizon-client/src/window.rs']) + sources=[lab.ROOT / 'crates/horizon-client-input/src/window.rs']) if __name__ == '__main__': diff --git a/tools/test_interaction_input_parity.py b/tools/test_interaction_input_parity.py index 1aa34a73f..1944a2ac7 100644 --- a/tools/test_interaction_input_parity.py +++ b/tools/test_interaction_input_parity.py @@ -43,7 +43,7 @@ def main(): "Includes passing entity interactions over solid blocks: only the held " "item may be tried afterward. " "Game-mode side effects and world simulation are controlled fixtures.", - sources=[lab.ROOT / "crates/horizon-client/src/interaction_input.rs", + sources=[lab.ROOT / "crates/horizon-client-input/src/interaction_input.rs", lab.ROOT / "crates/horizon-client/src/game/remote.rs", lab.ROOT / "crates/horizon-client/src/game/hand.rs", lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java"]) diff --git a/tools/test_local_input_parity.py b/tools/test_local_input_parity.py index c50087138..6d46dcf29 100644 --- a/tools/test_local_input_parity.py +++ b/tools/test_local_input_parity.py @@ -35,7 +35,7 @@ def main(): build=lab.LOCAL/'rust-local-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaLocalInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/input_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client-input/src/input.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/input_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) diff --git a/tools/test_options_parity.py b/tools/test_options_parity.py index e99f67a44..82bc5b9ec 100644 --- a/tools/test_options_parity.py +++ b/tools/test_options_parity.py @@ -189,8 +189,8 @@ def main(): harness.differential( 'rust-options-parity', 'VanillaOptionsOracle', 'options_probe', make_cases, scope, sources=[lab.ROOT / 'crates/horizon-client/src/options_file.rs', lab.ROOT / 'crates/horizon-client/src/options_fixes.rs', - lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client/src/key_names.rs', - lab.ROOT / 'crates/horizon-client/src/keybinds.rs']) + lab.ROOT / 'crates/horizon-client/src/java_text.rs', lab.ROOT / 'crates/horizon-client-input/src/key_names.rs', + lab.ROOT / 'crates/horizon-client-input/src/keybinds.rs']) if __name__ == '__main__': diff --git a/tools/test_sprint_input_parity.py b/tools/test_sprint_input_parity.py index b2b86b7c2..d89530826 100644 --- a/tools/test_sprint_input_parity.py +++ b/tools/test_sprint_input_parity.py @@ -40,7 +40,7 @@ def main(): build=lab.LOCAL/'rust-sprint-input';build.mkdir(exist_ok=True) report=build/'report.json';report.unlink(missing_ok=True) oracle=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java' - sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/sprint_probe.rs'] + sources=[Path(__file__),lab.ROOT/'tools/test_rust_parity.py',lab.ROOT/'tools/test_model_baking_parity.py',lab.ROOT/'tools/lab.py',oracle,lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock',lab.ROOT/'crates/horizon-client/Cargo.toml',lab.ROOT/'crates/horizon-client-input/src/input.rs',lab.ROOT/'crates/horizon-client/src/sprint.rs',lab.ROOT/'crates/horizon-client/src/lib.rs',lab.ROOT/'crates/horizon-client/examples/probe/sprint_probe.rs'] tested=base.source_hashes(sources) def run(command,name): with (build/(name+'.log')).open('w') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=600,stdout=log,stderr=subprocess.STDOUT) diff --git a/tools/test_toggle_keys_parity.py b/tools/test_toggle_keys_parity.py index a5d2b0500..07e9523ff 100644 --- a/tools/test_toggle_keys_parity.py +++ b/tools/test_toggle_keys_parity.py @@ -69,7 +69,7 @@ def main(): 'not exercised; KeyboardInput then reads isDown as the sprint and local input harnesses compare.') harness.differential( 'rust-toggle-keys-parity', 'VanillaToggleKeysOracle', 'toggle_keys_probe', make_cases, scope, - sources=[lab.ROOT / 'crates/horizon-client/src/keymapping.rs']) + sources=[lab.ROOT / 'crates/horizon-client-input/src/keymapping.rs']) if __name__ == '__main__': From eb664d50c1272b93af67759bd547c2b8b907a48f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:04:38 +0100 Subject: [PATCH 181/221] pr_ready: blocks.rs and items.rs live in horizon-items now Co-Authored-By: Claude Opus 5.5 --- tools/pr_ready.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tools/pr_ready.py b/tools/pr_ready.py index b741e475e..d4b97023f 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -292,8 +292,7 @@ def mod_features(crates): # What horizon-client's full content-root tests load (mod_content_tests.rs). They take minutes on prepared data, so # they are #[ignore]d and run here only when one of these changes. -CONTENT_ROOT = ("crates/horizon-client/src/mod_content", "crates/horizon-client/src/assets.rs", - "crates/horizon-client/src/blocks.rs", "crates/horizon-client/src/items.rs", "crates/horizon-items/", +CONTENT_ROOT = ("crates/horizon-client/src/mod_content", "crates/horizon-client/src/assets.rs", "crates/horizon-items/", "crates/horizon-mods/", "crates/horizon-assets/") CONTENT_ROOT_TESTS = "cargo test --locked -p horizon-client --features horizon-client/mods --lib mod_content::tests:: -- --ignored" From 8648470c475f409d171efc5b72a218f56aa58f94 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:06:54 +0100 Subject: [PATCH 182/221] rustfmt the merged item_data.rs line Co-Authored-By: Claude Opus 5.5 --- crates/horizon-items/src/item_data.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-items/src/item_data.rs b/crates/horizon-items/src/item_data.rs index c7a608d24..aefc5f23d 100644 --- a/crates/horizon-items/src/item_data.rs +++ b/crates/horizon-items/src/item_data.rs @@ -323,7 +323,9 @@ fn read_text(t: &Tag) -> Option { // this), so flatten the whole component instead of reading one key. // ComponentSerialization.CODEC also takes a list (its first element // styling the rest), as servers behind ViaVersion send book pages. - Tag::Compound(_) | Tag::List(_) => Some(horizon_client_core::component::name_text(t).plain()), + Tag::Compound(_) | Tag::List(_) => { + Some(horizon_client_core::component::name_text(t).plain()) + } _ => None, } } From 604025a53b910c11ca06083aa501cd207a4793f4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 09:10:48 +0100 Subject: [PATCH 183/221] Leave the default (temperate) variants out of the pairing data Pig, cow, chicken, frog and zombie nautilus define DATA_VARIANT_ID as their registry's TEMPERATE, so vanilla's getNonDefaultValues leaves it out of the add packet; server_entities caught the extra entry. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index f50852db3..d2bedf19f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -191,10 +191,18 @@ fn mob_variant_meta( "minecraft:zombie_nautilus_variant", ), }; + // Each registry's default (`define(DATA_VARIANT_ID, ... TEMPERATE)`) + // stays out of the pairing data, as other default values do. let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant); - if let Some(v) = id(registry, name.trim_start_matches("minecraft:")) { + let name = name.trim_start_matches("minecraft:"); + if let Some(v) = id(registry, name) + && name != "temperate" + { meta.push((index, serializer, Value::Id(v))); } + if let Some(v) = id(registry, "temperate") { + defaults.push((index, serializer, Value::Id(v))); + } } // Rabbit.DATA_TYPE_ID (after AgeableMob's two) and // Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and From 50cd5576f9fcaedd7373535afa1dbf4f94b6712c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:06:03 +0100 Subject: [PATCH 184/221] Clear a flying player's fall distance on the server tick --- crates/horizon-client/src/game/lan_actions.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ef177d26d..c7bd59f68 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -2211,6 +2211,7 @@ impl Game<'_> { let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; let (sneaking, sleeping) = (g.sneaking, g.sleeping); + let riding = g.vehicle.is_some(); let mut soul = None; let events = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); @@ -2230,6 +2231,12 @@ impl Game<'_> { w.player.health.advance_clock(); let _ = w.fluid_base_tick(); w.player.ground.on_ground = from_ground; + // Player.aiStep: a flying player that isn't riding starts every tick + // with no fall distance, so flying down in creative and switching to + // survival lands without the flight's distance. + if w.player.flying && !riding { + w.player.fall_distance = 0.0; + } let travelled: Vec<[f64; 3]> = moves.iter().map(|m| m.0).collect(); // Entity.move's movementThisTick: each move, from where the // tick's first one started. From a23a7ec35af7afadf309ba240ac5843cf0f45c32 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:06:35 +0100 Subject: [PATCH 185/221] Drop the whole stack on Ctrl+Q by the physical Control key only --- crates/horizon-client/src/game/remote.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e41aca43b..3dacecebd 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4695,7 +4695,9 @@ impl Game<'_> { match key { KeyCode::KeyF if !self.spectator() => self.remote_swap_hands(), KeyCode::KeyQ if !self.spectator() => { - let all = self.keys.contains(&KeyCode::ControlLeft); + // Minecraft.hasControlDown: the physical keys, so a toggled + // sprint on Left Control does not make Q drop the stack. + let all = self.has_control_down(); self.remote_drop(all); } KeyCode::KeyE if self.riding_mount_with_menu() => { From 377fecbf7914e49fc3bdceece33252b234db599c Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:07:53 +0100 Subject: [PATCH 186/221] Draw a quad over fully opaque texels without the alpha cutout A dirt path's side faces skip the clear top row of their texture, but the cutout still ran on them: mip filtering blended that row into the top edge and dropped it. Vanilla bakes each quad's layer from the texels under its UVs, so these quads are solid. --- crates/horizon-client/src/mesher.rs | 7 ++++--- crates/horizon-client/src/models/catalog.rs | 4 +++- crates/horizon-client/src/sprites.rs | 23 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 48d2f08bd..74a117d08 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -55,7 +55,7 @@ pub struct TerrainVertex { /// UV within the sprite, `UV_STEPS` per unit (`TerrainVertex::new`, /// `terrain.wgsl`'s `terrain_uv`). pub(crate) uv: [u16; 2], - /// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves. + /// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves and quads over opaque texels. pub layer: u16, /// Smooth light, 16x fixed point: sky in the low byte, block in the high one. pub light: u16, @@ -890,8 +890,9 @@ impl Mesher<'_> { target.push(TerrainVertex::new( [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], q.uv[i], - // Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout. - if !self.cutout_leaves && state.leaves { + // Opaque leaves (forceOpaque) and quads over opaque texels draw in the + // solid layer: no alpha cutout (a dirt path's side skips its clear top row). + if face.opaque && !face.translucent || !self.cutout_leaves && state.leaves { face.layer as u16 | OPAQUE_LAYER } else { face.layer as u16 diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 2e6326c40..c02e97240 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -28,6 +28,8 @@ use std::{ pub struct BakedFace { pub quad: ModelQuad, pub layer: u32, + /// The texels under the quad's UVs are all opaque (`SpriteContents.computeTransparency`): + /// drawn in the solid layer without an alpha test. pub opaque: bool, /// Fractional alpha: drawn in the sorted translucent pass. pub translucent: bool, @@ -230,9 +232,9 @@ impl StateModels { Ok(BakedFace { translucent: quad.material.force_translucent || sprites.translucent[layer as usize], + opaque: sprites.region_opaque(layer, &quad.uv), quad, layer, - opaque: sprites.opaque[layer as usize], }) }) .collect::>()?; diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index b720c5bfd..0d5871915 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -115,6 +115,29 @@ impl Sprites { pub fn count(&self) -> usize { self.native.len() } + /// `SpriteContents.computeTransparency(u0, v0, u1, v1)` is NONE: every texel under + /// the quad's UV box is fully opaque in every frame, so the quad needs no alpha test. + pub fn region_opaque(&self, layer: u32, uv: &[[f32; 2]; 4]) -> bool { + if self.opaque[layer as usize] { + return true; + } + let (side, frames, _) = &self.native[layer as usize]; + let side = *side as usize; + let range = |axis: usize| { + let lo = uv.iter().map(|p| p[axis]).fold(f32::INFINITY, f32::min); + let hi = uv.iter().map(|p| p[axis]).fold(f32::NEG_INFINITY, f32::max); + let clamp = |v: f32| (v.max(0.0) as usize).min(side); + clamp((lo * side as f32).floor())..clamp((hi * side as f32).ceil()) + }; + let (columns, rows) = (range(0), range(1)); + frames.iter().all(|frame| { + rows.clone().all(|y| { + columns + .clone() + .all(|x| frame[(y * side + x) * 4 + 3] == 255) + }) + }) + } /// Lay every layer out at one size: the largest texture's (resource packs /// may ship 32x, 64x... textures, like vanilla's stitched atlas), rounded /// up to a power of two and limited to [`MAX_ARRAY_BYTES`]. Smaller From 5d68512994628613d8962c1ce446d11a63a376e9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:08:07 +0100 Subject: [PATCH 187/221] Keep the body facing forward when a player walks backwards --- crates/horizon-client/src/game/lan.rs | 14 +++++++++++--- crates/horizon-client/src/game/perspective.rs | 10 +++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index a0f99bfca..1c9ee2dc1 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1520,10 +1520,18 @@ impl Game<'_> { m.head_yaw = g.head_yaw; m.head_pitch = g.pitch; let mut target = m.body_yaw; - if dx * dx + dz * dz > 0.002_500_000_2 { - target = (dz.atan2(dx) as f32).to_degrees() - 90.0; - } let wrap = |a: f32| (a + 180.0).rem_euclid(360.0) - 180.0; + if dx * dx + dz * dz > 0.002_500_000_2 { + // LivingEntity.tick: walking backwards the body faces away + // from the walk direction, not along it. + let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0; + let facing = (wrap(g.yaw) - walk).abs(); + target = if 95.0 < facing && facing < 265.0 { + walk - 180.0 + } else { + walk + }; + } m.body_yaw += wrap(target - m.body_yaw) * 0.3; let diff = wrap(g.yaw - m.body_yaw); if diff.abs() > 50.0 { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index caf49883b..2956f8162 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -372,7 +372,15 @@ impl Game<'_> { m.head_pitch = pitch; let mut target = m.body_yaw; if dx * dx + dz * dz > 0.002_500_000_2 { - target = (dz.atan2(dx) as f32).to_degrees() - 90.0; + // LivingEntity.tick: walking backwards the body faces away from + // the walk direction, not along it. + let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0; + let facing = (wrap(yaw) - walk).abs(); + target = if 95.0 < facing && facing < 265.0 { + walk - 180.0 + } else { + walk + }; } if swinging { target = yaw; From a05dc35c3906ed7b2364e4de18b9474222578059 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:08:49 +0100 Subject: [PATCH 188/221] Launch a Riptide trident on a server's client when the use is released --- crates/horizon-client/src/game/remote.rs | 13 ++++++++++++- crates/horizon-client/src/game/trident.rs | 17 ++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e41aca43b..588fbfdeb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -5751,7 +5751,18 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_ direction: 0, sequence: 0, })); - self.0.using = None; + // MultiPlayerGameMode.releaseUsingItem also runs `Item.releaseUsing` here: the + // player moves by itself, so a Riptide launch happens on the client. + let hand = self.0.used_hand(); + if let Some((slot, ticks)) = self.0.using.take() + && let Some(hand) = hand + && self + .0 + .stack_in(slot) + .is_some_and(|s| &*s.item == "minecraft:trident") + { + self.0.with_hand(hand, |g| g.release_trident(ticks)); + } } fn start_attack(&mut self) -> bool { self.0.remote_start_attack() diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 9d6b3f9c5..0ab873f40 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -240,7 +240,12 @@ impl Game<'_> { if !self.in_water_or_rain() || self.riding.is_some() { return; } - self.hurt_held_without_breaking(1); + // `hurtWithoutBreaking` and the sound belong to the server; a server's + // client only launches. + let server_client = self.remote.is_some(); + if !server_client { + self.hurt_held_without_breaking(1); + } // trident_spin_attack_strength: 1.5 + 0.75 per level above the first. let strength = 1.5 + 0.75 * (riptide as f32 - 1.0); let d = view_vector(self.yaw, self.pitch); @@ -257,8 +262,14 @@ impl Game<'_> { p.position.y += 1.2; } } - let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3)); - self.audio.play(&sound, at, 1.0, 1.0); + if !server_client { + let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3)); + self.audio.play(&sound, at, 1.0, 1.0); + } + return; + } + // The server throws the trident. + if self.remote.is_some() { return; } // hurtWithoutBreaking (Unbreaking applies), then the thrown copy. From 3c85d2558bddad95e736215b5dda428ed2396297 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:11:36 +0100 Subject: [PATCH 189/221] Tell a server player's client about its velocity after a mace smash --- crates/horizon-client/src/game/lan_actions.rs | 18 +++++++++++++++--- crates/horizon-client/src/game/mace.rs | 3 +++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ef177d26d..1a1ebaadb 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1567,9 +1567,21 @@ impl Game<'_> { if self.look_at_entity(host, gi, id, None).is_none() { return; } - self.as_guest(host, conn, |g| { - g.attack(); - }); + // A mace's smash sets the attacker's velocity and sends it at once, before the + // Wind Burst's push (MaceItem.hurtEnemy, then the post-attack effects). + let sent = self + .as_guest(host, conn, |g| { + let marked = g + .player + .as_mut() + .is_some_and(|p| std::mem::take(&mut p.health.sync_velocity)); + g.attack(); + let p = g.player.as_mut()?; + let sent = std::mem::replace(&mut p.health.sync_velocity, marked); + sent.then_some(p.velocity) + }) + .flatten(); + self.send_guest_motion(host, conn, sent); // The mob now answers to this guest (game/lan_mobs.rs). if let Ok(id) = u32::try_from(id) { host.mob_players.insert(id, conn); diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 34c968980..b7d04b265 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -181,6 +181,9 @@ impl Game<'_> { return; }; p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z); + // A server player's client is told (ClientboundSetEntityMotionPacket): it moves by + // itself, so without it a Wind Burst's push would add to the speed of the fall. + p.health.sync_velocity = true; // calculateImpactPosition: an earlier impact below the player stays. let impact = match p.impulse.impact_position { Some(at) if at.y <= p.position.y => at, From e314c2fa81e3e2c76958611c473bccb1497585ea Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 11:13:14 +0100 Subject: [PATCH 190/221] Implement the spear's left-click jab and the Lunge enchantment --- .../src/game/enchant_effects.rs | 100 ++++++++++++++++ crates/horizon-client/src/game/hand.rs | 23 +++- crates/horizon-client/src/game/lan_actions.rs | 33 ++++++ crates/horizon-client/src/game/remote.rs | 30 ++++- crates/horizon-client/src/game/spear.rs | 108 +++++++++++++++--- crates/horizon-client/src/spear.rs | 41 +++++-- 6 files changed, 301 insertions(+), 34 deletions(-) diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 5f021a43f..2db9ba576 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -197,6 +197,106 @@ impl Game<'_> { } self.post_attack_bursts(&held, &kind); } + /// `EnchantmentHelper.doPostPiercingAttackEffects`: the + /// `minecraft:post_piercing_attack` effects of the weapon in hand after a + /// jab (Lunge's dash). + pub(super) fn post_piercing_attack(&mut self) { + let Some(held) = self.held().cloned() else { + return; + }; + let mut effects = Vec::new(); + for (id, level) in held.enchantments() { + let Some(def) = self.res.stations().enchantments.get(id) else { + continue; + }; + for entry in def.effects["minecraft:post_piercing_attack"] + .as_array() + .into_iter() + .flatten() + { + effects.push((*level, entry["effect"].clone())); + } + } + // Lunge's requirements: not riding, gliding or in water, and a + // player outside creative with at least 7 food. + let Some(p) = self.player.as_ref() else { + return; + }; + if effects.is_empty() + || self.riding.is_some() + || p.fall_flying + || p.fluids.was_touching_water + || !(self.creative || p.health.food.food >= 7) + { + return; + } + for (level, effect) in effects { + self.apply_piercing_effect(&effect, level); + } + } + /// One `post_piercing_attack` effect on the player: `AllOf`, + /// `ChangeItemDamage`, `ApplyExhaustion`, `ApplyEntityImpulse` and + /// `PlaySoundEffect`. + fn apply_piercing_effect(&mut self, effect: &serde_json::Value, level: u32) { + let amount = || level_value(&effect["amount"], level); + match effect["type"].as_str() { + Some("minecraft:all_of") => { + for e in effect["effects"].as_array().into_iter().flatten() { + self.apply_piercing_effect(e, level); + } + } + Some("minecraft:change_item_damage") => self.damage_held(amount() as u32), + Some("minecraft:apply_exhaustion") => { + if let Some(p) = self.player.as_mut() { + p.cause_food_exhaustion(amount()); + } + } + // The direction turned by the look (`Entity.getLookQuaternion`: + // pitch about x, then yaw about y), scaled by coordinate_scale + // and the magnitude, added to the velocity (the guest's client + // is told of it by `guest_hit_by`). + Some("minecraft:apply_impulse") => { + let vec3 = |key: &str| [0, 1, 2].map(|i| effect[key][i].as_f64().unwrap_or(0.0)); + let (d, scale) = (vec3("direction"), vec3("coordinate_scale")); + let magnitude = f64::from(level_value(&effect["magnitude"], level)); + let (yaw, pitch) = ( + f64::from(self.yaw).to_radians(), + f64::from(self.pitch).to_radians(), + ); + let (y1, z1) = ( + d[1] * pitch.cos() - d[2] * pitch.sin(), + d[1] * pitch.sin() + d[2] * pitch.cos(), + ); + let impulse = horizon_core::geometry::Vec3::new( + (d[0] * yaw.cos() - z1 * yaw.sin()) * scale[0] * magnitude, + y1 * scale[1] * magnitude, + (d[0] * yaw.sin() + z1 * yaw.cos()) * scale[2] * magnitude, + ); + if let Some(p) = self.player.as_mut() { + p.velocity = p.velocity.add_vector(impulse); + } + } + // The sound for the level (a list picks by level), heard by all. + Some("minecraft:play_sound") => { + let sounds: Vec<&str> = match &effect["sound"] { + serde_json::Value::Array(list) => { + list.iter().filter_map(|s| s.as_str()).collect() + } + one => one.as_str().into_iter().collect(), + }; + let index = (level as usize).saturating_sub(1); + if let Some(sound) = sounds.get(index.min(sounds.len().saturating_sub(1))) { + let float = |key: &str| effect[key].as_f64().unwrap_or(1.0) as f32; + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.audio.play(sound, at, float("volume"), float("pitch")); + } + } + _ => {} + } + } /// `minecraft:post_attack` explode effects on the attacker (wind burst): /// a burst at the player's feet that only knocks back and triggers /// blocks (`ExplodeEffect` with `block_interaction: trigger`). diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index d91d3b979..524db061f 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -331,6 +331,12 @@ struct GameHands<'g, 'a> { error: Option>, } impl GameHands<'_, '_> { + /// The main-hand item's `kinetic_weapon` and `piercing_weapon`, a spear's. + fn attack_kinetic(&self) -> Option { + self.game + .held() + .and_then(|s| horizon_client::spear::Kinetic::of(&s.item)) + } fn keep(&mut self, r: Result<()>) { if let Err(e) = r && self.error.is_none() @@ -398,18 +404,27 @@ impl HandWorld for GameHands<'_, '_> { self.game.creative } fn cannot_attack(&mut self) -> bool { - false + let ticker = self.game.hand_strength.ticker; + self.game.cannot_attack_with_item(ticker, 0) } fn piercing_weapon(&mut self) -> bool { - false + self.attack_kinetic().is_some() } fn attack_animation(&mut self) -> SwingAnimation { - SwingAnimation::DEFAULT + self.attack_kinetic() + .map_or(SwingAnimation::DEFAULT, |k| k.attack_animation()) } fn interact_animation(&mut self, _: Hand) -> SwingAnimation { SwingAnimation::DEFAULT } - fn piercing_attack(&mut self, _: SwingAnimation) {} + fn piercing_attack(&mut self, _: SwingAnimation) { + // The server's part (`PiercingWeapon.attack`), then the client's: + // the sound `MultiPlayerGameMode.piercingAttack` plays. + if let Some(sound) = self.game.jab() { + self.game.play_at_feet(sound); + } + self.game.hand_strength.reset_attack(); + } fn attack_entity(&mut self) -> bool { self.game.attack() } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 4aeb25563..8a518acde 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1027,6 +1027,8 @@ impl Game<'_> { g.player_on_equip("mainhand", offhand.as_ref(), main.as_ref()); }); } + // STAB: `PiercingWeapon.attack` of a left click with a spear. + 8 if !spectator => self.guest_jab(host, conn), _ => {} }, S::SetCarriedItem(p) => { @@ -1514,6 +1516,37 @@ impl Game<'_> { Some((centre, eye)) } + /// `ServerGamePacketListenerImpl.handlePlayerAction` for STAB: the spear in + /// the guest's main hand jabs once its charge allows it (with five ticks + /// of tolerance). The guest's client is sent the dash Lunge gave them. + fn guest_jab(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let at = g.position; + // ServerPlayer.getKnownMovement: the move their client just sent. + let movement = g + .moves + .last() + .map_or(Vec3::ZERO, |m| Vec3::new(m.0[0], m.0[1], m.0[2])); + let sound = self + .guest_hit_by(host, conn, |g| { + g.known_movement = movement; + if g.cannot_attack_with_item(g.attack_ticks as i32, 5) { + None + } else { + g.jab() + } + }) + .flatten(); + // PiercingWeapon.makeSound: `playSound(causer, ...)`, so the guest's + // own client plays it. + if let Some(name) = sound { + let source = horizon_client::settings::sound_source(name) as i32; + host.hub.sound(name, at, 1.0, 1.0, source, Some(conn)); + } + } + fn guest_attack(&mut self, host: &mut LanHost, conn: u32, id: i32) { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3707b9945..4871d4f8a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -4564,6 +4564,28 @@ impl Game<'_> { if self.spectator() { return true; } + // A spear jabs (`MultiPlayerGameMode.piercingAttack`): the server + // stabs, this client swings, plays the sound and starts its charge + // again. + if let Some(kinetic) = self + .held() + .and_then(|s| horizon_client::spear::Kinetic::of(&s.item)) + { + if self.cannot_attack_with_item(self.hand_strength.ticker, 0) { + return false; + } + // ServerboundPlayerActionPacket.Action.STAB. + self.send(S::PlayerAction(play::PlayerAction { + action: 8, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + self.hand_strength.reset_attack(); + self.swing_hand(Hand::Main, kinetic.attack_animation()); + self.play_at_feet(kinetic.attack_sound); + return true; + } let mut instant = false; // A ghast's fireball or a wind charge nearer than any mob: the // server turns it (game/deflect.rs). @@ -4614,7 +4636,13 @@ impl Game<'_> { if !down { self.clicks.miss_time = 0; } - if self.clicks.miss_time > 0 || self.using.is_some() { + // A piercing weapon neither breaks blocks nor swings on its own. + if self.clicks.miss_time > 0 + || self.using.is_some() + || self + .held() + .is_some_and(|s| horizon_client::spear::Kinetic::of(&s.item).is_some()) + { return; } let entity = self.entity_targeted(); diff --git a/crates/horizon-client/src/game/spear.rs b/crates/horizon-client/src/game/spear.rs index 13df3aed9..f7d1b5e4e 100644 --- a/crates/horizon-client/src/game/spear.rs +++ b/crates/horizon-client/src/game/spear.rs @@ -5,10 +5,13 @@ //! attacker's own speed, and each condition runs out after its time //! (`Item.use`, `ItemStack.onUseTick`, `KineticWeapon.damageEntities`, //! `Player.stabAttack`). The hit's feedback (`onKineticHit`) reaches the -//! players around as entity event 2. +//! players around as entity event 2. A left click jabs instead +//! (`PiercingWeapon.attack`), which Lunge turns into a dash. use super::{Game, view_vector}; use horizon_client::{ + attack_strength::delay, collisions::SceneCollisions, + first_person::Hand, items::ItemStack, mobs::Damage, spear::{HIT_FEEDBACK_TICKS, Kinetic, REACH}, @@ -115,6 +118,28 @@ impl Game<'_> { hits } + /// `ProjectileUtil.getHitEntitiesAlong` with the spear's `AttackRange`: the + /// mobs along the view from the minimum reach to the maximum plus the + /// attacker's own movement, none when a block is closer than the minimum. + fn stab_targets(&self, eye: Vec3, look: Vec3, movement: Vec3) -> Vec { + // AttackRange.effectiveMinRange and effectiveMaxRange for a player. + let (min, max) = if self.creative { + (REACH.min_creative, REACH.max_creative) + } else { + (REACH.min, REACH.max) + }; + let from = eye.add_vector(look.scale(f64::from(min))); + let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0))); + // A block closer than the minimum reach takes the whole stab. + if let Some(block) = self.clip_collider(eye, to) { + to = block; + if eye.distance_squared(to) < eye.distance_squared(from) { + return Vec::new(); + } + } + self.mobs_along(from, to, f64::from(REACH.hitbox_margin)) + } + /// `KineticWeapon.damageEntities`: one tick of the spear in use, `ticks` /// ticks into the use. pub(super) fn spear_tick(&mut self, stack: &ItemStack, ticks: u32) { @@ -136,25 +161,10 @@ impl Game<'_> { let look = Vec3::new(look[0], look[1], look[2]); let movement = self.known_player_movement(); let attacker_speed = look.dot(movement.scale(20.0)); - // AttackRange.effectiveMinRange and effectiveMaxRange for a player. - let (min, max) = if self.creative { - (REACH.min_creative, REACH.max_creative) - } else { - (REACH.min, REACH.max) - }; - let from = eye.add_vector(look.scale(f64::from(min))); - let mut to = eye.add_vector(look.scale(f64::from(max) + movement.dot(look).max(0.0))); - // A block closer than the minimum reach takes the whole stab. - if let Some(block) = self.clip_collider(eye, to) { - to = block; - if eye.distance_squared(to) < eye.distance_squared(from) { - return; - } - } let now = self.world.game_time; let actor = self.lan_acting; let mut affected = false; - for i in self.mobs_along(from, to, f64::from(REACH.hitbox_margin)) { + for i in self.stab_targets(eye, look, movement) { let key = (actor, self.mobs[i].id); let recent = self .stabbed @@ -204,9 +214,18 @@ impl Game<'_> { return false; }; let from = [p.position.x, p.position.y, p.position.z]; - // The enchantments' share, with no attack strength scaling for a - // weapon in use. + // The enchantments' share, scaled by the attack strength unless the + // weapon is in use. let magic_boost = self.enchant_damage_bonus(&kind); + let (base_damage, magic_boost) = if self.using.is_none() { + let scale = self.attack_strength_scale(); + ( + base_damage * (0.2 + scale * scale * 0.8), + magic_boost * scale, + ) + } else { + (base_damage, magic_boost) + }; let total = if deals_damage { base_damage + magic_boost } else { @@ -275,6 +294,57 @@ impl Game<'_> { true } + /// `Player.cannotAttackWithItem` for the held item: a spear needs its + /// `minimum_attack_charge` of 1, counting `tolerance` ticks more than the + /// `ticker` ticks charged. + pub(super) fn cannot_attack_with_item(&self, ticker: i32, tolerance: i32) -> bool { + self.held().is_some_and(|s| Kinetic::of(&s.item).is_some()) + && (ticker + tolerance) as f32 / delay(self.main_hand_attack_speed()) < 1.0 + } + + /// `PiercingWeapon.attack` of the spear in the main hand, for a left + /// click: every mob along the view is stabbed, then `postPiercingAttack` + /// (Lunge), the hit sound and the swing. Gives the sound of the jab + /// (`makeSound`), which everyone but the user hears from the server. + pub(super) fn jab(&mut self) -> Option<&'static str> { + let kinetic = self.held().and_then(|s| Kinetic::of(&s.item))?; + let eye = self.eye_position()?; + let eye = Vec3::new(eye[0], eye[1], eye[2]); + let look = view_vector(self.yaw, self.pitch); + let look = Vec3::new(look[0], look[1], look[2]); + // The attack damage attribute. + let damage = 1.0 + + self.attack_item_info().map_or(0.0, |i| i.attack_damage) + + self.effect_attack_bonus(); + let movement = self.known_player_movement(); + let mut hit = false; + for i in self.stab_targets(eye, look, movement) { + hit |= self.stab_mob(i, damage, true, true, false); + } + // Player.onAttack, then postPiercingAttack. + self.attack_ticks = 0; + self.post_piercing_attack(); + if hit { + self.play_at_feet(kinetic.hit_sound); + } + // swingAndResetAttackStrength (ServerPlayer): a swing that starts + // resets the attack strength. + let swings = self.swings_started; + self.swing_hand(Hand::Main, kinetic.attack_animation()); + if self.swings_started != swings { + self.reset_attack_strength(); + } + Some(kinetic.attack_sound) + } + + /// A sound at the player's feet. + pub(super) fn play_at_feet(&mut self, sound: &str) { + if let Some(p) = &self.player { + let at = [p.position.x, p.position.y, p.position.z]; + self.audio.play(sound, Some(at), 1.0, 1.0); + } + } + /// `LivingEntity.onKineticHit` for `entity`: the hit feels (the spear /// moves back, `kinetic_hit_ticks`) and sounds, at most once every ten /// ticks. diff --git a/crates/horizon-client/src/spear.rs b/crates/horizon-client/src/spear.rs index ae6d8f80d..ed32b269a 100644 --- a/crates/horizon-client/src/spear.rs +++ b/crates/horizon-client/src/spear.rs @@ -2,6 +2,7 @@ //! conditions of a stab, `Item.Properties.spear`'s numbers) and //! `SpearAnimations` (how the spear is held in first and third person while //! it charges). +use crate::first_person::SwingAnimation; use glam::{Mat4, Vec3}; use horizon_core::{geometry::trig::Mth, jmath::pow}; use std::f32::consts::PI; @@ -39,6 +40,10 @@ pub struct Kinetic { pub damage_multiplier: f32, pub sound: &'static str, pub hit_sound: &'static str, + /// The `attack_animation` duration, and the `piercing_weapon` sound of a + /// jab. + pub attack_ticks: i32, + pub attack_sound: &'static str, } /// `AttackRange` of a spear: the reach of its stabs. @@ -62,16 +67,17 @@ pub const REACH: Reach = Reach { impl Kinetic { /// The `kinetic_weapon` of a spear item (`Item.Properties.spear`). pub fn of(item: &str) -> Option { - // (damage multiplier, delay, dismount time and speed, knockback time - // and speed, damage time and speed): seconds and blocks per second. - let (multiplier, delay, dismount, knockback, damage) = match item { - "minecraft:wooden_spear" => (0.7, 0.75, (5.0, 14.0), (10.0, 5.1), (15.0, 4.6)), - "minecraft:stone_spear" => (0.82, 0.7, (4.5, 13.0), (9.0, 5.1), (13.75, 4.6)), - "minecraft:copper_spear" => (0.82, 0.65, (4.0, 12.0), (8.25, 5.1), (12.5, 4.6)), - "minecraft:iron_spear" => (0.95, 0.6, (2.5, 11.0), (6.75, 5.1), (11.25, 4.6)), - "minecraft:golden_spear" => (0.7, 0.7, (3.5, 13.0), (8.5, 5.1), (13.75, 4.6)), - "minecraft:diamond_spear" => (1.075, 0.5, (3.0, 10.0), (6.5, 5.1), (10.0, 4.6)), - "minecraft:netherite_spear" => (1.2, 0.4, (2.5, 9.0), (5.5, 5.1), (8.75, 4.6)), + // (attack duration, damage multiplier, delay, dismount time and + // speed, knockback time and speed, damage time and speed): seconds + // and blocks per second. + let (attack, multiplier, delay, dismount, knockback, damage) = match item { + "minecraft:wooden_spear" => (0.65, 0.7, 0.75, (5.0, 14.0), (10.0, 5.1), (15.0, 4.6)), + "minecraft:stone_spear" => (0.75, 0.82, 0.7, (4.5, 13.0), (9.0, 5.1), (13.75, 4.6)), + "minecraft:copper_spear" => (0.85, 0.82, 0.65, (4.0, 12.0), (8.25, 5.1), (12.5, 4.6)), + "minecraft:iron_spear" => (0.95, 0.95, 0.6, (2.5, 11.0), (6.75, 5.1), (11.25, 4.6)), + "minecraft:golden_spear" => (0.95, 0.7, 0.7, (3.5, 13.0), (8.5, 5.1), (13.75, 4.6)), + "minecraft:diamond_spear" => (1.05, 1.075, 0.5, (3.0, 10.0), (6.5, 5.1), (10.0, 4.6)), + "minecraft:netherite_spear" => (1.15, 1.2, 0.4, (2.5, 9.0), (5.5, 5.1), (8.75, 4.6)), _ => return None, }; let wood = item == "minecraft:wooden_spear"; @@ -107,8 +113,23 @@ impl Kinetic { } else { "minecraft:item.spear.hit" }, + attack_ticks: ticks(attack), + attack_sound: if wood { + "minecraft:item.spear_wood.attack" + } else { + "minecraft:item.spear.attack" + }, }) } + + /// The spear's `attack_animation`: a STAB (`SwingAnimationType` 2) as long + /// as its attack duration. + pub fn attack_animation(&self) -> SwingAnimation { + SwingAnimation { + kind: 2, + duration: self.attack_ticks, + } + } } /// `KineticWeapon.HIT_FEEDBACK_TICKS`. From eace14a013c83e9ff1d7f500367f0e49ca95a395 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 11:58:19 +0100 Subject: [PATCH 191/221] rustfmt the step-sound match arms Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 4 +--- crates/horizon-client/src/game/remote.rs | 4 +--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c45ea3a48..35cd657e7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4868,9 +4868,7 @@ impl Game<'_> { for event in events { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), - MotionEvent::Emission { - state, muffled, .. - } => { + MotionEvent::Emission { state, muffled, .. } => { let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, // muffled under the swim sound in water. Whether it plays is diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 0611beb59..4244478ae 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3417,9 +3417,7 @@ impl Game<'_> { let feet = [player.position.x, player.position.y, player.position.z]; for event in events { match event { - horizon_client::motion::MotionEvent::Emission { - state, muffled, .. - } => { + horizon_client::motion::MotionEvent::Emission { state, muffled, .. } => { let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. let (volume, pitch) = if muffled { From fff7116b516a5a4f8ae1322a03f0d39a03cd1d2c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:12:33 +0100 Subject: [PATCH 192/221] Format the chat options or-pattern Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/options_ui.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 2fe25c610..c4091af94 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -540,9 +540,9 @@ impl Opt { Opt::HideLightningFlashes => on_off(s.file.bool("hideLightningFlashes")), Opt::MonochromeLogo => on_off(s.file.bool("darkMojangStudiosBackground")), Opt::HideSplashTexts => on_off(s.file.bool("hideSplashTexts")), - Opt::HideMatchedNames - | Opt::OnlySecureChat - | Opt::SaveChatDrafts => on_off(s.file.bool(self.file_key().unwrap())), + Opt::HideMatchedNames | Opt::OnlySecureChat | Opt::SaveChatDrafts => { + on_off(s.file.bool(self.file_key().unwrap())) + } Opt::NarratorHotkey => on_off(s.file.bool("narratorHotkey")), Opt::RotateWithMinecarts => on_off(s.file.bool("rotateWithMinecart")), Opt::HighContrastBlockOutlines => on_off(s.file.bool("highContrastBlockOutline")), From 3094896ad1c0bd7ac221bb257af55e1127a1702a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:02:29 +0100 Subject: [PATCH 193/221] mob_ai probe: count hits that bring an effect as player hurts The new AttackPlayerWithEffect hit (husk, bee, cave spider...) still hurts the oracle's player, so the probe prints its hurt sound. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/probe/mob_ai_probe.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 5ea0a456b..ca9f566fa 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -567,7 +567,9 @@ fn print_heart( /// The damage of a mob's direct hit on the player (others count as none). fn player_damage(e: &MobEvent) -> f32 { match e { - MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount, + MobEvent::AttackPlayer(amount, _) + | MobEvent::AttackPlayerWithEffect { amount, .. } + | MobEvent::DamagePlayer { amount, .. } => *amount, _ => 0.0, } } @@ -578,7 +580,9 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { return false; }; match e { - MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, + MobEvent::AttackPlayer(amount, _) + | MobEvent::AttackPlayerWithEffect { amount, .. } + | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, // ServerExplosion.hurtEntities: within twice the radius every hit does damage. MobEvent::Explode(at, radius) => { let d = Vec3::new(at[0], at[1], at[2]) From 0d554de016241881c62c75078fb5c27e268107e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:48:09 +0100 Subject: [PATCH 194/221] parity: game_loop records mouse, window and keymapping from the input crate The harness hashed crates/horizon-client/src/{mouse,window,keymapping}.rs, which this branch moves to horizon-client-input, so CI's parity job failed with FileNotFoundError before running it. Co-Authored-By: Claude Opus 5.5 --- tools/test_game_loop_parity.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index f5f5e94a3..6c9224519 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -154,7 +154,8 @@ def main(): 'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.') harness.differential( 'rust-game-loop-parity', 'VanillaGameLoopOracle', 'game_loop_probe', make_cases, scope, - sources=[lab.ROOT / f'crates/horizon-client/src/{name}.rs' for name in ('clock', 'mouse', 'window', 'keymapping')]) + sources=[lab.ROOT / 'crates/horizon-client/src/clock.rs'] + + [lab.ROOT / f'crates/horizon-client-input/src/{name}.rs' for name in ('mouse', 'window', 'keymapping')]) if __name__ == '__main__': From 2af3308892de305bba2e1bdf843db7bc99e6cabb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:01:12 +0100 Subject: [PATCH 195/221] Nightly builds name themselves on the title screen and in reports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A game built by the nightly workflow (HORIZON_NIGHTLY=" ") draws "Nightly · " in the title screen's top-left corner, reports it as its version in crash reports, and logs it as the log's first line, so a bug report that carries the log names the build. Telemetry gets the version the launcher installs it as (nightly--). Releases and source builds are unchanged; only the "Horizon " log line is new for them. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/crash.rs | 19 +++++++++++++--- crates/horizon-client/src/main.rs | 2 ++ crates/horizon-client/src/title.rs | 5 +++++ crates/horizon-core/src/release.rs | 35 ++++++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index e147bfb4c..5490808a1 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -105,9 +105,13 @@ impl Report { } } -/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's -/// crate version; for a build from source, that version alone. +/// The release this binary is (`v0.2.3`); a nightly's label (`Nightly 2026-10-28 · 0c02067`); for a +/// release from before 0.2, its tag and the client's crate version; for a build from source, that +/// version alone. pub fn version() -> String { + if let Some(label) = horizon_core::release::nightly_label() { + return label; + } let version = env!("CARGO_PKG_VERSION"); match (horizon_core::release::RELEASE, release_tag()) { (Some(_), Some(tag)) => tag, @@ -117,8 +121,12 @@ pub fn version() -> String { } /// The release this binary came with: the version release.yml built in (docs/versioning.md), else -/// the folder the launcher installed it in, named after the tag (releases from before 0.2). +/// the folder the launcher installed it in, named after the tag (releases from before 0.2). A +/// nightly is its version as the launcher installs it (`nightly-2026-10-28-0c02067`). pub fn release_tag() -> Option { + if let Some(nightly) = horizon_core::release::nightly_version() { + return Some(nightly); + } if let Some(version) = horizon_core::release::RELEASE { return Some(format!("v{version}")); } @@ -525,6 +533,11 @@ mod tests { #[test] fn a_release_reports_its_built_in_version() { // release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed. + if let Some(label) = horizon_core::release::nightly_label() { + assert_eq!(super::version(), label); + assert_eq!(release_tag(), horizon_core::release::nightly_version()); + return; + } match horizon_core::release::RELEASE { Some(version) => { assert_eq!(release_tag(), Some(format!("v{version}"))); diff --git a/crates/horizon-client/src/main.rs b/crates/horizon-client/src/main.rs index 7144a1670..8d03455af 100644 --- a/crates/horizon-client/src/main.rs +++ b/crates/horizon-client/src/main.rs @@ -23,6 +23,8 @@ fn main() { }; if !help { logging::init(&home, thread); + // The log's first line names the build, so a bug report that carries the log says which one it was. + log::info!("Horizon {}", crash::version()); crash::install(home.clone(), side); } if let Err(error) = game::run() { diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index b2fcfe8f4..d08917303 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -966,6 +966,11 @@ impl Title { } let version = format!("Horizon {} (Rust)", horizon_core::VANILLA_VERSION); batch.text(atlas, &version, 2.0, h - 10.0, u32::MAX, true); + // A nightly names its build in the top-left corner, the one spot no button reaches at any GUI + // scale, so screenshots and reports say which build they come from. + if let Some(nightly) = horizon_core::release::nightly_label() { + batch.text(atlas, &nightly, 2.0, 2.0, u32::MAX, true); + } let notice = "Not affiliated with Mojang or Microsoft"; let tw = HudBatch::text_width(atlas, notice); batch.text(atlas, notice, w - tw - 2.0, h - 10.0, u32::MAX, true); diff --git a/crates/horizon-core/src/release.rs b/crates/horizon-core/src/release.rs index 54a3cb94e..4e7378601 100644 --- a/crates/horizon-core/src/release.rs +++ b/crates/horizon-core/src/release.rs @@ -15,8 +15,43 @@ pub const VERSION: &str = match RELEASE { None => env!("CARGO_PKG_VERSION"), }; +/// A nightly's date and commit (`2026-10-28 0c02067`): nightly-build.yml builds the opt-in Nightly +/// channel with `HORIZON_NIGHTLY` set (docs/release-flow.md). None for a release or a build from source. +pub const NIGHTLY: Option<&str> = match option_env!("HORIZON_NIGHTLY") { + Some(nightly) if !nightly.is_empty() => Some(nightly), + _ => None, +}; + +/// How a nightly names itself where players read it, so their reports say which build they come +/// from: `Nightly 2026-10-28 · 0c02067`. None for any other build. +pub fn nightly_label() -> Option { + NIGHTLY.map(label) +} + +/// A nightly's version as the launcher installs it (`nightly-2026-10-28-0c02067`). +pub fn nightly_version() -> Option { + NIGHTLY.map(|n| format!("nightly-{}", n.replace(' ', "-"))) +} + +fn label(nightly: &str) -> String { + match nightly.split_once(' ') { + Some((date, commit)) => format!("Nightly {date} · {commit}"), + None => format!("Nightly {nightly}"), + } +} + #[cfg(test)] mod tests { + #[test] + fn a_nightly_names_its_date_and_commit() { + assert_eq!( + super::label("2026-10-28 0c02067"), + "Nightly 2026-10-28 · 0c02067" + ); + assert_eq!(super::label("2026-10-28"), "Nightly 2026-10-28"); + assert_eq!(super::nightly_label().is_some(), super::NIGHTLY.is_some()); + } + #[test] fn the_version_is_the_release_or_the_crate() { assert_eq!( From be0a93271f18fe69b3a794b0b006b753a56156d7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:04:41 +0100 Subject: [PATCH 196/221] test: retry ETXTBSY when horizon-server tests run a script they just wrote engine::tests::the_check_runs_the_program failed on CI (verify of #2215) with "can't start: Text file busy (os error 26)". The test writes a shell script and runs it at once; when another test thread forks to spawn a process while the script's write handle is open, the child keeps that handle until it execs, and running the script meanwhile fails with ETXTBSY on Linux. The two engine tests that do this now retry that one error (up to 50 times, 20 ms apart). Test-only change. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-server/src/engine.rs | 42 ++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs index fd7c86321..ce288fdff 100644 --- a/crates/horizon-server/src/engine.rs +++ b/crates/horizon-server/src/engine.rs @@ -315,18 +315,42 @@ mod tests { .unwrap(); std::fs::set_permissions(&game, std::fs::Permissions::from_mode(0o755)).unwrap(); std::fs::write(server.join("server.toml"), "").unwrap(); - let status = spawn( - &std::path::absolute(&game).unwrap(), - &root.join("res"), - &server, - ) - .unwrap() - .wait(); + // ETXTBSY: see `check_written`. + let mut tries = 0; + let status = loop { + match spawn( + &std::path::absolute(&game).unwrap(), + &root.join("res"), + &server, + ) { + Err(e) if e.raw_os_error() == Some(26) && tries < 50 => { + tries += 1; + std::thread::sleep(std::time::Duration::from_millis(20)); + } + child => break child.unwrap().wait(), + } + }; std::fs::remove_dir_all(&root).unwrap(); let status = status.unwrap(); assert!(status.success(), "{status}"); } + /// `check_starts` on a script this test process just wrote. Another test's spawn can fork while the + /// script's write handle is still open, and its child keeps that handle until it execs: running the + /// script meanwhile fails with ETXTBSY (Linux), so that one error is retried. + #[cfg(unix)] + fn check_written(program: &Path) -> Result<(), String> { + for _ in 0..50 { + match check_starts(program) { + Err(e) if e.contains("Text file busy") => { + std::thread::sleep(std::time::Duration::from_millis(20)) + } + other => return other, + } + } + check_starts(program) + } + #[cfg(unix)] #[test] fn the_check_runs_the_program() { @@ -340,10 +364,10 @@ mod tests { std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); path }; - assert_eq!(check_starts(&script("starts", "exit 0")), Ok(())); + assert_eq!(check_written(&script("starts", "exit 0")), Ok(())); let fails = script("fails", "echo 'no luck' >&2; exit 3"); assert_eq!( - check_starts(&fails), + check_written(&fails), Err(format!( "the game ({}) can't start (exit status 3): no luck", fails.display() From e350b87b3c28480c672943e832ff38aae5fce02a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:07:40 +0100 Subject: [PATCH 197/221] End portal exits pass no spawn finder main's item and mob End portal exit calls end_arrival, which now takes the respawn search's finder; in the End it only builds the platform. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/nether_portal.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index c8142284a..261e0cd10 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -297,7 +297,8 @@ impl Game<'_> { let p = plan.approximate; let centre = Vec3::new(f64::from(p.x) + 0.5, f64::from(p.y), f64::from(p.z) + 0.5); if plan.dim == Dim::End { - if let Err(e) = self.end_arrival(centre) { + // In the End the arrival only builds the platform: no spawn search. + if let Err(e) = self.end_arrival(centre, &mut None) { log::error!("End platform: {e}"); } return centre; From 09142298005c5fe45b1d4883dc5809965d3446eb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:07:40 +0100 Subject: [PATCH 198/221] A parrot saves its owner in main's Variant arm A second parrot arm was unreachable, so the variant was never saved. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index f7cc059aa..72b2136fc 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -330,14 +330,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); } - "minecraft:parrot" => { - if let Some(owner) = m.extra.owner { - map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); - } else { - map.remove(&"Owner".into()); - } - map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); - } "minecraft:wolf" => { if let Some(owner) = m.extra.owner { map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); @@ -511,6 +503,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { "Variant".into(), Tag::Int(i32::from(m.extra.variant.min(4))), ); + if let Some(owner) = m.extra.owner { + map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); + } else { + map.remove(&"Owner".into()); + } + map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); } "minecraft:salmon" => { let size = SALMON_SIZES[usize::from(m.extra.variant).min(2)]; From d5aa3f6e4256e8631cd14a1ad651fab5074f9efe Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:11:34 +0100 Subject: [PATCH 199/221] Name the cat relax goal's owner check is_owner_of The tame mob goals (#2382, #2399) add an is_owner(m, w) to this module. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/tame.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 5ac5d72dc..bd846ebc2 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -795,7 +795,7 @@ fn empty_above(w: &MobWorld, p: [i32; 3]) -> bool { } /// Whether `p` is the player that owns `m` (a cat without a recorded owner /// belongs to whoever it sees). -pub fn is_owner(m: &Mob, p: &super::PlayerView) -> bool { +pub fn is_owner_of(m: &Mob, p: &super::PlayerView) -> bool { m.extra.owner.is_none_or(|o| o == p.uuid) } /// `Cat.CatRelaxOnOwnerGoal`: while the owner sleeps, the cat lies down beside @@ -830,7 +830,7 @@ impl CatRelaxOnOwner { fn sleeping_owner<'w>(m: &Mob, w: &'w MobWorld) -> Option<&'w super::PlayerView> { w.player .as_ref() - .filter(|p| m.extra.tame && !m.extra.sitting && p.sleeping && is_owner(m, p)) + .filter(|p| m.extra.tame && !m.extra.sitting && p.sleeping && is_owner_of(m, p)) } } impl Goal for CatRelaxOnOwner { @@ -894,7 +894,7 @@ impl Goal for CatRelaxOnOwner { .w .player .as_ref() - .is_some_and(|p| is_owner(m, p) && p.sleep_timer >= 100) + .is_some_and(|p| is_owner_of(m, p) && p.sleep_timer >= 100) && m.random.next_float() < chance { give_morning_gift(m, cx); From 0879f3dbd2cb1a822946cded7f607607f5eb67ce Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:37:04 +0100 Subject: [PATCH 200/221] parity: a host's exclude list also holds on its own CI runner playhorizon's runner fails remote_fireball and remote_fireworks even alone and at bare main (3b19c386c: 2 of 2 runs and the retry), while the Mac mini passes them; every fork PR whose parity lands there stopped on them. The host's exclude list only kept harnesses off workers sent there, not off the runner's own jobs: platform_skips now adds the local host's exclude, skipped with its reason unless named. The two harnesses join playhorizon's list; the Mac mini's runner and the nightly audit (macOS) keep running them. Co-Authored-By: Claude Opus 5.5 --- docs/parity-workflow.md | 2 +- tests/test_parity_runner.py | 7 +++++++ tools/parity.py | 14 ++++++++------ tools/parity_hosts.json | 4 +++- 4 files changed, 19 insertions(+), 8 deletions(-) diff --git a/docs/parity-workflow.md b/docs/parity-workflow.md index 5c83c6a33..f527c9476 100644 --- a/docs/parity-workflow.md +++ b/docs/parity-workflow.md @@ -42,7 +42,7 @@ The game logs into `HORIZON_HOME` and falls back to the player's own game folder Harnesses can also run on the Mac mini, the desktop and playhorizon (`tools/parity_hosts.json` describes them; `desktop` and `playhorizon` use their CI runner's environment and vanilla data, and the desktop refuses work, or stops it, while someone uses it: docs/release-flow.md, "The desktop's runner"; its `default` list is empty, so pass `--hosts macmini,playhorizon` or set `PARITY_HOSTS`, after copying `shared-local/` to `~/code/horizon-parity/shared-local` on each host). The runner mirrors the worktree there with rsync (not `.git`, `.local`, `target` or ignored files) into `~/code/horizon-parity/remote/`, whose `.local` links to the vanilla data in `~/code/horizon-parity/shared-local`, and starts `tools/parity.py --worker` over ssh. The worker builds the probes (about 80 s the first time) and runs what it is sent under the same tracer, admitting harnesses against its own free memory. One queue, longest first, feeds every machine, remote ones first: the Mac takes up to 14 harnesses, the desktop 8, playhorizon 3 (on CPUs 0-3: its CI runner has 4-7). Each pass comes back with the content hash of every file it depended on, so it is keyed on exactly what ran, and logs come back to `.local/parity-runner/logs/`; state, sharing and `gate.py` work as before. If a host can't be reached, or drops out, its harnesses run here. -Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. +Harnesses a host can't run are listed in the file: `local_only` (`save_roundtrip` runs the game on a virtual screen) and each host's `exclude`. A host's `exclude` also holds when `parity.py` runs on that host itself, as its CI runner does: the harness is skipped there with its reason (playhorizon skips `remote_fireball` and `remote_fireworks`, which its CPU-starved CI slice fails even on bare main), unless named on the command line. The Mac mini's runner and the nightly audit still run them. The Mac excludes nothing: vanilla's `Math.sin`, `pow`, `log` and the like don't round the same on an Apple silicon Mac as on Linux (HotSpot uses fdlibm there, Intel's stubs on x86-64), and Rust's float functions round like neither (they call the platform libm), so code that mirrors a vanilla `Math` call uses `horizon_core::jmath`, which computes what HotSpot computes on the host architecture. The ThinkPad no longer runs harnesses (2026-10-26): playhorizon is the Linux host that is always on. The file's `solo` list names harnesses that drive game windows (`remote_fireworks`, `server_player_sculk`, `world_reopen`, ...). On a machine where `parity.py` has 4 CPUs or fewer, such as playhorizon's CI runner, each of them runs alone, after the others: there frames are drawn on the CPU, and beside other harnesses a screenshot or a control request took more ticks than the check allows. `PARITY_SOLO=1` or `0` forces this on or off. diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index fdc636a24..f26cbd5da 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -145,6 +145,13 @@ class ParityRunnerTests(unittest.TestCase): with mock.patch.object(parity.sys, "platform", "darwin"): self.assertEqual(parity.platform_skips(config), {"options": "libm"}) + def test_a_hosts_excludes_are_skipped_when_it_runs_parity_itself(self): + config = {"hosts": {"playhorizon": {"exclude": {"remote_fireworks": "starved"}}, "macmini": {"exclude": {}}}} + with mock.patch.object(parity.sys, "platform", "linux"): + self.assertEqual(parity.platform_skips(config, "playhorizon"), {"remote_fireworks": "starved"}) + self.assertEqual(parity.platform_skips(config, "macmini"), {}) + self.assertEqual(parity.platform_skips(config, "elsewhere"), {}) + def test_named_only_harnesses_are_listed_from_the_host_config(self): self.assertEqual(parity.named_only({"named_only": {"lan_integration": "slow"}}), {"lan_integration": "slow"}) self.assertEqual(parity.named_only({}), {}) diff --git a/tools/parity.py b/tools/parity.py index 38d113cab..f8f48fbcf 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -1454,11 +1454,13 @@ def affected_harnesses(found, records, changed, reach=True, base=None): return affected -def platform_skips(config): - """Harnesses tools/parity_hosts.json marks as giving different results on this platform: {name: reason}.""" - if sys.platform == "linux": - return {} - return dict(config.get("linux_only", {})) +def platform_skips(config, host=None): + """Harnesses tools/parity_hosts.json marks as giving different results on this platform, and those this host's + entry excludes (playhorizon's CI runner runs its own pull request jobs here, not only workers sent to it): + {name: reason}.""" + skips = {} if sys.platform == "linux" else dict(config.get("linux_only", {})) + skips.update(config.get("hosts", {}).get(HOST if host is None else host, {}).get("exclude", {})) + return skips def known_flaky(config): @@ -1593,7 +1595,7 @@ def main(): chosen = [name for name in found if stale(name, state, hasher, environment)] skips = platform_skips(host_config()) for name in [name for name in chosen if base_name(name) in skips and not args.names]: - print(f"skipped on {sys.platform}: {name}: {skips[base_name(name)]}", flush=True) + print(f"skipped on {HOST} ({sys.platform}): {name}: {skips[base_name(name)]}", flush=True) chosen.remove(name) manual = {} if args.names or args.all else named_only(host_config()) for name in [name for name in chosen if base_name(name) in manual]: diff --git a/tools/parity_hosts.json b/tools/parity_hosts.json index cec022194..2df32ba41 100644 --- a/tools/parity_hosts.json +++ b/tools/parity_hosts.json @@ -31,7 +31,9 @@ "exclude": { "mob_ai": "the vanilla oracle runs out of its 3 GB heap here (OutOfMemoryError in IO workers; passes on the desktop and the Mac) - 2026-10-26 trial", "lan_integration": "two clients rendered on the CPU (lavapipe): different timing subtests fail on each run (elytra, consume-release, barter, critical-hits) - 2026-10-26 trial", - "world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial" + "world_reopen": "failed twice here (no Save and Quit button after reopening; the minecart-count flake), passes on the desktop - 2026-10-26 trial", + "remote_fireball": "fails here even alone, at bare main 3b19c386c (2 of 2 runs and the retry), and passes on the Mac mini: the guest's egg is seen in 2 of 6 samples. CPU-starved: the whole horizon-ci slice (runner on 4-7, workers on 0-3) shares a 700% quota and was throttled in 27% of periods, so lavapipe frames and screenshots outlast the projectile's flight - 2026-10-27", + "remote_fireworks": "fails here even alone, at bare main 3b19c386c (2 of 2 runs and the retry), and passes on the Mac mini: the guest's sparks are gone by its trail screenshot (same CPU starvation as remote_fireball; a private Xvfb on CPUs 0-3 did not help) - 2026-10-27" }, "note": "a partner's server (Ubuntu, 8 EPYC threads, 30 GB, Detroit; tailnet only), its CI runner has CPUs 4-7, so workers get 0-3 (as tools/remote.sh runs do) and 3 jobs, in the CI runner's environment, slice and Xvfb screen (tools/ci/linux-runner.sh); the always-on Linux host since the ThinkPad stopped running harnesses (2026-10-26)" } From 0ff1df58a2f2684b9c52320ab9a32e05076e32d9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:11:13 +0100 Subject: [PATCH 201/221] nightly_set.py: trusted reviewers' picks for the Nightly (library) The pieces of nightly-2 (`/nightly 2640 2642`): parsing a comment, the reviewers list (.github/nightly-reviewers.txt, with a `paused` line), the refusals (paths CODEOWNERS gives to Ludovic, closed or merged PRs, more than 30, more than 6 builds a day), the set and its commands (Ludovic's remove keeps reviewers from adding a PR back), the nightly-state branch (pushed with retries when another run saved first), and the assembly: each PR head merged onto main in order with `git merge-tree --write-tree`, objects only, so no file, hook or filter of a pull request reaches the runner. Equal inputs give the same commit. A conflict names the two pull requests (or main) and the paths. Nothing calls it yet: the next PR wires it into nightly-build.yml and a `nightly command` workflow. Co-Authored-By: Claude Opus 5.5 --- tests/test_nightly_set.py | 293 +++++++++++++++++++++ tools/ci/nightly_set.py | 528 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 821 insertions(+) create mode 100644 tests/test_nightly_set.py create mode 100644 tools/ci/nightly_set.py diff --git a/tests/test_nightly_set.py b/tests/test_nightly_set.py new file mode 100644 index 000000000..5002fb137 --- /dev/null +++ b/tests/test_nightly_set.py @@ -0,0 +1,293 @@ +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +from tools.ci import nightly +from tools.ci import nightly_set as ns + +ROOT = Path(__file__).resolve().parents[1] +NOW = "2026-10-28T12:00:00+00:00" +PATTERNS = ns.guarded_patterns((ROOT / ".github/CODEOWNERS").read_text()) + + +def pr(n, head="h", state="open", files=("crates/horizon-world/src/lib.rs",), base="main"): + return ns.PullRequest(n, state, f"{head}{n}", f"Fix {n}", f"dev{n}", base, list(files)) + + +def lookup(*prs): + known = {p.number: p for p in prs} + return lambda n: known.get(n) + + +def run(state, text, login="kacpherek", *prs): + return ns.apply(state, ns.parse(text), login, NOW, lookup(*prs), PATTERNS) + + +class ParseTests(unittest.TestCase): + def test_commands(self): + self.assertEqual(ns.parse("/nightly 2640 #2642, 2640"), ns.Command("set", [2640, 2642])) + self.assertEqual(ns.parse("/nightly add 2650"), ns.Command("add", [2650])) + self.assertEqual(ns.parse("/Nightly REMOVE 2640"), ns.Command("remove", [2640])) + self.assertEqual(ns.parse("/nightly clear"), ns.Command("clear", [])) + self.assertEqual(ns.parse("/nightly status"), ns.Command("status", [])) + self.assertEqual(ns.parse("/nightly"), ns.Command("status", [])) + self.assertEqual(ns.parse("/nightly dry-run 1 2"), ns.Command("dry-run", [1, 2])) + self.assertEqual(ns.parse("\n /nightly 7\nthanks!"), ns.Command("set", [7])) + + def test_other_comments_are_not_commands(self): + for body in ("", "LGTM", "please /nightly 2640", "/nightlyx 1", "> /nightly 1"): + self.assertIsNone(ns.parse(body), body) + + def test_wrong_commands_are_answered(self): + for body in ("/nightly please", "/nightly add", "/nightly clear 5", "/nightly 1 `rm -rf`", + "/nightly " + " ".join(str(n) for n in range(1, 32))): + with self.assertRaises(ns.Refused, msg=body): + ns.parse(body) + + def test_answers_never_quote_markdown_or_mentions(self): + with self.assertRaises(ns.Refused) as e: + ns.parse("/nightly @ludovic111`x`") + self.assertNotIn("@", str(e.exception).split("isn't")[0]) + self.assertNotIn("`x`", str(e.exception)) + + +class AllowTests(unittest.TestCase): + LIST = "# trusted\nkacpherek # added by Ludovic\nrdbtCVS\n\nnot a login!\n" + + def test_listed_reviewers_and_ludovic(self): + reviewers = ns.read_reviewers(self.LIST) + ns.authorize("kacpherek", reviewers) + ns.authorize("RDBTcvs", reviewers) + ns.authorize("ludovic111", reviewers) + for login in ("levzzz5154", "someone", "not"): + with self.assertRaises(ns.Refused): + ns.authorize(login, reviewers) + + def test_paused_stops_reviewers_not_ludovic(self): + reviewers = ns.read_reviewers(self.LIST + "paused # Ludovic, 2026-10-29\n") + self.assertTrue(reviewers.paused) + with self.assertRaises(ns.Refused): + ns.authorize("kacpherek", reviewers) + ns.authorize("ludovic111", reviewers) + + def test_the_repos_list_names_the_three_reviewers(self): + reviewers = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text()) + self.assertEqual(reviewers.logins, {"kacpherek", "rdbtcvs", "levzzz5154"}) + self.assertFalse(reviewers.paused) + + +class RefusalTests(unittest.TestCase): + def test_what_codeowners_guards_is_refused(self): + for path in (".github/workflows/x.yml", "tools/ci/nightly.py", "crates/horizon-release-sign/src/lib.rs", + "crates/horizon-server/src/update.rs", "launcher/src/backend.rs", "launcher/links.json", + "launcher/src/signed.rs", "tools/release_train.py"): + self.assertTrue(ns.guarded(path, PATTERNS), path) + for path in ("crates/horizon-client/src/game.rs", "launcher/src/main.rs", "tools/ci.py", "docs/x.md", + "crates/horizon-server/src/main.rs"): + self.assertFalse(ns.guarded(path, PATTERNS), path) + self.assertTrue(ns.guarded("tools/ci/x.py", ns.guarded_patterns(""))) # even without CODEOWNERS + + def test_a_set_with_a_refused_pull_request_changes_nothing(self): + state = {"prs": []} + bad = [pr(2, files=["tools/ci/nightly.py"]), pr(3, state="closed"), pr(4, state="merged"), pr(5, base="x")] + for p in bad: + with self.assertRaises(ns.Refused): + run(state, f"/nightly 1 {p.number}", "kacpherek", pr(1), p) + with self.assertRaises(ns.Refused): + run(state, "/nightly 1 9", "kacpherek", pr(1)) # 9 doesn't exist + + def test_at_most_thirty(self): + state = {"prs": [ns.entry(pr(n), "a", NOW) for n in range(1, 31)]} + with self.assertRaises(ns.Refused): + run(state, "/nightly add 31", "kacpherek", pr(31)) + + +class SetTests(unittest.TestCase): + def test_set_add_remove_clear(self): + r = run({}, "/nightly 1 2", "kacpherek", pr(1), pr(2)) + self.assertTrue(r.build) + self.assertEqual([e["number"] for e in r.state["prs"]], [1, 2]) + self.assertEqual(r.state["prs"][0]["asked_by"], "kacpherek") + # add takes the newest head again and keeps its place + r = run(r.state, "/nightly add 1 3", "rdbtCVS", pr(1, head="new"), pr(3)) + self.assertEqual([(e["number"], e["head"]) for e in r.state["prs"]], [(1, "new1"), (2, "h2"), (3, "h3")]) + r = run(r.state, "/nightly remove 2", "rdbtCVS") + self.assertEqual([e["number"] for e in r.state["prs"]], [1, 3]) + r = run(r.state, "/nightly clear", "kacpherek") + self.assertEqual(r.state["prs"], []) + self.assertTrue(r.build) + + def test_status_and_dry_run_change_nothing(self): + state = run({}, "/nightly 1", "kacpherek", pr(1)).state + status = run(state, "/nightly status", "levzzz5154") + self.assertIs(status.state, state) + self.assertFalse(status.build) + self.assertIn("#1 Fix 1", status.answer) + dry = run(state, "/nightly dry-run 2 3", "kacpherek", pr(2), pr(3)) + self.assertIs(dry.state, state) + self.assertEqual([e["number"] for e in dry.dry_run], [2, 3]) + + def test_ludovics_remove_wins(self): + state = run({}, "/nightly 1 2", "kacpherek", pr(1), pr(2)).state + state = run(state, "/nightly remove 2", "ludovic111").state + self.assertEqual(state["blocked"], [2]) + for text in ("/nightly add 2", "/nightly 1 2", "/nightly dry-run 2"): + with self.assertRaises(ns.Refused): + run(state, text, "kacpherek", pr(1), pr(2)) + state = run(state, "/nightly add 2", "ludovic111", pr(2)).state + self.assertEqual(state["blocked"], []) + self.assertEqual([e["number"] for e in run(state, "/nightly add 2", "kacpherek", pr(2)).state["prs"]], [1, 2]) + + def test_titles_never_mention_anyone(self): + p = pr(1) + p.title = "Fix @everyone\nsecond line" + answer = run({}, "/nightly 1", "kacpherek", p).answer + self.assertNotIn("@everyone", answer) + self.assertNotIn("second line\n", answer) + + def test_builds_are_numbered_per_day(self): + self.assertEqual(ns.next_build("2026-10-28", []), "nightly/build-2026-10-28-1") + self.assertEqual(ns.next_build("2026-10-28", ["nightly/build-2026-10-28-1", "nightly/build-2026-10-28-4"]), + "nightly/build-2026-10-28-5") + + +class ScheduledTests(unittest.TestCase): + def test_the_scheduled_nightly_takes_new_heads_and_drops_closed_ones(self): + state = run({}, "/nightly 1 2 3 4", "kacpherek", pr(1), pr(2), pr(3), pr(4)).state + get = lookup(pr(1, head="new"), pr(2, state="merged"), pr(3, state="closed"), + pr(4, files=[".github/workflows/x.yml"])) + kept, left_out = nightly.refresh(state["prs"], get, PATTERNS) + self.assertEqual([(e["number"], e["head"]) for e in kept], [(1, "new1")]) + self.assertEqual(len(left_out), 3) + self.assertIn("merged", left_out[0]) + + def test_notes_list_each_pull_request_and_who_picked_it(self): + prs = run({}, "/nightly 1 2", "kacpherek", pr(1), pr(2)).state["prs"] + main = nightly.Ref("main", "m" * 40, None) + text = nightly.set_notes("2026-10-28", nightly.Ref("nightly/build-2026-10-28-1", "b" * 40, None), main, prs, + ["#3 Fix 3: closed, left out"]) + self.assertIn("can include pull requests not reviewed yet, picked by trusted reviewers", text) + self.assertIn("- Fix 1 (#1) by dev1, at h1, picked by kacpherek", text) + self.assertIn("### Left out (1)", text) + + +def sh(repo, *args, env=None): + return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True, + env={**os.environ, **(env or {})}).stdout.strip() + + +class AssemblyTests(unittest.TestCase): + """A fixture repository: main and three pull requests, two of them touching the same line.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.repo = self.tmp.name + ident = {"GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", + "GIT_COMMITTER_EMAIL": "t@t", "GIT_AUTHOR_DATE": "2026-10-28T10:00:00Z", + "GIT_COMMITTER_DATE": "2026-10-28T10:00:00Z"} + self.env = ident + sh(self.repo, "init", "-q", "-b", "main") + self.write({"a.txt": "a\n", "b.txt": "b\n", "c.txt": "c\n"}) + self.main = self.commit("main") + self.p1 = self.branch("p1", {"a.txt": "a from p1\n"}) + self.p2 = self.branch("p2", {"b.txt": "b from p2\n", ".gitattributes": "* filter=evil\n"}) + self.p3 = self.branch("p3", {"a.txt": "a from p3\n"}) + sh(self.repo, "checkout", "-q", "main") + + def tearDown(self): + self.tmp.cleanup() + + def write(self, files): + for name, text in files.items(): + Path(self.repo, name).write_text(text) + + def commit(self, message): + sh(self.repo, "add", "-A") + sh(self.repo, "commit", "-q", "-m", message, env=self.env) + return sh(self.repo, "rev-parse", "HEAD") + + def branch(self, name, files): + sh(self.repo, "checkout", "-q", "-b", name, self.main) + self.write(files) + return self.commit(name) + + def test_clean_merges_in_order_and_the_same_inputs_give_the_same_commit(self): + built = ns.assemble(self.main, [(1, self.p1), (2, self.p2)], cwd=self.repo) + self.assertEqual(sh(self.repo, "show", f"{built}:a.txt"), "a from p1") + self.assertEqual(sh(self.repo, "show", f"{built}:b.txt"), "b from p2") + self.assertEqual(sh(self.repo, "rev-list", "--count", f"{self.main}..{built}", "--first-parent"), "2") + self.assertEqual(ns.assemble(self.main, [(1, self.p1), (2, self.p2)], cwd=self.repo), built) + # nothing was checked out: the working tree is still main's + self.assertEqual(Path(self.repo, "a.txt").read_text(), "a\n") + self.assertFalse(Path(self.repo, ".gitattributes").exists()) + + def test_two_pull_requests_that_conflict_are_named(self): + with self.assertRaises(ns.Conflict) as e: + ns.assemble(self.main, [(1, self.p1), (2, self.p2), (3, self.p3)], cwd=self.repo) + self.assertEqual((e.exception.number, e.exception.other, e.exception.files), (3, 1, ["a.txt"])) + self.assertIn("#1 and #3 conflict in `a.txt`", e.exception.text()) + + def test_a_conflict_with_main_says_so(self): + sh(self.repo, "checkout", "-q", "main") + self.write({"a.txt": "a from main\n"}) + main = self.commit("main moves") + with self.assertRaises(ns.Conflict) as e: + ns.assemble(main, [(1, self.p1)], cwd=self.repo) + self.assertIsNone(e.exception.other) + self.assertIn("conflicts with main", e.exception.text()) + + def test_changed_files_finds_guarded_paths(self): + self.assertEqual(sorted(ns.changed_files(self.main, self.p2, cwd=self.repo)), [".gitattributes", "b.txt"]) + + +class StateTests(unittest.TestCase): + """The nightly-state branch on a local bare repository standing in for origin.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.origin, self.repo = Path(self.tmp.name, "origin.git"), Path(self.tmp.name, "work") + subprocess.run(["git", "init", "-q", "--bare", str(self.origin)], check=True) + subprocess.run(["git", "init", "-q", str(self.repo)], check=True) + sh(self.repo, "remote", "add", "origin", str(self.origin)) + + def tearDown(self): + self.tmp.cleanup() + + def test_first_save_then_load(self): + self.assertEqual(ns.load_state(str(self.repo)), ({}, "", None)) + ns.update_state(lambda st, b: ({"prs": [1]}, b + "{}\n", "first"), "t", cwd=str(self.repo)) + state, builds, head = ns.load_state(str(self.repo)) + self.assertEqual((state, builds), ({"prs": [1]}, "{}\n")) + self.assertIn("first", sh(self.repo, "log", "-1", "--format=%s", head)) + + def test_a_run_that_pushed_first_is_kept(self): + ns.update_state(lambda st, b: ({"prs": [1]}, b, "one"), "t", cwd=str(self.repo)) + other = Path(self.tmp.name, "other") + subprocess.run(["git", "init", "-q", str(other)], check=True) + sh(other, "remote", "add", "origin", str(self.origin)) + seen = [] + + def add_two(st, b): + seen.append(list(st.get("prs", []))) + if len(seen) == 1: # meanwhile another run saves first + ns.update_state(lambda s2, b2: ({"prs": s2["prs"] + [3]}, b2, "other"), "t", cwd=str(other)) + return {"prs": st["prs"] + [2]}, b, "two" + final = ns.update_state(add_two, "t", cwd=str(self.repo)) + self.assertEqual(seen, [[1], [1, 3]]) + self.assertEqual(final["prs"], [1, 3, 2]) + self.assertEqual(ns.load_state(str(self.repo))[0]["prs"], [1, 3, 2]) + + def test_builds_today_lists_the_days_branches(self): + sh(self.repo, "commit", "-q", "--allow-empty", "-m", "x", env={ + "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t", "GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}) + head = sh(self.repo, "rev-parse", "HEAD") + for name in ("nightly/build-2026-10-28-1", "nightly/build-2026-10-28-2", "nightly/build-2026-10-27-1"): + self.assertTrue(ns.push(head, name, "t", cwd=str(self.repo))) + self.assertEqual(sorted(ns.builds_today("2026-10-28", cwd=str(self.repo))), + ["nightly/build-2026-10-28-1", "nightly/build-2026-10-28-2"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ci/nightly_set.py b/tools/ci/nightly_set.py new file mode 100644 index 000000000..a192993d4 --- /dev/null +++ b/tools/ci/nightly_set.py @@ -0,0 +1,528 @@ +#!/usr/bin/env python3 +"""Trusted reviewers pick the pull requests a Nightly holds (docs/release-flow.md "Nightly channel"). + + nightly_set.py command one `/nightly …` comment (nightly-command.yml): checks who asked, updates the set, + starts the build and answers in the thread + +A comment by Ludovic or by a login in .github/nightly-reviewers.txt, on any issue or pull request: + + /nightly 2640 2642 the set becomes these pull requests, merged onto main in this order; builds now + /nightly add 2650 adds one, or takes its newest head again; builds now + /nightly remove 2640 drops one; builds now. Ludovic's remove also keeps reviewers from adding it back + /nightly clear empties the set: the Nightly is the proven union or main again; builds now + /nightly status what the set holds + /nightly dry-run 2640 builds main + these and signs with a throwaway key; publishes nothing, the set stays + +The set (set.json on the nightly-state branch) keeps each pull request at the head it had when someone asked for +it; the scheduled nightly takes their newest heads and drops the merged and closed ones (nightly.py pick). +builds.jsonl there records every build's set, for the stats. Nothing here runs a pull request's code: its commits +are fetched and merged with `git merge-tree --write-tree`, which writes git objects and never a working tree, so no +file of theirs reaches the disk and no hook, filter or script of theirs runs. +""" +from __future__ import annotations + +import copy +import datetime as dt +import json +import os +import re +import subprocess +import sys +import tempfile +import time +from dataclasses import dataclass, field +from pathlib import Path +from typing import Callable + +OWNER = "ludovic111" +REVIEWERS = ".github/nightly-reviewers.txt" +CODEOWNERS = ".github/CODEOWNERS" +# What CODEOWNERS guards today, refused even if the file moved: what builds, signs and checks releases. +ALWAYS_GUARDED = ["/.github/", "/tools/ci/", "/crates/horizon-release-sign/", "/crates/horizon-server/src/update.rs", + "/launcher/src/backend.rs", "/launcher/links.json"] +STATE_BRANCH = "nightly-state" +BUILD_PREFIX = "nightly/build-" +MAX_PRS = 30 +MAX_BUILDS_PER_DAY = 6 +BOT = ("github-actions[bot]", "41898283+github-actions[bot]@users.noreply.github.com") +# Git never runs anything of the merged commits; these make sure nothing of the runner's either. +SAFE_GIT = ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "merge.renormalize=false"] +NUMBER = re.compile(r"^#?(\d{1,6}),?$") +LOGIN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") +VERBS = ("add", "remove", "clear", "status", "dry-run") +USAGE = ("Use `/nightly 2640 2642`, `/nightly add 2650`, `/nightly remove 2640`, `/nightly clear`, " + "`/nightly status` or `/nightly dry-run 2640`.") + + +class Refused(Exception): + """A command that changes nothing; its text is the answer.""" + + +@dataclass +class Command: + verb: str # set, add, remove, clear, status, dry-run + prs: list[int] = field(default_factory=list) + + def text(self) -> str: + words = ["/nightly"] + ([] if self.verb == "set" else [self.verb]) + [str(n) for n in self.prs] + return " ".join(words) + + +def safe(word: str) -> str: + """A word of a comment, fit to quote back: no markdown, no mentions.""" + return re.sub(r"[^\w#:.-]", "", word)[:40] or "?" + + +def parse(body: str) -> Command | None: + """The command on a comment's first line; None when it isn't one. Raises Refused when it is one, but wrong.""" + line = next((line.strip() for line in body.splitlines() if line.strip()), "") + words = line.split() + if not words or words[0].lower() != "/nightly": + return None + rest = words[1:] + verb = "status" if not rest else "set" + if rest and rest[0].lower() in VERBS: + verb = rest.pop(0).lower() + prs: list[int] = [] + for word in rest: + m = NUMBER.match(word) + if not m: + raise Refused(f"`{safe(word)}` isn't a pull request number. {USAGE}") + if (n := int(m.group(1))) not in prs: + prs.append(n) + if verb in ("clear", "status") and prs: + raise Refused(f"`/nightly {verb}` takes no numbers. {USAGE}") + if verb not in ("clear", "status") and not prs: + raise Refused(f"`/nightly {'' if verb == 'set' else verb + ' '}` needs pull request numbers. {USAGE}") + if len(prs) > MAX_PRS: + raise Refused(f"A Nightly holds at most {MAX_PRS} pull requests; that's {len(prs)}.") + return Command(verb, prs) + + +@dataclass +class Reviewers: + logins: set[str] # lowercase + paused: bool + + +def read_reviewers(text: str) -> Reviewers: + """The list file: one login per line, `#` comments, and a `paused` line that stops every reviewer.""" + logins, paused = set(), False + for raw in text.splitlines(): + line = raw.split("#", 1)[0].strip() + if not line: + continue + words = line.split() + if len(words) != 1: # not a login: ignored rather than half-read + continue + word = words[0] + if word.lower() == "paused": + paused = True + elif LOGIN.match(word): + logins.add(word.lower()) + return Reviewers(logins, paused) + + +def is_owner(login: str) -> bool: + return login.lower() == OWNER + + +def authorize(login: str, reviewers: Reviewers) -> None: + """Ludovic always; a listed reviewer unless the list is paused; nobody else.""" + if is_owner(login): + return + if login.lower() not in reviewers.logins: + raise Refused(f"Only Ludovic and the trusted reviewers listed in `{REVIEWERS}` can pick the Nightly.") + if reviewers.paused: + raise Refused(f"`/nightly` is paused: Ludovic stopped it in `{REVIEWERS}`.") + + +def guarded_patterns(codeowners: str) -> list[str]: + """The paths CODEOWNERS gives to Ludovic, plus ALWAYS_GUARDED.""" + found = [line.split()[0] for line in codeowners.splitlines() if line.strip().startswith("/")] + return sorted(set(found + ALWAYS_GUARDED)) + + +def guarded(path: str, patterns: list[str]) -> bool: + p = "/" + path.lstrip("/") + return any(p.startswith(pat) if pat.endswith("/") else p == pat for pat in patterns) + + +@dataclass +class PullRequest: + number: int + state: str # open, closed, merged + head: str + title: str + author: str + base: str + files: list[str] + + +def check(pr: PullRequest | None, number: int, patterns: list[str]) -> str | None: + """Why `pr` can't go in a Nightly, or None.""" + if pr is None: + return f"#{number} isn't a pull request here" + if pr.state != "open": + return f"#{number} is {pr.state}" + if pr.base != "main": + return f"#{number} targets `{safe(pr.base)}`, not main" + bad = [f for f in pr.files if guarded(f, patterns)] + if bad: + more = f" and {len(bad) - 1} more" if len(bad) > 1 else "" + return f"#{number} changes `{bad[0]}`{more}, which only Ludovic merges (CODEOWNERS)" + return None + + +def entry(pr: PullRequest, asked_by: str, now: str) -> dict: + return {"number": pr.number, "head": pr.head, "title": pr.title, "author": pr.author, "asked_by": asked_by, + "asked_at": now} + + +@dataclass +class Result: + state: dict + answer: str + build: bool + dry_run: list[dict] | None = None # the set a dry run builds; the saved set stays + + +def plain(text: str) -> str: + """A title fit for a comment or the notes: no mention, no markdown that spans lines.""" + return text.replace("@", "@\u200b").replace("\n", " ").strip()[:200] + + +def describe(prs: list[dict], heading: str = "The set") -> str: + if not prs: + return "The set is empty: the Nightly is the newest proven union, or main." + lines = [f"{heading} ({len(prs)}), merged onto main in this order:"] + lines += [f"- #{e['number']} {plain(e['title'])} (by {e['author']}, at {e['head'][:7]}, asked by " + f"{e['asked_by']})" for e in prs] + return "\n".join(lines) + + +def apply(state: dict, cmd: Command, login: str, now: str, lookup: Callable[[int], PullRequest | None], + patterns: list[str]) -> Result: + """What `cmd` by `login` makes of `state` (set.json). Pure but for `lookup`; raises Refused.""" + st = copy.deepcopy(state) + prs: list[dict] = st.setdefault("prs", []) + blocked: list[int] = st.setdefault("blocked", []) + owner = is_owner(login) + if cmd.verb == "status": + extra = f"\nOnly Ludovic can add these back: {', '.join(f'#{n}' for n in blocked)}." if blocked else "" + return Result(state, describe(prs) + extra, False) + if cmd.verb == "clear": + st["prs"] = [] + elif cmd.verb == "remove": + absent = [n for n in cmd.prs if n not in [e["number"] for e in prs]] + if absent and len(absent) == len(cmd.prs) and not owner: + raise Refused(f"{', '.join(f'#{n}' for n in absent)} isn't in the set. " + describe(prs)) + st["prs"] = [e for e in prs if e["number"] not in cmd.prs] + if owner: + st["blocked"] = blocked + [n for n in cmd.prs if n not in blocked] + else: # set, add, dry-run + if not owner and (held := [n for n in cmd.prs if n in blocked]): + raise Refused(f"Ludovic took {', '.join(f'#{n}' for n in held)} out of the Nightly; only he can put " + "it back.") + problems, asked = [], [] + for n in cmd.prs: + pr = lookup(n) + if why := check(pr, n, patterns): + problems.append(why) + else: + asked.append(entry(pr, login, now)) + if problems: + raise Refused("Nothing changed: " + "; ".join(problems) + ".") + if cmd.verb == "add": + fresh = {e["number"]: e for e in asked} + new = [fresh.pop(e["number"], e) for e in prs] + list(fresh.values()) # keeps its place, newest head + else: + new = asked + if len(new) > MAX_PRS: + raise Refused(f"A Nightly holds at most {MAX_PRS} pull requests; that would be {len(new)}.") + if cmd.verb == "dry-run": + return Result(state, describe(new, "Dry run, the saved set stays as it is. It builds"), True, + dry_run=new) + if owner: + st["blocked"] = [n for n in blocked if n not in cmd.prs] + st["prs"] = new + return Result(st, describe(st["prs"]), True) + + +def log_command(state: dict, cmd: Command, login: str, now: str, issue: str, url: str) -> dict: + st = copy.deepcopy(state) + st["log"] = (st.get("log", []) + [{"at": now, "by": login, "command": cmd.text(), "issue": issue, + "url": url}])[-50:] + return st + + +# --- git ------------------------------------------------------------------------------------------------------- + + +def git(*args: str, cwd: str | None = None, env: dict | None = None, check: bool = True, + input: str | None = None) -> subprocess.CompletedProcess: + return subprocess.run(["git", *SAFE_GIT, *args], cwd=cwd, env={**os.environ, **(env or {})}, check=check, + capture_output=True, text=True, input=input) + + +def out(*args: str, cwd: str | None = None, env: dict | None = None) -> str: + return git(*args, cwd=cwd, env=env).stdout.strip() + + +def identity(date: str) -> dict: + """The bot's name, and a fixed date so the same inputs give the same commit.""" + name, email = BOT + return {"GIT_AUTHOR_NAME": name, "GIT_AUTHOR_EMAIL": email, "GIT_COMMITTER_NAME": name, + "GIT_COMMITTER_EMAIL": email, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date} + + +def merge_tree(a: str, b: str, cwd: str | None = None) -> tuple[str | None, list[str]]: + """The merged tree of commits a and b, or None and the conflicted paths. Objects only, no working tree.""" + r = git("merge-tree", "--write-tree", "--name-only", "--no-messages", a, b, cwd=cwd, check=False) + if r.returncode == 0: + return r.stdout.split()[0], [] + if r.returncode == 1: + return None, [line for line in r.stdout.splitlines()[1:] if line.strip()] + raise RuntimeError(f"git merge-tree {a[:9]} {b[:9]}: {r.stderr.strip()}") + + +def commit_tree(tree: str, parents: list[str], message: str, date: str, cwd: str | None = None) -> str: + args = ["commit-tree", tree] + for p in parents: + args += ["-p", p] + return out(*args, "-m", message, cwd=cwd, env=identity(date)) + + +@dataclass +class Conflict(Exception): + number: int + other: int | None # the earlier pull request it conflicts with; None: main; 0: only with several together + files: list[str] + + def text(self) -> str: + where = ", ".join(f"`{f}`" for f in self.files[:8]) + (" and more" if len(self.files) > 8 else "") + if self.other is None: + return (f"#{self.number} conflicts with main in {where}: it needs main merged into it first.") + if self.other == 0: + return (f"#{self.number} conflicts with the pull requests before it, taken together, in {where}.") + return (f"#{self.other} and #{self.number} conflict in {where}. Make an integration pull request that " + "combines them (in your fork) and pick that one instead.") + + +def changed_files(base: str, head: str, cwd: str | None = None) -> list[str]: + """What `head` changes since it left `base`, renames' old paths included.""" + since = out("merge-base", base, head, cwd=cwd) + names = out("diff", "--name-status", "--no-renames", since, head, cwd=cwd) + return [line.split("\t", 1)[1] for line in names.splitlines() if "\t" in line] + + +def culprit(main: str, earlier: list[tuple[int, str]], head: str, date: str, cwd: str | None) -> int | None: + if merge_tree(main, head, cwd)[0] is None: + return None + for n, h in earlier: + tree, _ = merge_tree(main, h, cwd) + if tree is None: + continue + if merge_tree(commit_tree(tree, [main, h], "probe", date, cwd), head, cwd)[0] is None: + return n + return 0 + + +def assemble(main: str, heads: list[tuple[int, str]], cwd: str | None = None) -> str: + """main, then each pull request's head merged in order: the commit a Nightly builds. Raises Conflict.""" + date = out("show", "-s", "--format=%cI", main, cwd=cwd) + current = main + for i, (n, head) in enumerate(heads): + tree, files = merge_tree(current, head, cwd) + if tree is None: + raise Conflict(n, culprit(main, heads[:i], head, date, cwd), files) + current = commit_tree(tree, [current, head], f"Nightly: merge #{n} at {head[:12]}", date, cwd) + return current + + +def fetch_heads(heads: list[tuple[int, str]], cwd: str | None = None) -> list[int]: + """Fetches each head from origin; returns the numbers whose head is gone (force-pushed away and collected).""" + shas = [h for _, h in heads] + if shas and git("fetch", "--quiet", "--no-tags", "origin", *shas, cwd=cwd, check=False).returncode == 0: + return [] + gone = [] + for n, h in heads: + if git("cat-file", "-e", f"{h}^{{commit}}", cwd=cwd, check=False).returncode == 0: + continue + git("fetch", "--quiet", "--no-tags", "origin", h, cwd=cwd, check=False) + if git("cat-file", "-e", f"{h}^{{commit}}", cwd=cwd, check=False).returncode != 0: + gone.append(n) + return gone + + +def auth(token: str) -> list[str]: + """A `git -c` for pushing with the job's token, never written to a file or a log.""" + import base64 + basic = base64.b64encode(f"x-access-token:{token}".encode()).decode() + os.environ.setdefault("GIT_TERMINAL_PROMPT", "0") + return ["-c", f"http.https://github.com/.extraheader=AUTHORIZATION: basic {basic}"] + + +def push(sha: str, ref: str, token: str, cwd: str | None = None, force: bool = False) -> bool: + spec = f"{'+' if force else ''}{sha}:refs/heads/{ref}" + return git(*auth(token), "push", "--quiet", "--no-verify", "origin", spec, cwd=cwd, check=False).returncode == 0 + + +def builds_today(today: str, cwd: str | None = None) -> list[str]: + listed = out("ls-remote", "origin", f"refs/heads/{BUILD_PREFIX}{today}-*", cwd=cwd) + return [line.split("refs/heads/", 1)[1] for line in listed.splitlines() if "refs/heads/" in line] + + +def next_build(today: str, existing: list[str]) -> str: + taken = [int(m.group(1)) for b in existing if (m := re.search(r"-(\d+)$", b))] + return f"{BUILD_PREFIX}{today}-{max(taken, default=0) + 1}" + + +# --- the state branch ------------------------------------------------------------------------------------------ + + +def load_state(cwd: str | None = None) -> tuple[dict, str, str | None]: + """set.json, builds.jsonl and the branch's head (None before the first command).""" + if git("fetch", "--quiet", "--no-tags", "origin", f"+refs/heads/{STATE_BRANCH}:refs/nightly/state", cwd=cwd, + check=False).returncode != 0: + return {}, "", None + head = out("rev-parse", "refs/nightly/state", cwd=cwd) + state = json.loads(git("show", f"{head}:set.json", cwd=cwd, check=False).stdout or "{}") + builds = git("show", f"{head}:builds.jsonl", cwd=cwd, check=False).stdout + return state, builds, head + + +def write_state(state: dict, builds: str, parent: str | None, message: str, cwd: str | None = None) -> str: + """A commit of the state branch, made in a private index: the checkout isn't touched.""" + with tempfile.TemporaryDirectory() as tmp: + env = {"GIT_INDEX_FILE": str(Path(tmp) / "index")} + for name, text in (("set.json", json.dumps(state, indent=2) + "\n"), ("builds.jsonl", builds), + ("README.md", STATE_README)): + blob = git("hash-object", "-w", "--stdin", cwd=cwd, input=text).stdout.strip() + git("update-index", "--add", "--cacheinfo", f"100644,{blob},{name}", cwd=cwd, env=env) + tree = out("write-tree", cwd=cwd, env=env) + now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds") + return commit_tree(tree, [parent] if parent else [], message, now, cwd) + + +STATE_README = """# nightly-state + +Written by tools/ci/nightly_set.py and tools/ci/nightly.py, never by hand. `set.json`: the pull requests the trusted +reviewers picked for the Nightly (docs/release-flow.md "Nightly channel"), each at the head it was asked at. +`builds.jsonl`: one line per Nightly build with its set. +""" + + +def update_state(change: Callable[[dict, str], tuple[dict, str, str] | None], token: str, + cwd: str | None = None, tries: int = 5): + """Applies change(state, builds) -> (state, builds, message), or None for no change, and pushes it; when another + run pushed first, reads the branch again and applies it again. Returns the last state.""" + for _ in range(tries): + state, builds, head = load_state(cwd) + changed = change(state, builds) + if changed is None: + return state + new, new_builds, message = changed + if push(write_state(new, new_builds, head, message, cwd), STATE_BRANCH, token, cwd): + return new + time.sleep(2) + raise RuntimeError(f"could not update {STATE_BRANCH} after {tries} tries") + + +# --- GitHub ---------------------------------------------------------------------------------------------------- + + +def gh(*args: str, check: bool = True) -> str: + r = subprocess.run(["gh", *args], capture_output=True, text=True) + if check and r.returncode != 0: + raise RuntimeError(f"gh {args[0]} {args[1] if len(args) > 1 else ''}: {r.stderr.strip()[:300]}") + return r.stdout.strip() if r.returncode == 0 else "" + + +def lookup(repo: str) -> Callable[[int], PullRequest | None]: + def get(n: int) -> PullRequest | None: + raw = gh("api", f"repos/{repo}/pulls/{n}", check=False) + if not raw: + return None + p = json.loads(raw) + files = gh("api", "--paginate", f"repos/{repo}/pulls/{n}/files", "--jq", + ".[] | .filename, (.previous_filename // empty)").splitlines() + state = "merged" if p.get("merged_at") else p["state"] + return PullRequest(n, state, p["head"]["sha"], p["title"], p["user"]["login"], p["base"]["ref"], files) + return get + + +def answer(repo: str, issue: str, text: str) -> None: + gh("api", f"repos/{repo}/issues/{issue}/comments", "-f", f"body=🤖 Nightly: {text}") + + +def dispatch(repo: str, issue: str, request: str, dry_run: list[dict] | None) -> str: + """Starts `nightly build` for this request; returns its run's URL once GitHub lists it.""" + args = ["workflow", "run", "nightly-build.yml", "--repo", repo, "--ref", "main", "-f", f"issue={issue}", + "-f", f"request={request}", "-f", "force=true"] + if dry_run is not None: + args += ["-f", "dry_run=true", "-f", "prs=" + " ".join(f"{e['number']}@{e['head']}" for e in dry_run)] + gh(*args) + for _ in range(15): + time.sleep(4) + runs = json.loads(gh("run", "list", "--repo", repo, "--workflow", "nightly-build.yml", "--event", + "workflow_dispatch", "--limit", "20", "--json", "displayTitle,url", check=False) or "[]") + for r in runs: + if request in r["displayTitle"]: + return r["url"] + return f"https://github.com/{repo}/actions/workflows/nightly-build.yml" + + +def command() -> None: + """nightly-command.yml: the comment arrives in env vars, never in a shell line.""" + repo, issue = os.environ["GITHUB_REPOSITORY"], os.environ["ISSUE"] + login, body, url = os.environ["AUTHOR"], os.environ.get("BODY", ""), os.environ.get("COMMENT_URL", "") + token = os.environ["GH_TOKEN"] + try: + cmd = parse(body) + except Refused as e: + answer(repo, issue, str(e)) + return + if cmd is None: + return + now = dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds") + try: + reviewers = Path(REVIEWERS).read_text() if Path(REVIEWERS).exists() else "" + authorize(login, read_reviewers(reviewers)) + patterns = guarded_patterns(Path(CODEOWNERS).read_text() if Path(CODEOWNERS).exists() else "") + if cmd.verb != "status": + today = now[:10] + done = builds_today(today) + if len(done) >= MAX_BUILDS_PER_DAY: + raise Refused(f"{len(done)} Nightly builds today already, the most a day takes: the next scheduled " + "one (20:17 UTC) builds the set.") + results: list[Result] = [] + + def change(state: dict, builds: str): + result = apply(state, cmd, login, now, lookup(repo), patterns) + results.append(result) + if result.state is state: # status, dry run: nothing to save + return None + return log_command(result.state, cmd, login, now, issue, url), builds, f"{cmd.text()} by {login}" + + update_state(change, token) + result = results[-1] + except Refused as e: + answer(repo, issue, str(e)) + return + text = result.answer + if result.build: + run = dispatch(repo, issue, f"{issue}-{int(time.time())}", result.dry_run) + text += f"\n\nBuilding: {run}. I'll answer here when it's {'done' if result.dry_run else 'published'}." + answer(repo, issue, text) + + +def main() -> None: + if sys.argv[1:] == ["command"]: + command() + else: + sys.exit(__doc__) + + +if __name__ == "__main__": + main() From 79eddec09c8c219c3232c5aec1a893496f7370e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:11:14 +0100 Subject: [PATCH 202/221] Nightly: trusted reviewers pick the pull requests with /nightly MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ludovic's decision (2026-10-27, from kacpherek's proposal under #2779): the Nightly is where contributors test pull requests before the gate. kacpherek, rdbtCVS and levzzz5154 (.github/nightly-reviewers.txt) and Ludovic pick them with `/nightly 2640 2642`, `add`, `remove`, `clear`, `status` or `dry-run` in any issue or pull request. - nightly-command.yml (issue_comment, main's copy): checks who asked, saves the set on nightly-state, starts `nightly build`, answers "🤖 Nightly: …". It never checks out or merges a pull request. - nightly-build.yml: `pick` builds main + the set (newest heads and merged or closed ones dropped at the scheduled run), pushes it as nightly/build--, records it in builds.jsonl; build, sign and publish are unchanged; `answer` tells the thread how it ended. - Notes say a Nightly can include pull requests not reviewed yet, picked by trusted reviewers, and list each with its author and who picked it. - docs/release-flow.md: who can pick, how, how Ludovic removes or pauses them. Co-Authored-By: Claude Opus 5.5 --- .github/nightly-reviewers.txt | 7 ++ .github/workflows/nightly-build.yml | 71 ++++++++++-- .github/workflows/nightly-command.yml | 46 ++++++++ docs/release-flow.md | 67 ++++++++++-- tools/ci/nightly.py | 150 ++++++++++++++++++++++++-- 5 files changed, 313 insertions(+), 28 deletions(-) create mode 100644 .github/nightly-reviewers.txt create mode 100644 .github/workflows/nightly-command.yml diff --git a/.github/nightly-reviewers.txt b/.github/nightly-reviewers.txt new file mode 100644 index 000000000..5b737439c --- /dev/null +++ b/.github/nightly-reviewers.txt @@ -0,0 +1,7 @@ +# Trusted reviewers: they pick the pull requests the Nightly holds with `/nightly 2640 2642` in any issue or pull +# request (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). Ludovic is always allowed and isn't +# listed. One GitHub login per line, with who added it and when. Removing a line revokes that login at once. +# A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work). +kacpherek # added by Ludovic, 2026-10-27 +rdbtCVS # added by Ludovic, 2026-10-27 +levzzz5154 # added by Ludovic, 2026-10-27 diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index d674d5992..e71e061b0 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -1,13 +1,20 @@ name: nightly build -# The opt-in Nightly channel (docs/release-flow.md "Nightly"; Ludovic, 2026-10-27). Once a night it builds the newest -# union branch on origin (union/-: main plus pull requests the contribution gate proved together), or -# main when no union is newer, and publishes it as the `nightly` pre-release. Launchers install it only for players -# who turn Nightly on. The previous nightly stays a week as nightly-. +run-name: nightly build${{ inputs.request && format(' (request {0})', inputs.request) || '' }} +# The opt-in Nightly channel (docs/release-flow.md "Nightly"; Ludovic, 2026-10-27). Once a night, and when a trusted +# reviewer asks (`/nightly 2640 2642`, nightly-command.yml), it builds main plus the pull requests the reviewers +# picked, merged in order (tools/ci/nightly_set.py). With none picked, it builds the newest union branch on origin +# (union/-: main plus pull requests the contribution gate proved together), or main when no union is +# newer. It publishes the result as the `nightly` pre-release. Launchers install it only for players who turn Nightly +# on. The previous nightly stays a week as nightly-. # -# Why the signing key never meets the union's code: +# Why the signing key never meets the pull requests' code: +# - `pick` merges the picked heads onto main with `git merge-tree --write-tree`: git objects only, no working tree, +# so none of their files reaches the disk and no hook, filter or script of theirs runs. It refuses any pull +# request that changes a path CODEOWNERS gives to Ludovic (this folder, tools/ci/, the signing and update code), +# pushes the merge as nightly/build-- and saves the set on the nightly-state branch. # - This file, game-build.yml and every script below run from main's copy: a schedule runs the default branch, and # `uses: ./…` takes the caller's commit. The union's own .github/ is never read. -# - `build` (game-build.yml) checks out and compiles the union with no secrets: its token reads contents only and +# - `build` (game-build.yml) checks out and compiles the merge (or the union) with no secrets: its token reads contents only and # isn't kept in the checkout; the macOS programs are signed ad hoc (Developer ID needs the runner's keychain, # which stays locked for nightlies). # - `sign` is the only job with RELEASE_SIGNING_KEY. It checks out nothing but main's tools/ci/sign_release.sh, which @@ -31,18 +38,37 @@ on: description: Build and sign with a throwaway key, publish nothing type: boolean default: false + issue: + description: The issue or pull request whose `/nightly` comment asked for this build (answered there) + type: string + default: '' + request: + description: The command's id, in the run's name so it can link the run + type: string + default: '' + prs: + description: A dry run's own set, `2640@ 2642@` (the saved set stays) + type: string + default: '' permissions: contents: read concurrency: + # One build at a time. A newer request replaces one still waiting: it builds the set as it is by then, so no pick + # is lost. group: nightly-build cancel-in-progress: false jobs: pick: runs-on: ubuntu-latest timeout-minutes: 10 + permissions: + contents: write # nightly/build-- and the nightly-state branch (main is protected) + issues: write # says in the thread when the picked pull requests conflict + pull-requests: write outputs: build: ${{ steps.pick.outputs.build }} sha: ${{ steps.pick.outputs.sha }} + short: ${{ steps.pick.outputs.short }} source: ${{ steps.pick.outputs.source }} date: ${{ steps.pick.outputs.date }} version: ${{ steps.pick.outputs.version }} @@ -60,6 +86,9 @@ jobs: env: GH_TOKEN: ${{ github.token }} FORCE: ${{ (inputs.force || steps.mode.outputs.dry_run == 'true') && 'yes' || '' }} + DRY_RUN: ${{ steps.mode.outputs.dry_run }} + NIGHTLY_ISSUE: ${{ inputs.issue }} + NIGHTLY_PRS: ${{ inputs.prs }} run: | python3 tools/ci/nightly.py pick ${FORCE:+--force} | tee -a "$GITHUB_STEP_SUMMARY" { echo; cat nightly-notes.md; } >> "$GITHUB_STEP_SUMMARY" @@ -164,3 +193,33 @@ jobs: run: | echo "Would publish nightly at ${{ needs.pick.outputs.sha }} (${{ needs.pick.outputs.source }})" ls -l dist + + answer: + # Tells the thread that asked for this build how it ended. A conflict `pick` already explained there. + needs: [pick, build, sign, publish] + if: always() && inputs.issue != '' && needs.pick.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + issues: write + pull-requests: write + steps: + - env: + GH_TOKEN: ${{ github.token }} + ISSUE: ${{ inputs.issue }} + BUILD: ${{ needs.pick.outputs.build }} + PUBLISHED: ${{ needs.publish.result }} + DRY_RUN: ${{ needs.pick.outputs.dry_run }} + NAME: Nightly ${{ needs.pick.outputs.date }} · ${{ needs.pick.outputs.short }} + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + if [[ "$BUILD" != true ]]; then + text="nothing new: the published Nightly is already this build." + elif [[ "$PUBLISHED" == success && "$DRY_RUN" == true ]]; then + text="the dry run built and signed $NAME; nothing was published. $RUN" + elif [[ "$PUBLISHED" == success ]]; then + text="published $NAME: https://github.com/$GITHUB_REPOSITORY/releases/tag/nightly. Launchers with Nightly on install it at their next start." + else + text="the build failed, nothing was published: $RUN" + fi + gh api "repos/$GITHUB_REPOSITORY/issues/$ISSUE/comments" -f body="🤖 Nightly: $text" diff --git a/.github/workflows/nightly-command.yml b/.github/workflows/nightly-command.yml new file mode 100644 index 000000000..340988d93 --- /dev/null +++ b/.github/workflows/nightly-command.yml @@ -0,0 +1,46 @@ +name: nightly command +# `/nightly …` comments: the trusted reviewers in .github/nightly-reviewers.txt (and Ludovic) pick the pull requests +# the Nightly holds (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). This job only checks who asked, +# saves the set on the nightly-state branch, starts `nightly build` and answers in the thread. +# +# Why no pull request's code runs here, though the token can write: +# - `issue_comment` always runs this file from main, whoever comments and wherever; a pull request's own copy of it +# is never read. +# - It checks out main and runs main's nightly_set.py. The comment's text and author reach it as env vars, never in +# a shell line. +# - It never checks out, fetches or merges a pull request: it reads their file lists through the API. The merge +# happens in nightly-build.yml's `pick`, with git objects only; their code runs in its `build`, without secrets. +on: + issue_comment: + types: [created] +permissions: + contents: read +jobs: + command: + # Every other comment skips here, before a runner starts. + if: startsWith(github.event.comment.body, '/nightly') && github.event.comment.user.type != 'Bot' + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: write # the nightly-state branch (main is protected) + actions: write # starts `nightly build` + issues: write # answers in the thread + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + sparse-checkout: | + .github/CODEOWNERS + .github/nightly-reviewers.txt + tools/ci/nightly_set.py + sparse-checkout-cone-mode: false + - name: Run the command + env: + GH_TOKEN: ${{ github.token }} + BODY: ${{ github.event.comment.body }} + AUTHOR: ${{ github.event.comment.user.login }} + ISSUE: ${{ github.event.issue.number }} + COMMENT_URL: ${{ github.event.comment.html_url }} + run: python3 tools/ci/nightly_set.py command diff --git a/docs/release-flow.md b/docs/release-flow.md index a8d559c91..fdf6e97ce 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -263,8 +263,9 @@ silent (no ping and Discord's @silent flag). Launcher releases post without a pi ### One channel Since 2026-10-23 there is one release channel, and it is every launcher's default. Since 2026-10-27 (Ludovic's -decision, revising 2026-10-23's) players may also turn on [Nightly](#nightly-channel), an opt-in pre-release built -from reviewed pull requests; nothing about releases changes for anyone who doesn't. Every game release is published +decision, revising 2026-10-23's) players may also turn on [Nightly](#nightly-channel), an opt-in pre-release of main +plus pull requests the trusted reviewers picked, not all reviewed yet; nothing about releases changes for anyone who +doesn't. Every game release is published as the release, never a pre-release, and marked GitHub's *latest*: the launcher, `horizon-server update` and `install.sh` take it at once. Because nothing promotes it later, the checks that used to gate a promotion run in the release itself, and the publish job (`tools/release_train.py gate`) publishes nothing unless both pass: @@ -411,22 +412,66 @@ launcher and the website read: both then look the newest launcher tags up one by ## Nightly channel -`.github/workflows/nightly-build.yml` publishes an opt-in build once a night (20:17 UTC), for players who want -reviewed fixes before they are released (#2681). It builds the newest `union/-` branch on origin (main -plus the pull requests the contribution gate proved together in one wave) when that union is newer than main's head -and holds something main lacks, otherwise main (`tools/ci/nightly.py pick`). A night with nothing new publishes -nothing. Only proven unions are pushed to origin, so nothing unreviewed ships. +`.github/workflows/nightly-build.yml` publishes an opt-in build once a night (20:17 UTC) and when a trusted +reviewer asks, for players who want fixes before they are released (#2681). It builds main plus the pull requests the +trusted reviewers picked, merged in their order. With none picked, it builds the newest `union/-` branch +on origin (main plus the pull requests the contribution gate proved together in one wave) when that union is newer +than main's head and holds something main lacks, otherwise main (`tools/ci/nightly.py pick`). A night with nothing +new publishes nothing. A Nightly can include pull requests not reviewed yet: that is what it is for, playing them +before the gate. -- **Jobs.** `pick` chooses the commit and writes the notes (the open pull requests it holds beyond main). `build` is +### Trusted reviewers pick the pull requests + +The Nightly is where contributors test pull requests before the gate. The trusted reviewers listed in +`.github/nightly-reviewers.txt` (kacpherek, rdbtCVS and levzzz5154 since 2026-10-27) and Ludovic pick them with a +comment on any issue or pull request (`.github/workflows/nightly-command.yml`, `tools/ci/nightly_set.py`): + +```text +/nightly 2640 2642 the set becomes these pull requests, merged onto main in this order; builds now +/nightly add 2650 adds one, or takes its newest head again; builds now +/nightly remove 2640 drops one; builds now +/nightly clear empties the set: back to the proven union or main; builds now +/nightly status what the set holds +/nightly dry-run 2640 builds main + these and signs with a throwaway key; publishes nothing, the set stays +``` + +- **The answer.** The workflow answers in the thread with one comment starting `🤖 Nightly:`: the set, the build's + run, and later the published Nightly (or why it failed). +- **The set** is `set.json` on the `nightly-state` branch: who asked, when, and each pull request at the head it had + then. A head is taken again only when someone asks again or at the scheduled run, never silently in between. The + scheduled run takes every pull request's newest head and drops the merged and closed ones; the notes say so. + `builds.jsonl` there records each build's set (for `nightly_stats.py`). +- **Assembly.** `pick` (main's code) fetches each head and merges them onto main with `git merge-tree + --write-tree`: git objects only, no working tree, so no file, hook or filter of theirs reaches the runner. The + result is pushed as `nightly/build--` and `build` compiles that, without secrets, as for a release. + Equal inputs give the same commit, so an unchanged set and main publish nothing new. On a conflict the build + stops and answers which two pull requests conflict and where; a reviewer can then open an integration pull + request from their fork that combines them, and pick that one instead. +- **Refused.** A pull request that changes a path CODEOWNERS gives to Ludovic (`.github/`, `tools/ci/`, the + signing and update code, `launcher/src/backend.rs`, `launcher/links.json`…), more than 30 in a set, and more than + 6 builds a day (the scheduled one always runs). +- **No repository role.** Reviewers need no permission on the repository: the list file and the workflow are the + whole of it. +- **Ludovic stays in charge.** + - Ludovic's `/nightly clear` or `/nightly remove` always applies. A pull request he removed can only come back + when he adds it. + - A one-line pull request removing a login from `.github/nightly-reviewers.txt` revokes it as soon as it merges + (the file is his under CODEOWNERS). + - A line `paused` in that file stops every reviewer's `/nightly`; his own still work. + - Main, the gate and releases don't change: picks reach only players who turned Nightly on. + +- **Jobs.** `pick` chooses or assembles the commit and writes the notes (each pull request in it with its title, + author and who picked it, or for a union the open pull requests it holds beyond main). `build` is `game-build.yml`, the same builds and smoke test as a release, with the version `nightly-` and `HORIZON_NIGHTLY=" "` built in, macOS signed ad hoc. `sign` signs SHA256SUMS for the channel (the message says `horizon release nightly`, so a nightly's signature never passes for a release's). `publish` checks the signature and the smoke test (not `release-blocker`: a nightly is how blockers get tested), renames the previous `nightly` pre-release to `nightly-`, publishes the new one as the `nightly` pre-release (never GitHub's latest), and deletes the `nightly-` pre-releases and tags older than 7 days, nothing else. -- **The signing key never meets the union's code.** Every workflow file and script runs from main's copy (a schedule - runs the default branch; `uses: ./…` takes the caller's commit), never the union's `.github/`. `build` compiles the - union with a read-only token that isn't kept in the checkout and no secrets; the runner's Developer ID keychain +- **The signing key never meets the pull requests' code.** Every workflow file and script runs from main's copy (a + schedule and `issue_comment` run the default branch; `uses: ./…` takes the caller's commit), never a pull + request's `.github/`, and a pull request that changes `.github/` or `tools/ci/` is refused. `build` compiles the + merge with a read-only token that isn't kept in the checkout and no secrets; the runner's Developer ID keychain stays locked. `sign` is the only job with the key, and checks out only main's `tools/ci/sign_release.sh`, which hashes the archives with the runner's `sha256sum` and signs with its OpenSSL: it never runs what `build` made. `publish` runs main's `horizon-release-sign`, never the archives. diff --git a/tools/ci/nightly.py b/tools/ci/nightly.py index 57af588c1..9a6dd8a3b 100644 --- a/tools/ci/nightly.py +++ b/tools/ci/nightly.py @@ -5,10 +5,12 @@ nightly.py rotate renames the current `nightly` pre-release to nightly-, frees the tag nightly.py prune [--days 7] deletes the nightly- pre-releases and tags older than that, nothing else -A nightly builds the newest union branch on origin (`union/-`: main plus pull requests the contribution -gate proved together), or main when no union is newer than main's head. It is published as the `nightly` -pre-release; the previous one stays a week as nightly-. Runs from main's checkout with `gh`; it reads the -branch it picks with git and never runs anything from it. +A nightly builds main plus the pull requests the trusted reviewers picked (the set: tools/ci/nightly_set.py), merged +in their order and pushed as nightly/build--. With no set it builds the newest union branch on origin +(`union/-`: main plus pull requests the contribution gate proved together), or main when no union is +newer than main's head. It is published as the `nightly` pre-release; the previous one stays a week as +nightly-. Runs from main's checkout with `gh`; it reads and merges the branches with git and never runs +anything from them. """ from __future__ import annotations @@ -20,6 +22,12 @@ import re import subprocess import sys from dataclasses import dataclass +from pathlib import Path + +if __package__: # imported as tools.ci.nightly (the tests) + from . import nightly_set as ns +else: # run as tools/ci/nightly.py: its folder is on the path + import nightly_set as ns DATED = re.compile(r"^nightly-(\d{4}-\d{2}-\d{2})$") TITLE_DATE = re.compile(r"Nightly (\d{4}-\d{2}-\d{2})") @@ -69,11 +77,27 @@ def output(**values: str) -> None: f.write(f"{k}={v}\n") -def notes(today: str, chosen: Ref, held: list[dict]) -> str: - lines = [f"Nightly {today} · {chosen.sha[:7]}: built from `{chosen.name}` ({chosen.sha}).", "", - "**Opt-in, not a release.** Fixes the maintainers reviewed but haven't released yet: it may break. " - "Turn it on in the launcher's settings; your release install and your worlds stay as they are. " - "Report bugs with the version the game shows (\"Nightly · \").", ""] +OPT_IN = ("**Opt-in, not a release.** A Nightly can include pull requests not reviewed yet, picked by trusted " + "reviewers: it may break. Turn it on in the launcher's settings; your release install and your worlds stay " + "as they are. Report bugs with the version the game shows (\"Nightly · \").") + + +def set_notes(today: str, chosen: Ref, main: Ref, prs: list[dict], left_out: list[str]) -> str: + """The notes of a build of main plus the reviewers' set.""" + lines = [f"Nightly {today} · {chosen.sha[:7]}: main ({main.sha[:7]}) with {len(prs)} pull requests merged in, " + f"built from `{chosen.name}` ({chosen.sha}).", "", OPT_IN, "", + f"### Pull requests in this Nightly ({len(prs)})", ""] + lines += [f"- {ns.plain(e['title'])} (#{e['number']}) by {e['author']}, at {e['head'][:7]}, picked by " + f"{e['asked_by']}" for e in prs] + if left_out: + lines += ["", f"### Left out ({len(left_out)})", ""] + [f"- {ns.plain(why)}" for why in left_out] + return "\n".join(lines) + "\n" + + +def notes(today: str, chosen: Ref, held: list[dict], left_out: list[str] | None = None) -> str: + lines = [f"Nightly {today} · {chosen.sha[:7]}: built from `{chosen.name}` ({chosen.sha}).", "", OPT_IN, ""] + if left_out: + lines += [f"The reviewers' set had nothing left to build: {'; '.join(ns.plain(w) for w in left_out)}.", ""] if held: lines += [f"### Not on main yet ({len(held)})", ""] lines += [f"- {p['title']} (#{p['number']})" for p in held] @@ -82,12 +106,116 @@ def notes(today: str, chosen: Ref, held: list[dict]) -> str: return "\n".join(lines) + "\n" +def refresh(entries: list[dict], get, patterns: list[str]) -> tuple[list[dict], list[str]]: + """The scheduled nightly's set: each pull request at its newest head; merged, closed and refused ones out.""" + kept, left_out = [], [] + for e in entries: + pr = get(e["number"]) + if pr is not None and pr.state == "merged": + left_out.append(f"#{e['number']} {e['title']}: merged, so it's in main") + elif why := ns.check(pr, e["number"], patterns): + left_out.append(f"{why}: left out") + else: + kept.append({**e, "head": pr.head, "title": pr.title}) + return kept, left_out + + +def requested(spec: str, get) -> list[dict]: + """A dry run's set from its input: `2640@ 2642@`.""" + prs = [] + for word in spec.split(): + number, _, head = word.partition("@") + pr = get(int(number)) + prs.append({"number": int(number), "head": head or (pr.head if pr else ""), "title": pr.title if pr else "?", + "author": pr.author if pr else "?", "asked_by": "dry run"}) + return prs + + +def stop(repo: str, issue: str, text: str) -> None: + """Says why the build stopped, where it was asked for, and fails the job.""" + print(text) + if issue and repo: + ns.answer(repo, issue, text) + sys.exit(1) + + +def build_set(main: Ref, prs: list[dict], left_out: list[str], today: str, force: bool) -> None: + """main + the set, merged with git only (nightly_set.assemble), pushed as nightly/build--.""" + repo, issue = os.environ.get("GITHUB_REPOSITORY", ""), os.environ.get("NIGHTLY_ISSUE", "") + token, event = os.environ.get("GH_TOKEN", ""), os.environ.get("GITHUB_EVENT_NAME", "") + dry_run = os.environ.get("DRY_RUN") == "true" + patterns = ns.guarded_patterns(Path(ns.CODEOWNERS).read_text() if Path(ns.CODEOWNERS).exists() else "") + gone = set(ns.fetch_heads([(e["number"], e["head"]) for e in prs])) + kept = [] + for e in prs: + if e["number"] in gone: + left_out.append(f"#{e['number']} {e['title']}: its head {e['head'][:7]} is gone; ask for it again") + elif bad := [f for f in ns.changed_files(main.sha, e["head"]) if ns.guarded(f, patterns)]: + left_out.append(f"#{e['number']} {e['title']}: changes `{bad[0]}`, which only Ludovic merges") + else: + kept.append(e) + if not kept: + return build_union(main, today, force, left_out) + try: + sha = ns.assemble(main.sha, [(e["number"], e["head"]) for e in kept]) + except ns.Conflict as c: + state, _, _ = ns.load_state() + asked_in = issue or next((x["issue"] for x in reversed(state.get("log", [])) if x.get("issue")), "") + stop(repo, asked_in, f"the build stopped: {c.text()}") + previous = git("ls-remote", "--tags", "origin", "refs/tags/nightly").split("\t")[0] or None + build = force or previous != sha + name = "(unchanged)" + if build: + done = ns.builds_today(today) + if len(done) >= ns.MAX_BUILDS_PER_DAY and event != "schedule": + stop(repo, issue, f"{len(done)} Nightly builds today already, the most a day takes: the next scheduled " + "one (20:17 UTC) builds the set.") + name = ns.next_build(today, done) + if not ns.push(sha, name, token): + stop(repo, issue, f"could not push {name}") + record = {"ref": name, "sha": sha, "main": main.sha, "at": dt.datetime.now(dt.timezone.utc).isoformat( + timespec="seconds"), "event": event, "dry_run": dry_run, "run": os.environ.get("GITHUB_RUN_ID", ""), + "prs": [{k: e[k] for k in ("number", "head", "title", "author", "asked_by")} for e in kept], + "left_out": left_out} + ns.update_state(lambda st, builds: (st, builds + json.dumps(record) + "\n", f"build {name}"), token) + chosen = Ref(name, sha, dt.datetime.now(dt.timezone.utc)) + with open("nightly-notes.md", "w") as f: + f.write(set_notes(today, chosen, main, kept, left_out)) + output(build=str(build).lower(), sha=sha, short=sha[:7], source=name, date=today, version=f"nightly-{today}", + nightly=f"{today} {sha[:7]}") + print(f"{'build' if build else 'skip (unchanged since the last nightly)'}: {name} {sha}, main {main.sha[:7]} + " + + ", ".join(f"#{e['number']}" for e in kept)) + + def pick(force: bool) -> None: git("fetch", "--quiet", "origin", "+refs/heads/main:refs/remotes/origin/main", "+refs/heads/union/*:refs/remotes/origin/union/*") main = refs("refs/remotes/origin/main")[0] - chosen = choose(main, refs("refs/remotes/origin/union/")) today = dt.datetime.now(dt.timezone.utc).date().isoformat() + repo, token = os.environ.get("GITHUB_REPOSITORY", ""), os.environ.get("GH_TOKEN", "") + if spec := os.environ.get("NIGHTLY_PRS", "").strip(): # a dry run's own set; the saved one stays + return build_set(main, requested(spec, ns.lookup(repo)), [], today, force) + state, _, _ = ns.load_state() + prs, left_out = state.get("prs", []), [] + if prs and os.environ.get("GITHUB_EVENT_NAME") == "schedule": + patterns = ns.guarded_patterns(Path(ns.CODEOWNERS).read_text() if Path(ns.CODEOWNERS).exists() else "") + get = ns.lookup(repo) + + def fresh(st: dict, builds: str): + kept, out = refresh(st.get("prs", []), get, patterns) + left_out[:] = out + if kept == st.get("prs", []): + return None + return {**st, "prs": kept}, builds, "the scheduled nightly takes the newest heads" + prs = ns.update_state(fresh, token).get("prs", []) + if prs: + return build_set(main, prs, left_out, today, force) + build_union(main, today, force, left_out) + + +def build_union(main: Ref, today: str, force: bool, left_out: list[str] | None = None) -> None: + """No set: the newest proven union, or main.""" + chosen = choose(main, refs("refs/remotes/origin/union/")) previous = git("ls-remote", "--tags", "origin", "refs/tags/nightly").split("\t")[0] or None build = force or previous != chosen.sha # The open pull requests this build holds beyond main: their heads are in it and not in main. @@ -101,7 +229,7 @@ def pick(force: bool) -> None: held.append(pr) held.sort(key=lambda p: p["number"]) with open("nightly-notes.md", "w") as f: - f.write(notes(today, chosen, held)) + f.write(notes(today, chosen, held, left_out)) output(build=str(build).lower(), sha=chosen.sha, short=chosen.sha[:7], source=chosen.name, date=today, version=f"nightly-{today}", nightly=f"{today} {chosen.sha[:7]}") print(f"{'build' if build else 'skip (unchanged since the last nightly)'}: {chosen.name} {chosen.sha}, " From c9990e43e958f7f8717252e4c9ea7245b890465a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:14:01 +0100 Subject: [PATCH 203/221] nightly_set tests: the scheduled refresh and the notes move with nightly.py (next PR) Co-Authored-By: Claude Opus 5.5 --- tests/test_nightly_set.py | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/tests/test_nightly_set.py b/tests/test_nightly_set.py index 5002fb137..9a0e16778 100644 --- a/tests/test_nightly_set.py +++ b/tests/test_nightly_set.py @@ -4,7 +4,6 @@ import tempfile import unittest from pathlib import Path -from tools.ci import nightly from tools.ci import nightly_set as ns ROOT = Path(__file__).resolve().parents[1] @@ -153,26 +152,6 @@ class SetTests(unittest.TestCase): "nightly/build-2026-10-28-5") -class ScheduledTests(unittest.TestCase): - def test_the_scheduled_nightly_takes_new_heads_and_drops_closed_ones(self): - state = run({}, "/nightly 1 2 3 4", "kacpherek", pr(1), pr(2), pr(3), pr(4)).state - get = lookup(pr(1, head="new"), pr(2, state="merged"), pr(3, state="closed"), - pr(4, files=[".github/workflows/x.yml"])) - kept, left_out = nightly.refresh(state["prs"], get, PATTERNS) - self.assertEqual([(e["number"], e["head"]) for e in kept], [(1, "new1")]) - self.assertEqual(len(left_out), 3) - self.assertIn("merged", left_out[0]) - - def test_notes_list_each_pull_request_and_who_picked_it(self): - prs = run({}, "/nightly 1 2", "kacpherek", pr(1), pr(2)).state["prs"] - main = nightly.Ref("main", "m" * 40, None) - text = nightly.set_notes("2026-10-28", nightly.Ref("nightly/build-2026-10-28-1", "b" * 40, None), main, prs, - ["#3 Fix 3: closed, left out"]) - self.assertIn("can include pull requests not reviewed yet, picked by trusted reviewers", text) - self.assertIn("- Fix 1 (#1) by dev1, at h1, picked by kacpherek", text) - self.assertIn("### Left out (1)", text) - - def sh(repo, *args, env=None): return subprocess.run(["git", *args], cwd=repo, check=True, capture_output=True, text=True, env={**os.environ, **(env or {})}).stdout.strip() From 6c0e262aa070d0e34006049c62379057f8405bb2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:14:39 +0100 Subject: [PATCH 204/221] nightly_set tests: the repo's list file is checked with it (next PR) Co-Authored-By: Claude Opus 5.5 --- tests/test_nightly_set.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/test_nightly_set.py b/tests/test_nightly_set.py index 9a0e16778..f29c1dabe 100644 --- a/tests/test_nightly_set.py +++ b/tests/test_nightly_set.py @@ -71,12 +71,6 @@ class AllowTests(unittest.TestCase): ns.authorize("kacpherek", reviewers) ns.authorize("ludovic111", reviewers) - def test_the_repos_list_names_the_three_reviewers(self): - reviewers = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text()) - self.assertEqual(reviewers.logins, {"kacpherek", "rdbtcvs", "levzzz5154"}) - self.assertFalse(reviewers.paused) - - class RefusalTests(unittest.TestCase): def test_what_codeowners_guards_is_refused(self): for path in (".github/workflows/x.yml", "tools/ci/nightly.py", "crates/horizon-release-sign/src/lib.rs", From 7efd8ef33a5bb2cb54af239d7b51e3c8c464e81c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:15:14 +0100 Subject: [PATCH 205/221] Nightly tests: the scheduled refresh, the notes and the repo's reviewers list Co-Authored-By: Claude Opus 5.5 --- tests/test_nightly.py | 38 ++++++++++++++++++++++++++++++++++++++ tests/test_nightly_set.py | 5 +++++ 2 files changed, 43 insertions(+) diff --git a/tests/test_nightly.py b/tests/test_nightly.py index 2bbf8fc98..2916351b7 100644 --- a/tests/test_nightly.py +++ b/tests/test_nightly.py @@ -1,7 +1,25 @@ import datetime as dt import unittest +from pathlib import Path from tools.ci import nightly +from tools.ci import nightly_set as ns + +NOW = "2026-10-28T12:00:00+00:00" +PATTERNS = ns.guarded_patterns((Path(__file__).resolve().parents[1] / ".github/CODEOWNERS").read_text()) + + +def pr(n, head="h", state="open", files=("crates/horizon-world/src/lib.rs",), base="main"): + return ns.PullRequest(n, state, f"{head}{n}", f"Fix {n}", f"dev{n}", base, list(files)) + + +def lookup(*prs): + known = {p.number: p for p in prs} + return lambda n: known.get(n) + + +def run(state, text, login="kacpherek", *prs): + return ns.apply(state, ns.parse(text), login, NOW, lookup(*prs), PATTERNS) T = dt.datetime(2026, 10, 28, 12, 0, tzinfo=dt.timezone.utc) @@ -45,5 +63,25 @@ class NightlyTests(unittest.TestCase): self.assertIn("Everything in it is on main.", nightly.notes("2026-10-28", ref("main", "m" * 40, 0), [])) + +class ScheduledTests(unittest.TestCase): + def test_the_scheduled_nightly_takes_new_heads_and_drops_closed_ones(self): + state = run({}, "/nightly 1 2 3 4", "kacpherek", pr(1), pr(2), pr(3), pr(4)).state + get = lookup(pr(1, head="new"), pr(2, state="merged"), pr(3, state="closed"), + pr(4, files=[".github/workflows/x.yml"])) + kept, left_out = nightly.refresh(state["prs"], get, PATTERNS) + self.assertEqual([(e["number"], e["head"]) for e in kept], [(1, "new1")]) + self.assertEqual(len(left_out), 3) + self.assertIn("merged", left_out[0]) + + def test_notes_list_each_pull_request_and_who_picked_it(self): + prs = run({}, "/nightly 1 2", "kacpherek", pr(1), pr(2)).state["prs"] + main = nightly.Ref("main", "m" * 40, None) + text = nightly.set_notes("2026-10-28", nightly.Ref("nightly/build-2026-10-28-1", "b" * 40, None), main, prs, + ["#3 Fix 3: closed, left out"]) + self.assertIn("can include pull requests not reviewed yet, picked by trusted reviewers", text) + self.assertIn("- Fix 1 (#1) by dev1, at h1, picked by kacpherek", text) + self.assertIn("### Left out (1)", text) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_nightly_set.py b/tests/test_nightly_set.py index f29c1dabe..a235a29c1 100644 --- a/tests/test_nightly_set.py +++ b/tests/test_nightly_set.py @@ -71,6 +71,11 @@ class AllowTests(unittest.TestCase): ns.authorize("kacpherek", reviewers) ns.authorize("ludovic111", reviewers) + def test_the_repos_list_names_the_three_reviewers(self): + reviewers = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text()) + self.assertEqual(reviewers.logins, {"kacpherek", "rdbtcvs", "levzzz5154"}) + self.assertFalse(reviewers.paused) + class RefusalTests(unittest.TestCase): def test_what_codeowners_guards_is_refused(self): for path in (".github/workflows/x.yml", "tools/ci/nightly.py", "crates/horizon-release-sign/src/lib.rs", From 21ac444f28e2dbc08936d3d0f7bfc75a274feba5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:16:27 +0100 Subject: [PATCH 206/221] refactor: block entity data moves down beside the chunk Step A of the horizon-client crate split. `Chunk.block_entities` held `containers::BlockEntity`, whose payloads were defined across containers, brewing, signs, sculk, mobs::spawner, mobs::trial_spawner, vault, beehive and command_block, so `chunk` reached most of the gameplay code. The enum and every payload type now live in `chunk/block_entity.rs` as plain data (definitions and derives). Every impl block stays in its feature module, and each module re-exports its types under the old path, so callers don't change. Also: - `mobs::Who` moves to `horizon_client_core::who` (the vibration `Info` names it); mobs re-exports it. - `skins::NameOrId` moves beside `SkullSkin`, which holds it; skins re-exports it. - `Spawner.next`, the `Next` enum and `Selector.current` become `pub(crate)`, since their struct now lives in another module. - The vault, spawner and trial_spawner harnesses record `chunk/block_entity.rs`. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client-core/src/lib.rs | 1 + crates/horizon-client-core/src/who.rs | 8 + crates/horizon-client/src/beehive.rs | 15 +- crates/horizon-client/src/block_entities.rs | 2 +- crates/horizon-client/src/brewing.rs | 15 +- crates/horizon-client/src/chunk.rs | 4 +- .../horizon-client/src/chunk/block_entity.rs | 409 ++++++++++++++++++ crates/horizon-client/src/command_block.rs | 17 +- crates/horizon-client/src/containers.rs | 174 +------- crates/horizon-client/src/mobs.rs | 7 +- crates/horizon-client/src/mobs/spawner.rs | 44 +- .../horizon-client/src/mobs/trial_spawner.rs | 48 +- crates/horizon-client/src/sculk.rs | 43 +- crates/horizon-client/src/signs.rs | 17 +- crates/horizon-client/src/skins.rs | 8 +- crates/horizon-client/src/vault.rs | 34 +- tools/test_spawner_parity.py | 1 + tools/test_trial_spawner_parity.py | 1 + tools/test_vault_parity.py | 3 +- 19 files changed, 442 insertions(+), 409 deletions(-) create mode 100644 crates/horizon-client-core/src/who.rs create mode 100644 crates/horizon-client/src/chunk/block_entity.rs diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs index d839feddf..4c4231359 100644 --- a/crates/horizon-client-core/src/lib.rs +++ b/crates/horizon-client-core/src/lib.rs @@ -24,4 +24,5 @@ pub mod snbt; pub mod sound_source; pub mod text; pub mod uuid; +pub mod who; pub type Result = std::result::Result>; diff --git a/crates/horizon-client-core/src/who.rs b/crates/horizon-client-core/src/who.rs new file mode 100644 index 000000000..63101e879 --- /dev/null +++ b/crates/horizon-client-core/src/who.rs @@ -0,0 +1,8 @@ +//! Who an action came from or is aimed at: the player or a mob by id. + +/// Who caused damage or is being targeted. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Who { + Player, + Mob(u32), +} diff --git a/crates/horizon-client/src/beehive.rs b/crates/horizon-client/src/beehive.rs index 26aa87cfc..d0fa10c18 100644 --- a/crates/horizon-client/src/beehive.rs +++ b/crates/horizon-client/src/beehive.rs @@ -3,6 +3,7 @@ //! the rain, nor through a blocked front, unless the hive is emptied in an //! emergency), honey for every bee coming home with nectar. The host (the game //! or the mob AI probe) loads and adds the bees through [`HiveHost`]. +pub use crate::chunk::block_entity::{Beehive, Occupant}; use crate::mobs::{Mob, Species, bee}; use horizon_core::random::{LegacyRandom, RandomSource}; use horizon_world::nbt::{Compound, Tag}; @@ -38,20 +39,6 @@ const IGNORED_BEE_TAGS: [&str; 25] = [ "UUID", ]; -/// `BeehiveBlockEntity`: the bees inside and the flower one of them knew. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Beehive { - pub bees: Vec, - pub flower: Option<[i32; 3]>, -} -/// `BeehiveBlockEntity.Occupant`: a bee's tag (with its `id`), its time in -/// the hive and the time it stays at least. -#[derive(Clone, Debug, PartialEq)] -pub struct Occupant { - pub entity_data: Tag, - pub ticks_in_hive: i32, - pub min_ticks_in_hive: i32, -} /// `BeehiveBlockEntity.BeeReleaseStatus`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Release { diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs index 03fff85ca..944579b83 100644 --- a/crates/horizon-client/src/block_entities.rs +++ b/crates/horizon-client/src/block_entities.rs @@ -23,7 +23,7 @@ //! Which states tick is a table by state id, built by the game from the block //! registry; whether a slot is made is decided when the slot is promoted at //! the start of the next tick, from the block state then. -use crate::containers::BlockEntity; +use crate::chunk::block_entity::BlockEntity; use crate::fast_hash::{FxHashMap, FxHashSet}; use std::collections::HashMap; diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs index b3cda5f90..e058f0fe7 100644 --- a/crates/horizon-client/src/brewing.rs +++ b/crates/horizon-client/src/brewing.rs @@ -2,12 +2,13 @@ //! in vanilla, ported as tables), data-driven `minecraft:brewing` recipes from //! `data/minecraft/recipe/brewing`, potion colours and tooltips, and //! `BrewingStandBlockEntity.serverTick`. +pub use crate::chunk::block_entity::BrewingStand; use crate::{ containers::Providers, items::{ItemStack, Items}, }; use serde_json::Value; -use std::{collections::HashSet, fs, path::Path, sync::Arc}; +use std::{collections::HashSet, fs, path::Path}; pub use horizon_client_core::potions::{ BASE_POTION_COLOR, Category, EFFECTS, EffectDef, POTIONS, PotionDef, effect, namespaced, @@ -190,18 +191,6 @@ impl Brewing { } } -/// `BrewingStandBlockEntity` state. Slots: 0-2 bottles, 3 ingredient, 4 fuel. -#[derive(Clone, Debug, Default)] -pub struct BrewingStand { - pub items: [Option; 5], - pub brew_time: i32, - pub total_brew_time: i32, - pub fuel: i32, - pub total_fuel: i32, - pub speed: f32, - pub ingredient: Option>, - pub last_bottles: Option<[bool; 3]>, -} /// What a brewing tick asks the world to do. #[derive(Clone, Debug, Default, PartialEq)] pub struct BrewTick { diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index b0dd377c7..c405f5522 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -6,6 +6,8 @@ use horizon_world::nbt::{Compound, Tag}; use horizon_world::registry::BlockStateId; use std::sync::{Arc, OnceLock}; +pub mod block_entity; + pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; pub const SECTIONS: usize = (HEIGHT / 16) as usize; @@ -149,7 +151,7 @@ pub struct Chunk { /// Newly generated (not loaded from a save): eligible for generation-time spawns. pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. - pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>, + pub block_entities: Vec<((i32, i32, i32), block_entity::BlockEntity)>, /// `CustomName` of the container block entities (shown as the screen title). pub block_names: Vec<((i32, i32, i32), String)>, /// Generation postprocessing marks (ProtoChunk.postProcessing) as world diff --git a/crates/horizon-client/src/chunk/block_entity.rs b/crates/horizon-client/src/chunk/block_entity.rs new file mode 100644 index 000000000..0547228d8 --- /dev/null +++ b/crates/horizon-client/src/chunk/block_entity.rs @@ -0,0 +1,409 @@ +//! Block entity data: what a chunk stores for its block entities (`BlockEntity` +//! and its payloads). Plain data, as vanilla's block entities are world data; +//! their behaviour lives with the features that use them (`containers`, +//! `brewing`, `signs`, ...), which re-export these types under their old paths. +use horizon_client_core::{text::Text, who::Who}; +use horizon_items::{banner_layer::BannerLayer, items::ItemStack}; +use horizon_world::{ + level::sculk::SculkSpreader, + nbt::{Compound, Tag}, +}; +use std::{collections::HashMap, sync::Arc}; + +/// An entity's UUID as its four ints (`UUIDUtil.CODEC`). +pub type Uuid = [i32; 4]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FurnaceKind { + Furnace, + BlastFurnace, + Smoker, +} +#[derive(Clone, Debug)] +pub struct Furnace { + pub kind: FurnaceKind, + /// input, fuel, result + pub items: [Option; 3], + pub lit_remaining: i32, + pub lit_total: i32, + pub cooking_timer: i32, + pub cooking_total: i32, + pub speed: f32, + /// `AbstractFurnaceBlockEntity.recipesUsed`: how many of each recipe this furnace has + /// made since a player last took from its output. The experience is owed per recipe + /// rather than per item, and a save keeps it as the `RecipesUsed` compound. + pub recipes_used: HashMap, +} +#[derive(Clone, Debug)] +pub enum BlockEntity { + Chest(Vec>), + Furnace(Furnace), + Brewing(Box), + /// Signs and hanging signs (`SignBlockEntity`). + Sign(SignData), + /// `JukeboxBlockEntity`: the record and its `JukeboxSongPlayer`. + Jukebox(Jukebox), + /// `BeaconBlockEntity`. + Beacon(Box), + /// `LecternBlockEntity`: the book and the open page. + Lectern(Lectern), + /// Sculk sensors, shriekers and catalysts (`crate::sculk`). + Sculk(Box), + /// `CreakingHeartBlockEntity`: its protector and the hurt emitter. + CreakingHeart(Box), + /// `BannerBlockEntity`: the pattern layers. + Banner(Banner), + /// `CrafterBlockEntity`. + Crafter(Crafter), + /// `SpawnerBlockEntity` (`crate::mobs::spawner`). + Spawner(Box), + /// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`). + TrialSpawner(Box), + /// `VaultBlockEntity` (`crate::vault`). + Vault(Box), + /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). + Beehive(Box), + /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). + CommandBlock(Box), + /// `CampfireBlockEntity` of campfires and soul campfires. + Campfire(Box), + /// `SkullBlockEntity` of every skull and head block. + Skull(Skull), + /// `TheEndGatewayBlockEntity`: its age and configured destination. + EndGateway(EndGateway), + /// `DaylightDetectorBlockEntity`: no data, only the ticker + /// (`DaylightDetectorBlock.tickEntity`). + DaylightDetector, + /// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots. + ChiseledBookshelf(Box), +} +/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChiseledBookshelf { + pub items: [Option; 6], + pub last_slot: i32, +} +impl Default for ChiseledBookshelf { + fn default() -> Self { + Self { + items: Default::default(), + last_slot: -1, + } + } +} +/// `TheEndGatewayBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub exit_portal: Option<[i32; 3]>, + pub exact_teleport: bool, +} +/// `CampfireBlockEntity`: four cooking slots, each with its +/// `cookingProgress` and `cookingTime` (the recipe's). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Campfire { + pub items: [Option; 4], + pub progress: [i32; 4], + pub total: [i32; 4], +} +/// `SkullBlockEntity`: the player profile the head shows (kept as loaded: +/// a compound, or a string when it names a player only), the note block +/// sound and `custom_name`. +#[derive(Clone, Debug, Default)] +pub struct Skull { + pub profile: Option, + pub note_block_sound: Option, + pub custom_name: Option, + /// What `profile` draws, read from it once rather than every frame. + pub skin: Option, +} +/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL +/// with the `skins/` sprite it downloads to, and the +/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a +/// profile with no id). +#[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, +} +/// `Either`: the key a `Dynamic` `ResolvableProfile` resolves +/// by (`ResolvableProfile.nameOrId`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NameOrId { + Name(String), + Id(u128), +} +/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag +/// and the ticks left in the crafting animation. +#[derive(Clone, Debug, Default)] +pub struct Crafter { + pub items: [Option; 9], + pub disabled: [bool; 9], + pub triggered: bool, + pub crafting_ticks: i32, + /// The block state's `triggered` when last ticked (not saved): the block + /// entity flag follows it only when it changes (`CrafterBlock.neighborChanged`). + pub state_triggered: Option, +} +#[derive(Clone, Debug, Default)] +pub struct Banner { + pub layers: Vec, + pub name: Option, + /// Components not consumed by BannerBlockEntity's implicit fields. + pub components: horizon_world::nbt::Compound, +} +/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`). +#[derive(Clone, Debug, Default)] +pub struct CreakingHeart { + /// The protector: its entity id once resolved, and its UUID (the saved form). + pub creaking: Option<(Option, [i32; 4])>, + pub ticks_existed: i64, + pub ticker: i32, + /// Ticks left of the hurt effect (`emitter`) and where it heads. + pub emitter: i32, + pub emitter_target: Option<[f64; 3]>, + pub output_signal: i32, +} +#[derive(Clone, Debug, Default)] +pub struct Lectern { + pub book: Option, + pub page: i32, +} +#[derive(Clone, Debug, Default)] +pub struct Beacon { + pub levels: i32, + /// Effect ids (`minecraft:speed`). + pub primary: Option, + pub secondary: Option, + /// Beam sections (RGB colour, height) and the ones being rebuilt. + pub sections: Vec<(u32, i32)>, + pub checking: Vec<(u32, i32)>, + pub last_check_y: i32, +} +#[derive(Clone, Debug, Default)] +pub struct Jukebox { + pub record: Option, + /// `ticks_since_song_started`, while a song plays. + pub ticks: i64, + pub playing: bool, +} +/// `BrewingStandBlockEntity` state. Slots: 0-2 bottles, 3 ingredient, 4 fuel. +#[derive(Clone, Debug, Default)] +pub struct BrewingStand { + pub items: [Option; 5], + pub brew_time: i32, + pub total_brew_time: i32, + pub fuel: i32, + pub total_fuel: i32, + pub speed: f32, + pub ingredient: Option>, + pub last_bottles: Option<[bool; 3]>, +} +/// One sign side (`SignText`). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SignText { + pub lines: [String; 4], + /// `DyeColor` id. + pub color: u8, + pub glowing: bool, +} +/// `SignBlockEntity` / `HangingSignBlockEntity` data. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SignData { + pub hanging: bool, + pub front: SignText, + pub back: SignText, + pub waxed: bool, +} +/// `VibrationInfo`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Info { + pub event: &'static str, + pub distance: f32, + pub pos: [f64; 3], + pub source: Option, + pub owner: Option, +} +/// `VibrationSelector`: the closest, then highest-frequency candidate of a tick. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Selector { + pub(crate) current: Option<(Info, i64)>, +} +/// `VibrationSystem.Data`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Data { + pub current: Option, + pub travel: i32, + pub selector: Selector, +} +/// Which sculk block entity this is. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SculkKind { + Sensor, + Calibrated, + Shrieker, + Catalyst, +} +/// `SculkSensorBlockEntity`, `CalibratedSculkSensorBlockEntity`, +/// `SculkShriekerBlockEntity` and `SculkCatalystBlockEntity`. +#[derive(Clone, Debug)] +pub struct SculkEntity { + pub kind: SculkKind, + pub vibration: Data, + /// `last_vibration_frequency` (sensors). + pub last_frequency: i32, + /// `warning_level` (shriekers). + pub warning_level: i32, + /// The catalyst's charge cursors. + pub spreader: SculkSpreader, +} +/// `SpawnData.CustomSpawnRules`: the block and sky light the spawn block +/// must have (inclusive ranges within 0..=15). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CustomSpawnRules { + pub block: (i32, i32), + pub sky: (i32, i32), +} +/// `SpawnData`: the entity to spawn, optional light rules and an equipment +/// table (kept as loaded). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SpawnData { + pub entity: Compound, + pub custom_spawn_rules: Option, + pub equipment: Option, +} +/// Which `SpawnData` is next: one of the potentials (the same object in +/// vanilla, so changing it changes the potential) or its own. +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum Next { + Potential(usize), + Own(SpawnData), +} +/// `BaseSpawner`. +#[derive(Clone, Debug, PartialEq)] +pub struct Spawner { + pub spawn_delay: i32, + /// `SpawnPotentials`: data and weight. + pub potentials: Vec<(SpawnData, i32)>, + pub(crate) next: Option, + pub min_spawn_delay: i32, + pub max_spawn_delay: i32, + pub spawn_count: i32, + pub max_nearby_entities: i32, + pub required_player_range: i32, + pub spawn_range: i32, + /// The client copy's delay (`spawnDelay` on the client level), which + /// speeds the spin up as the next spawn nears. + pub client_delay: i32, + pub spin: f64, + pub o_spin: f64, +} +/// `TrialSpawnerConfig`. +#[derive(Clone, Debug, PartialEq)] +pub struct TrialConfig { + pub spawn_range: i32, + pub total_mobs: f32, + pub simultaneous_mobs: f32, + pub total_mobs_added_per_player: f32, + pub simultaneous_mobs_added_per_player: f32, + pub ticks_between_spawn: i32, + pub spawn_potentials: Vec<(SpawnData, i32)>, + pub loot_tables_to_eject: Vec<(String, i32)>, + pub items_to_drop_when_ominous: String, +} +/// A `Holder` as saved: a registry id +/// (`minecraft:trial_chamber/breeze/normal`) or an inline config. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ConfigSlot { + /// The value as loaded, written back as is; None for the default. + pub saved: Option, + pub config: TrialConfig, +} +/// `TrialSpawner` with its `TrialSpawnerStateData`. +#[derive(Clone, Debug, PartialEq)] +pub struct TrialSpawner { + pub normal: ConfigSlot, + pub ominous: ConfigSlot, + pub target_cooldown_length: i32, + pub required_player_range: i32, + pub detected_players: Vec, + pub current_mobs: Vec, + pub cooldown_ends_at: i64, + pub next_mob_spawns_at: i64, + pub total_mobs_spawned: i32, + pub next_spawn_data: Option, + pub ejecting_loot_table: Option, + /// `isOminous`, set from the block on every server tick. + pub is_ominous: bool, + /// The server's display entity exists (`getOrCreateDisplayEntity`): it is + /// made once per loaded block entity and kept. + pub has_display: bool, + pub spin: f64, + pub o_spin: f64, + /// `getDispensingItems`, kept once rolled (not saved): the ominous items + /// and their weights (the rolled counts). + pub dispensing: Option>, +} +/// `VaultConfig`. +#[derive(Clone, Debug, PartialEq)] +pub struct VaultConfig { + pub loot_table: String, + pub activation_range: f64, + pub deactivation_range: f64, + /// None when the config has no key (`ItemStack.EMPTY`): the vault never opens. + pub key_item: Option, + pub override_loot_table_to_display: Option, +} +/// `VaultBlockEntity`: its config, server data and shared data. +#[derive(Clone, Debug, PartialEq)] +pub struct Vault { + pub config: VaultConfig, + /// `VaultServerData`, oldest rewarded player first. + pub rewarded_players: Vec, + pub state_updating_resumes_at: i64, + /// Popped from the end. + pub items_to_eject: Vec, + pub total_ejections_needed: i32, + pub last_insert_fail_timestamp: i64, + /// `VaultSharedData`. + pub display_item: Option, + pub connected_players: Vec, + pub connected_particles_range: f64, + /// The shared data changed since the last tick sent it. + pub shared_dirty: bool, + /// `VaultClientData`: the display item's spin and the previous tick's, in degrees. + pub spin: f32, + pub o_spin: f32, +} +/// `BeehiveBlockEntity`: the bees inside and the flower one of them knew. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Beehive { + pub bees: Vec, + pub flower: Option<[i32; 3]>, +} +/// `BeehiveBlockEntity.Occupant`: a bee's tag (with its `id`), its time in +/// the hive and the time it stays at least. +#[derive(Clone, Debug, PartialEq)] +pub struct Occupant { + pub entity_data: Tag, + pub ticks_in_hive: i32, + pub min_ticks_in_hive: i32, +} +#[derive(Clone, Debug, PartialEq)] +pub struct CommandBlock { + pub command: String, + pub success_count: i32, + /// `CustomName` as saved (a text component). + pub custom_name: Option, + pub track_output: bool, + pub last_output: Option, + pub update_last_execution: bool, + /// The game time of the last run, -1 for none. + pub last_execution: i64, + pub powered: bool, + pub auto: bool, + pub condition_met: bool, +} diff --git a/crates/horizon-client/src/command_block.rs b/crates/horizon-client/src/command_block.rs index 47f808932..1d3fe16ec 100644 --- a/crates/horizon-client/src/command_block.rs +++ b/crates/horizon-client/src/command_block.rs @@ -1,6 +1,7 @@ //! `CommandBlockEntity` with its `BaseCommandBlock`: the command, the success //! count comparators read, the output it keeps, and the powered, automatic //! and condition flags `CommandBlock.tick` runs on. +pub use crate::chunk::block_entity::CommandBlock; use crate::{ save::{number, text}, text::Text, @@ -76,22 +77,6 @@ pub fn automatic_block(name: &str) -> bool { name == "minecraft:chain_command_block" } -#[derive(Clone, Debug, PartialEq)] -pub struct CommandBlock { - pub command: String, - pub success_count: i32, - /// `CustomName` as saved (a text component). - pub custom_name: Option, - pub track_output: bool, - pub last_output: Option, - pub update_last_execution: bool, - /// The game time of the last run, -1 for none. - pub last_execution: i64, - pub powered: bool, - pub auto: bool, - pub condition_met: bool, -} - impl Default for CommandBlock { fn default() -> Self { Self { diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index af867903f..cd232ca94 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -1,6 +1,10 @@ //! Container block entities: chests/barrels (27 slots) and the three furnace //! kinds, ticking as `AbstractFurnaceBlockEntity.serverTick` with fuel times //! from the data-driven `context_int_provider`/`context_float_provider` files. +pub use crate::chunk::block_entity::{ + Banner, Beacon, BlockEntity, Campfire, ChiseledBookshelf, Crafter, CreakingHeart, EndGateway, + Furnace, FurnaceKind, Jukebox, Lectern, Skull, SkullSkin, +}; use crate::{ crafting::Recipes, items::{ItemStack, Items}, @@ -8,12 +12,6 @@ use crate::{ use serde_json::Value; use std::{collections::HashMap, fs, path::Path, sync::Arc}; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum FurnaceKind { - Furnace, - BlastFurnace, - Smoker, -} impl FurnaceKind { pub fn recipe_type(self) -> &'static str { match self { @@ -34,21 +32,6 @@ impl FurnaceKind { } } } -#[derive(Clone, Debug)] -pub struct Furnace { - pub kind: FurnaceKind, - /// input, fuel, result - pub items: [Option; 3], - pub lit_remaining: i32, - pub lit_total: i32, - pub cooking_timer: i32, - pub cooking_total: i32, - pub speed: f32, - /// `AbstractFurnaceBlockEntity.recipesUsed`: how many of each recipe this furnace has - /// made since a player last took from its output. The experience is owed per recipe - /// rather than per item, and a save keeps it as the `RecipesUsed` compound. - pub recipes_used: HashMap, -} /// The key `recipes_used` keeps a recipe under: its full id, as vanilla's `ResourceKey` /// writes it in `RecipesUsed`. Horizon's own recipe ids are file names without the namespace, so /// keeping both forms would write a key twice, and vanilla refuses such a furnace @@ -63,78 +46,6 @@ pub fn recipe_used_key(id: &str) -> String { /// A hopper's slots: the only plain container with five. pub const HOPPER_SLOTS: usize = 5; -#[derive(Clone, Debug)] -pub enum BlockEntity { - Chest(Vec>), - Furnace(Furnace), - Brewing(Box), - /// Signs and hanging signs (`SignBlockEntity`). - Sign(crate::signs::SignData), - /// `JukeboxBlockEntity`: the record and its `JukeboxSongPlayer`. - Jukebox(Jukebox), - /// `BeaconBlockEntity`. - Beacon(Box), - /// `LecternBlockEntity`: the book and the open page. - Lectern(Lectern), - /// Sculk sensors, shriekers and catalysts (`crate::sculk`). - Sculk(Box), - /// `CreakingHeartBlockEntity`: its protector and the hurt emitter. - CreakingHeart(Box), - /// `BannerBlockEntity`: the pattern layers. - Banner(Banner), - /// `CrafterBlockEntity`. - Crafter(Crafter), - /// `SpawnerBlockEntity` (`crate::mobs::spawner`). - Spawner(Box), - /// `TrialSpawnerBlockEntity` (`crate::mobs::trial_spawner`). - TrialSpawner(Box), - /// `VaultBlockEntity` (`crate::vault`). - Vault(Box), - /// `BeehiveBlockEntity` of beehives and bee nests (`crate::beehive`). - Beehive(Box), - /// `CommandBlockEntity` of the three command blocks (`crate::command_block`). - CommandBlock(Box), - /// `CampfireBlockEntity` of campfires and soul campfires. - Campfire(Box), - /// `SkullBlockEntity` of every skull and head block. - Skull(Skull), - /// `TheEndGatewayBlockEntity`: its age and configured destination. - EndGateway(EndGateway), - /// `DaylightDetectorBlockEntity`: no data, only the ticker - /// (`DaylightDetectorBlock.tickEntity`). - DaylightDetector, - /// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots. - ChiseledBookshelf(Box), -} -/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`. -#[derive(Clone, Debug, PartialEq)] -pub struct ChiseledBookshelf { - pub items: [Option; 6], - pub last_slot: i32, -} -impl Default for ChiseledBookshelf { - fn default() -> Self { - Self { - items: Default::default(), - last_slot: -1, - } - } -} -/// `TheEndGatewayBlockEntity`. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct EndGateway { - pub age: i64, - pub exit_portal: Option<[i32; 3]>, - pub exact_teleport: bool, -} -/// `CampfireBlockEntity`: four cooking slots, each with its -/// `cookingProgress` and `cookingTime` (the recipe's). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Campfire { - pub items: [Option; 4], - pub progress: [i32; 4], - pub total: [i32; 4], -} impl Campfire { /// `placeFood`'s slot: the first empty one, given the item's /// `campfire_cooking` time; it takes one item of `held`. @@ -182,17 +93,6 @@ impl Campfire { changed } } -/// `SkullBlockEntity`: the player profile the head shows (kept as loaded: -/// a compound, or a string when it names a player only), the note block -/// sound and `custom_name`. -#[derive(Clone, Debug, Default)] -pub struct Skull { - pub profile: Option, - pub note_block_sound: Option, - pub custom_name: Option, - /// What `profile` draws, read from it once rather than every frame. - pub skin: Option, -} impl Skull { pub fn new( profile: Option, @@ -208,18 +108,6 @@ impl Skull { } } } -/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL -/// with the `skins/` sprite it downloads to, and the -/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a -/// profile with no id). -#[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 { pub fn of(profile: &horizon_world::nbt::Tag) -> Self { let download = crate::skins::profile_skin_url_nbt(profile).and_then(|url| { @@ -248,18 +136,6 @@ impl SkullSkin { fn is_skull(name: &str) -> bool { name.ends_with("_skull") || (name.ends_with("_head") && name != "minecraft:piston_head") } -/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag -/// and the ticks left in the crafting animation. -#[derive(Clone, Debug, Default)] -pub struct Crafter { - pub items: [Option; 9], - pub disabled: [bool; 9], - pub triggered: bool, - pub crafting_ticks: i32, - /// The block state's `triggered` when last ticked (not saved): the block - /// entity flag follows it only when it changes (`CrafterBlock.neighborChanged`). - pub state_triggered: Option, -} impl Crafter { /// `slotCanBeDisabled`: only empty slots. pub fn slot_can_be_disabled(&self, slot: usize) -> bool { @@ -299,48 +175,6 @@ impl Crafter { }) } } -#[derive(Clone, Debug, Default)] -pub struct Banner { - pub layers: Vec, - pub name: Option, - /// Components not consumed by BannerBlockEntity's implicit fields. - pub components: horizon_world::nbt::Compound, -} -/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`). -#[derive(Clone, Debug, Default)] -pub struct CreakingHeart { - /// The protector: its entity id once resolved, and its UUID (the saved form). - pub creaking: Option<(Option, [i32; 4])>, - pub ticks_existed: i64, - pub ticker: i32, - /// Ticks left of the hurt effect (`emitter`) and where it heads. - pub emitter: i32, - pub emitter_target: Option<[f64; 3]>, - pub output_signal: i32, -} -#[derive(Clone, Debug, Default)] -pub struct Lectern { - pub book: Option, - pub page: i32, -} -#[derive(Clone, Debug, Default)] -pub struct Beacon { - pub levels: i32, - /// Effect ids (`minecraft:speed`). - pub primary: Option, - pub secondary: Option, - /// Beam sections (RGB colour, height) and the ones being rebuilt. - pub sections: Vec<(u32, i32)>, - pub checking: Vec<(u32, i32)>, - pub last_check_y: i32, -} -#[derive(Clone, Debug, Default)] -pub struct Jukebox { - pub record: Option, - /// `ticks_since_song_started`, while a song plays. - pub ticks: i64, - pub playing: bool, -} impl BlockEntity { pub fn for_block(name: &str) -> Option { if let Some(hanging) = crate::signs::sign_kind(name) { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index cd8962754..f52bd8e39 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -503,12 +503,7 @@ impl MobTypes { Ok(Self { types: out }) } } -/// Who caused damage or is being targeted. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Who { - Player, - Mob(u32), -} +pub use horizon_client_core::who::Who; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum DamageKind { PlayerAttack, diff --git a/crates/horizon-client/src/mobs/spawner.rs b/crates/horizon-client/src/mobs/spawner.rs index 78b091b7b..4479ada31 100644 --- a/crates/horizon-client/src/mobs/spawner.rs +++ b/crates/horizon-client/src/mobs/spawner.rs @@ -12,24 +12,11 @@ use super::{ spawn_rules::{self, Reason}, spawn_selection::{self, Category, NaturalLevel}, }; +use crate::chunk::block_entity::Next; +pub use crate::chunk::block_entity::{CustomSpawnRules, SpawnData, Spawner}; use horizon_core::{geometry::Aabb, geometry::Vec3, random::RandomSource}; use horizon_world::nbt::{Compound, JavaString, Tag}; -/// `SpawnData.CustomSpawnRules`: the block and sky light the spawn block -/// must have (inclusive ranges within 0..=15). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct CustomSpawnRules { - pub block: (i32, i32), - pub sky: (i32, i32), -} -/// `SpawnData`: the entity to spawn, optional light rules and an equipment -/// table (kept as loaded). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct SpawnData { - pub entity: Compound, - pub custom_spawn_rules: Option, - pub equipment: Option, -} impl SpawnData { /// The `SpawnData` constructor: an `id` that is a valid identifier is /// stored normalised (`zombie` becomes `minecraft:zombie`), any other is @@ -200,33 +187,6 @@ fn encode_range((lo, hi): (i32, i32)) -> Tag { } } -/// Which `SpawnData` is next: one of the potentials (the same object in -/// vanilla, so changing it changes the potential) or its own. -#[derive(Clone, Debug, PartialEq)] -enum Next { - Potential(usize), - Own(SpawnData), -} - -/// `BaseSpawner`. -#[derive(Clone, Debug, PartialEq)] -pub struct Spawner { - pub spawn_delay: i32, - /// `SpawnPotentials`: data and weight. - pub potentials: Vec<(SpawnData, i32)>, - next: Option, - pub min_spawn_delay: i32, - pub max_spawn_delay: i32, - pub spawn_count: i32, - pub max_nearby_entities: i32, - pub required_player_range: i32, - pub spawn_range: i32, - /// The client copy's delay (`spawnDelay` on the client level), which - /// speeds the spin up as the next spawn nears. - pub client_delay: i32, - pub spin: f64, - pub o_spin: f64, -} impl Default for Spawner { fn default() -> Self { Self { diff --git a/crates/horizon-client/src/mobs/trial_spawner.rs b/crates/horizon-client/src/mobs/trial_spawner.rs index 2314d9f45..e789f14fb 100644 --- a/crates/horizon-client/src/mobs/trial_spawner.rs +++ b/crates/horizon-client/src/mobs/trial_spawner.rs @@ -13,6 +13,7 @@ use super::{ spawn_selection, spawner::{self, SpawnData, SpawnerLevel, SpawnerSpawn}, }; +pub use crate::chunk::block_entity::{ConfigSlot, TrialConfig, TrialSpawner}; use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::nbt::{Compound, JavaString, Tag}; use std::{collections::HashMap, path::Path, sync::OnceLock}; @@ -32,19 +33,6 @@ const TICKS_BETWEEN_ITEM_SPAWNERS: i64 = 160; /// Bad Omen. pub const TRIAL_OMEN_TICKS_PER_LEVEL: i32 = 18000; -/// `TrialSpawnerConfig`. -#[derive(Clone, Debug, PartialEq)] -pub struct TrialConfig { - pub spawn_range: i32, - pub total_mobs: f32, - pub simultaneous_mobs: f32, - pub total_mobs_added_per_player: f32, - pub simultaneous_mobs_added_per_player: f32, - pub ticks_between_spawn: i32, - pub spawn_potentials: Vec<(SpawnData, i32)>, - pub loot_tables_to_eject: Vec<(String, i32)>, - pub items_to_drop_when_ominous: String, -} impl Default for TrialConfig { /// `TrialSpawnerConfig.Builder`'s defaults. fn default() -> Self { @@ -202,15 +190,6 @@ fn identifier(t: Option<&Tag>) -> Option { } } -/// A `Holder` as saved: a registry id -/// (`minecraft:trial_chamber/breeze/normal`) or an inline config. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct ConfigSlot { - /// The value as loaded, written back as is; None for the default. - pub saved: Option, - pub config: TrialConfig, -} - /// `TrialSpawnerState`. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub enum TrialState { @@ -335,31 +314,6 @@ pub trait TrialSpawnerLevel: SpawnerLevel { fn seed(&self) -> i64; } -/// `TrialSpawner` with its `TrialSpawnerStateData`. -#[derive(Clone, Debug, PartialEq)] -pub struct TrialSpawner { - pub normal: ConfigSlot, - pub ominous: ConfigSlot, - pub target_cooldown_length: i32, - pub required_player_range: i32, - pub detected_players: Vec, - pub current_mobs: Vec, - pub cooldown_ends_at: i64, - pub next_mob_spawns_at: i64, - pub total_mobs_spawned: i32, - pub next_spawn_data: Option, - pub ejecting_loot_table: Option, - /// `isOminous`, set from the block on every server tick. - pub is_ominous: bool, - /// The server's display entity exists (`getOrCreateDisplayEntity`): it is - /// made once per loaded block entity and kept. - pub has_display: bool, - pub spin: f64, - pub o_spin: f64, - /// `getDispensingItems`, kept once rolled (not saved): the ominous items - /// and their weights (the rolled counts). - pub dispensing: Option>, -} impl Default for TrialSpawner { fn default() -> Self { Self { diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index eefedaa98..97a2187cb 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -1,6 +1,7 @@ //! Game events and the vibration system (`GameEvent`, `VibrationSystem`, //! `VibrationSelector`) shared by sculk sensors, shriekers and wardens, the //! sculk block entities and the per-player warden spawn tracker. +pub use crate::chunk::block_entity::{Data, Info, SculkEntity, SculkKind, Selector}; use crate::mobs::Who; use horizon_core::{ geometry::{Direction, Vec3, traverse_blocks}, @@ -185,20 +186,6 @@ pub fn valid_vibration(listens: bool, event: &str, ctx: &Context) -> bool { !ctx.dampening_state } -/// `VibrationInfo`. -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct Info { - pub event: &'static str, - pub distance: f32, - pub pos: [f64; 3], - pub source: Option, - pub owner: Option, -} -/// `VibrationSelector`: the closest, then highest-frequency candidate of a tick. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Selector { - current: Option<(Info, i64)>, -} impl Selector { pub fn add_candidate(&mut self, new: Info, tick: i64) { if self.should_replace(&new, tick) { @@ -233,13 +220,6 @@ impl Selector { self.current } } -/// `VibrationSystem.Data`. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct Data { - pub current: Option, - pub travel: i32, - pub selector: Selector, -} /// What one `VibrationSystem.Ticker.tick` did. #[derive(Clone, Debug, Default, PartialEq)] pub struct Tick { @@ -382,27 +362,6 @@ pub fn is_occluded( true } -/// Which sculk block entity this is. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum SculkKind { - Sensor, - Calibrated, - Shrieker, - Catalyst, -} -/// `SculkSensorBlockEntity`, `CalibratedSculkSensorBlockEntity`, -/// `SculkShriekerBlockEntity` and `SculkCatalystBlockEntity`. -#[derive(Clone, Debug)] -pub struct SculkEntity { - pub kind: SculkKind, - pub vibration: Data, - /// `last_vibration_frequency` (sensors). - pub last_frequency: i32, - /// `warning_level` (shriekers). - pub warning_level: i32, - /// The catalyst's charge cursors. - pub spreader: SculkSpreader, -} impl SculkEntity { pub fn new(kind: SculkKind) -> Self { Self { diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs index 799210797..50559e9ae 100644 --- a/crates/horizon-client/src/signs.rs +++ b/crates/horizon-client/src/signs.rs @@ -1,6 +1,7 @@ //! Sign block entities (`SignBlockEntity`, `SignText`): two four-line text //! sides with a dye colour and glow, saved in vanilla's `front_text` / //! `back_text` NBT layout. +pub use crate::chunk::block_entity::{SignData, SignText}; use horizon_world::nbt::Tag; /// `DyeColor` names and `getTextColor` values by id. @@ -24,14 +25,6 @@ pub const DYE_TEXT: [(&str, u32); 16] = [ ]; const BLACK: u8 = 15; -/// One sign side (`SignText`). -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct SignText { - pub lines: [String; 4], - /// `DyeColor` id. - pub color: u8, - pub glowing: bool, -} impl Default for SignText { fn default() -> Self { Self { @@ -61,14 +54,6 @@ impl SignText { } } -/// `SignBlockEntity` / `HangingSignBlockEntity` data. -#[derive(Clone, Debug, Default, PartialEq, Eq)] -pub struct SignData { - pub hanging: bool, - pub front: SignText, - pub back: SignText, - pub waxed: bool, -} impl SignData { pub fn id(&self) -> &'static str { if self.hanging { diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index 740208973..76bb79f6c 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -160,13 +160,7 @@ pub(crate) fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option } } -/// `Either`: the key a `Dynamic` `ResolvableProfile` resolves -/// by (`ResolvableProfile.nameOrId`). -#[derive(Clone, Debug, PartialEq, Eq, Hash)] -pub enum NameOrId { - Name(String), - Id(u128), -} +pub use crate::chunk::block_entity::NameOrId; /// `GameProfile` as `fetchProfile` returns it: the account's id, name and /// property map (its `textures` property is the skin). diff --git a/crates/horizon-client/src/vault.rs b/crates/horizon-client/src/vault.rs index 38e5d29d7..919ba8e56 100644 --- a/crates/horizon-client/src/vault.rs +++ b/crates/horizon-client/src/vault.rs @@ -7,6 +7,7 @@ //! the next one. The level's random draws the display item and throws the //! rewards; the loot tables go through the caller, so the game and a //! differential test world roll them the same way. +pub use crate::chunk::block_entity::{Vault, VaultConfig}; use crate::items::ItemStack; use horizon_core::random::RandomSource; use horizon_world::nbt::{Compound, Tag}; @@ -26,17 +27,6 @@ const UNLOCKING_DELAY: i64 = 14; const INSERT_FAIL_SOUND_BUFFER: i64 = 15; const STATE_DELAY: i64 = 20; -/// `VaultConfig`. -#[derive(Clone, Debug, PartialEq)] -pub struct VaultConfig { - pub loot_table: String, - pub activation_range: f64, - pub deactivation_range: f64, - /// None when the config has no key (`ItemStack.EMPTY`): the vault never opens. - pub key_item: Option, - pub override_loot_table_to_display: Option, -} - impl Default for VaultConfig { /// `VaultConfig.DEFAULT`: the trial key and the trial chambers' reward. fn default() -> Self { @@ -169,28 +159,6 @@ pub trait VaultLevel { /// the table has one. pub type Roll<'a, R> = dyn FnMut(&str, &mut R, bool) -> Vec + 'a; -/// `VaultBlockEntity`: its config, server data and shared data. -#[derive(Clone, Debug, PartialEq)] -pub struct Vault { - pub config: VaultConfig, - /// `VaultServerData`, oldest rewarded player first. - pub rewarded_players: Vec, - pub state_updating_resumes_at: i64, - /// Popped from the end. - pub items_to_eject: Vec, - pub total_ejections_needed: i32, - pub last_insert_fail_timestamp: i64, - /// `VaultSharedData`. - pub display_item: Option, - pub connected_players: Vec, - pub connected_particles_range: f64, - /// The shared data changed since the last tick sent it. - pub shared_dirty: bool, - /// `VaultClientData`: the display item's spin and the previous tick's, in degrees. - pub spin: f32, - pub o_spin: f32, -} - impl Default for Vault { fn default() -> Self { Self { diff --git a/tools/test_spawner_parity.py b/tools/test_spawner_parity.py index 34f6ec726..f94324cc9 100644 --- a/tools/test_spawner_parity.py +++ b/tools/test_spawner_parity.py @@ -232,6 +232,7 @@ def main(): oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', + lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) diff --git a/tools/test_trial_spawner_parity.py b/tools/test_trial_spawner_parity.py index 43d26338a..6f588b785 100644 --- a/tools/test_trial_spawner_parity.py +++ b/tools/test_trial_spawner_parity.py @@ -197,6 +197,7 @@ def main(): sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', lab.ROOT / 'crates/horizon-client/src/mobs/trial_spawner.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawner.rs', + lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_selection.rs', lab.ROOT / 'crates/horizon-client/src/mobs/spawn_rules.rs'] tested = base.source_hashes(sources) diff --git a/tools/test_vault_parity.py b/tools/test_vault_parity.py index 00e6422f5..d3025623d 100644 --- a/tools/test_vault_parity.py +++ b/tools/test_vault_parity.py @@ -174,7 +174,8 @@ def main(): resources = lab.LOCAL / 'horizon-client/26.3' oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaNaturalSpawnOracle.java' sources = [oracle, Path(__file__), lab.ROOT / 'crates/horizon-client/examples/probe/natural_spawn_fixture.rs', - lab.ROOT / 'crates/horizon-client/src/vault.rs'] + lab.ROOT / 'crates/horizon-client/src/vault.rs', + lab.ROOT / 'crates/horizon-client/src/chunk/block_entity.rs'] tested = base.source_hashes(sources) inputs = build / 'inputs.txt' cases = corpus() From 99ce9afd638a784ebfe16964fed0e75240c0da5e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:20:32 +0100 Subject: [PATCH 207/221] Launcher: the Nightly setting says reviewers pick its pull requests nightly-2: a Nightly can include pull requests not reviewed yet, picked by trusted reviewers (docs/release-flow.md "Nightly channel"). The Settings row says so, in English, French and Russian. Co-Authored-By: Claude Opus 5.5 --- launcher/lang/fr.json | 2 +- launcher/lang/ru.json | 2 +- launcher/src/main.rs | 4 +++- launcher/src/nightly.rs | 5 +++-- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/launcher/lang/fr.json b/launcher/lang/fr.json index 315924ce1..b92252a92 100644 --- a/launcher/lang/fr.json +++ b/launcher/lang/fr.json @@ -160,7 +160,7 @@ "Prepared for Minecraft {version}": "Préparé pour Minecraft {version}", "Prepared for Minecraft {version}, without its sounds: the game will be silent. Prepare again to copy them from your Minecraft install.": "Préparé pour Minecraft {version}, sans ses sons : le jeu sera muet. Préparez à nouveau pour les copier depuis votre installation de Minecraft.", "Nightly builds": "Versions Nightly", - "Reviewed fixes not released yet; may break.": "Des correctifs relus, pas encore publiés ; peut casser.", + "Can include pull requests not reviewed yet, picked by trusted reviewers; may break.": "Peut inclure des pull requests pas encore relues, choisies par des relecteurs de confiance ; peut casser.", "Plays in its own Nightly instance: your worlds and the release stay as they are.": "Se joue dans sa propre instance Nightly : vos mondes et la version publiée restent tels quels.", "Installing the nightly, {percent}%": "Installation de la Nightly, {percent} %", "The nightly could not be installed: {error}": "La Nightly n'a pas pu être installée : {error}", diff --git a/launcher/lang/ru.json b/launcher/lang/ru.json index 0464b8808..753132e4b 100644 --- a/launcher/lang/ru.json +++ b/launcher/lang/ru.json @@ -160,7 +160,7 @@ "Prepared for Minecraft {version}": "Подготовлено для Minecraft {version}", "Prepared for Minecraft {version}, without its sounds: the game will be silent. Prepare again to copy them from your Minecraft install.": "Подготовлено для Minecraft {version}, но без звуков: игра будет беззвучной. Подготовьте заново, чтобы скопировать их из вашей установки Minecraft.", "Nightly builds": "Ночные сборки", - "Reviewed fixes not released yet; may break.": "Проверенные исправления, ещё не вышедшие в релиз; что-то может сломаться.", + "Can include pull requests not reviewed yet, picked by trusted reviewers; may break.": "Может включать ещё не проверенные pull request'ы, выбранные доверенными ревьюерами; что-то может сломаться.", "Plays in its own Nightly instance: your worlds and the release stay as they are.": "Запускается в отдельной сборке Nightly: ваши миры и релиз остаются как есть.", "Installing the nightly, {percent}%": "Установка ночной сборки, {percent}%", "The nightly could not be installed: {error}": "Не удалось установить ночную сборку: {error}", diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 78cd56bd7..eefc653ac 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -2901,7 +2901,9 @@ impl Launcher { this.set_nightly(!this.settings.nightly); cx.notify(); })); - let what = tr("Reviewed fixes not released yet; may break."); + let what = tr( + "Can include pull requests not reviewed yet, picked by trusted reviewers; may break.", + ); let status = match (&self.nightly_progress, &self.nightly_error) { _ if !on => tr("Plays in its own Nightly instance: your worlds and the release stay as they are.") .to_string(), diff --git a/launcher/src/nightly.rs b/launcher/src/nightly.rs index d5f75e8ab..4aed66434 100644 --- a/launcher/src/nightly.rs +++ b/launcher/src/nightly.rs @@ -1,5 +1,6 @@ -//! Nightly (docs/release-flow.md "Nightly channel"): an opt-in build of reviewed fixes not released -//! yet, published each night as the `nightly` pre-release. Off by default (`Settings::nightly`). +//! Nightly (docs/release-flow.md "Nightly channel"): an opt-in build of main plus pull requests +//! picked by trusted reviewers, some not reviewed yet, published as the `nightly` pre-release each +//! night and when a reviewer asks. Off by default (`Settings::nightly`). //! //! It never touches the release: it installs as its own version, `nightly--`, and plays //! in its own instance, "Nightly" (`instances/nightly/` in the game's home), so the player's worlds From 8d5424408c2bf1d1d5ab512acccbd5a01671b91f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:26:51 +0100 Subject: [PATCH 208/221] Nightly: nothing an unreviewed build leaves reaches a release Orchestrator's review of #2859: a nightly can hold pull requests nobody reviewed yet, and their build scripts run in `build`. game-build.yml gets a `trusted` input, true only from release.yml: - the Rust cache (GitHub-hosted Linux and Windows): its own key for an untrusted build (`nightly-`), never saved; a release restores only what a release saved; - macOS: an untrusted build's exporters and build jobs run on the runner that already runs pull requests' parity jobs (macOS + horizon-game), never the release runner (MAC_RUNNER) nor parity-main's; - a trusted build doesn't read the machine's shared sccache, which pull requests' jobs write (runner-env.sh: HORIZON_NO_SCCACHE). tests/test_nightly.py pins all three. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/game-build.yml | 25 +++++++++++++++++---- .github/workflows/nightly-build.yml | 4 ++++ .github/workflows/release.yml | 1 + docs/release-flow.md | 6 ++++- tests/test_nightly.py | 35 +++++++++++++++++++++++++++++ tools/ci/runner-env.sh | 5 +++-- 6 files changed, 69 insertions(+), 7 deletions(-) diff --git a/.github/workflows/game-build.yml b/.github/workflows/game-build.yml index 65acf1b28..7e075ea63 100644 --- a/.github/workflows/game-build.yml +++ b/.github/workflows/game-build.yml @@ -19,6 +19,15 @@ on: description: A nightly's " " (HORIZON_NIGHTLY), shown by the game; empty for a release type: string default: '' + trusted: + # Only release.yml says true: it builds main. A nightly can hold pull requests nobody reviewed yet, whose + # build scripts and tests run here and could rewrite target/, the cargo home or a compiler cache. So an + # untrusted build never runs on the release runner, never saves the Rust cache (its key is its own anyway), + # and a trusted one never reads the machine's shared sccache, which pull requests' jobs write + # (tests/test_nightly.py pins all of it). + description: The source is main (a release); false for anything else (a nightly) + type: boolean + default: false developer_id: description: Sign the macOS programs with Developer ID and notarize the zip (the runner's keychain) type: boolean @@ -27,8 +36,10 @@ permissions: contents: read jobs: exporters: - # This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it. - runs-on: ${{ vars.MAC_RUNNER || 'ludovics-mac-mini' }} + # This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it. An untrusted build + # goes to the Mac mini runner that already runs pull requests' parity jobs (macOS + horizon-game: + # ludovics-mac-mini), never the release runner (MAC_RUNNER: ludovics-mac-mini-release) nor parity-main's. + runs-on: ${{ inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]') }} # Three full preparations (two isolated, one batched) besides the compile. timeout-minutes: 60 steps: @@ -39,6 +50,8 @@ jobs: clean: true - uses: dtolnay/rust-toolchain@stable - run: bash tools/ci/runner-env.sh + env: + HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }} - run: bash tools/ci/vanilla-data.sh - name: Compile and validate original exporters against the pinned jars shell: bash @@ -90,7 +103,7 @@ jobs: mac: true dir: horizon-macos-arm64 asset: horizon-macos-arm64.zip - runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }} + runs-on: ${{ matrix.mac && (inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]')) || matrix.os }} # Notarizing the zip can take a few minutes. timeout-minutes: ${{ matrix.mac && 60 || 40 }} env: @@ -117,7 +130,9 @@ jobs: - uses: Swatinem/rust-cache@v2 if: runner.environment == 'github-hosted' with: - shared-key: release-${{ matrix.name }} + # A release restores only what a release saved: an untrusted build has its own key and saves nothing. + shared-key: ${{ inputs.trusted && 'release' || 'nightly' }}-${{ matrix.name }} + save-if: ${{ inputs.trusted }} - name: ALSA and udev headers if: runner.os == 'Linux' run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev @@ -173,6 +188,8 @@ jobs: done - name: Tools from the runner if: runner.environment == 'self-hosted' + env: + HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }} run: bash tools/ci/runner-env.sh - name: Resources prepared from the runner's own Minecraft if: runner.environment == 'self-hosted' diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index e71e061b0..24b6974a5 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -14,6 +14,9 @@ run-name: nightly build${{ inputs.request && format(' (request {0})', inputs.req # pushes the merge as nightly/build-- and saves the set on the nightly-state branch. # - This file, game-build.yml and every script below run from main's copy: a schedule runs the default branch, and # `uses: ./…` takes the caller's commit. The union's own .github/ is never read. +# - `build` (game-build.yml, `trusted: false`) never reaches a release's tools: its macOS jobs run on the runner +# that already runs pull requests' parity jobs, never the release runner; its Rust cache has its own key and is +# never saved; and releases don't read the machine's shared sccache. # - `build` (game-build.yml) checks out and compiles the merge (or the union) with no secrets: its token reads contents only and # isn't kept in the checkout; the macOS programs are signed ad hoc (Developer ID needs the runner's keychain, # which stays locked for nightlies). @@ -107,6 +110,7 @@ jobs: version: ${{ needs.pick.outputs.version }} nightly: ${{ needs.pick.outputs.nightly }} developer_id: false + trusted: false # it can hold unreviewed pull requests: their own cache key, never saved, not the release runner sign: needs: [pick, build] diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 92738c330..0065a380a 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -90,6 +90,7 @@ jobs: with: ref: ${{ needs.decide.outputs.head }} version: ${{ needs.decide.outputs.version }} + trusted: true # main: the release runner, the release cache, no shared sccache sign: needs: [decide, build] diff --git a/docs/release-flow.md b/docs/release-flow.md index fdf6e97ce..1089b9444 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -474,7 +474,11 @@ comment on any issue or pull request (`.github/workflows/nightly-command.yml`, ` merge with a read-only token that isn't kept in the checkout and no secrets; the runner's Developer ID keychain stays locked. `sign` is the only job with the key, and checks out only main's `tools/ci/sign_release.sh`, which hashes the archives with the runner's `sha256sum` and signs with its OpenSSL: it never runs what `build` made. - `publish` runs main's `horizon-release-sign`, never the archives. + `publish` runs main's `horizon-release-sign`, never the archives. Nothing a nightly's build leaves reaches a + release either: `game-build.yml`'s `trusted` input is true only for `release.yml`. An untrusted build runs its + macOS jobs on the runner that runs pull requests' parity jobs (`horizon-game`), never the release runner + (`MAC_RUNNER`), and its Rust cache has its own key and is never saved. A trusted build doesn't use the machine's + shared sccache, which pull requests' jobs write (`HORIZON_NO_SCCACHE`, `tools/ci/runner-env.sh`). - **Players.** Releases stay the default and the only channel any launcher follows unless its player turns Nightly on. `release_train.py`, `horizon-server update`, `install.sh` and the launcher's release list skip the tags: none of them is `vX.Y.Z`. diff --git a/tests/test_nightly.py b/tests/test_nightly.py index 2916351b7..c44416044 100644 --- a/tests/test_nightly.py +++ b/tests/test_nightly.py @@ -85,3 +85,38 @@ class ScheduledTests(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +WORKFLOWS = Path(__file__).resolve().parents[1] / ".github" / "workflows" + + +class UntrustedBuildTests(unittest.TestCase): + """A nightly can hold unreviewed pull requests: nothing its build leaves may reach a release (game-build.yml).""" + + def setUp(self): + self.game = (WORKFLOWS / "game-build.yml").read_text() + + def test_only_the_release_is_trusted(self): + self.assertIn("trusted: true", (WORKFLOWS / "release.yml").read_text()) + nightly_build = (WORKFLOWS / "nightly-build.yml").read_text() + self.assertIn("trusted: false", nightly_build) + self.assertNotIn("trusted: true", nightly_build) + self.assertIn("default: false", self.game.split("trusted:", 1)[1].split("developer_id:", 1)[0]) + + def test_an_untrusted_build_neither_shares_nor_saves_the_release_cache(self): + self.assertIn("shared-key: ${{ inputs.trusted && 'release' || 'nightly' }}-${{ matrix.name }}", self.game) + self.assertIn("save-if: ${{ inputs.trusted }}", self.game) + self.assertEqual(self.game.count("Swatinem/rust-cache"), 1) + + def test_an_untrusted_build_never_runs_on_the_release_runner(self): + runs_on = [line for line in self.game.splitlines() if "runs-on:" in line] + self.assertEqual(len(runs_on), 2) + pr_runner = "fromJSON('[\"self-hosted\", \"macOS\", \"horizon-game\"]')" + for line in runs_on: + self.assertIn(f"inputs.trusted && vars.MAC_RUNNER || {pr_runner}", line) + + def test_a_trusted_build_never_reads_the_shared_sccache(self): + calls = self.game.count("bash tools/ci/runner-env.sh") + self.assertEqual(self.game.count("HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }}"), calls) + env = (Path(__file__).resolve().parents[1] / "tools/ci/runner-env.sh").read_text() + self.assertEqual(env.count('-z "${HORIZON_NO_SCCACHE:-}"'), 2) diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh index 14e9e6762..189bba980 100755 --- a/tools/ci/runner-env.sh +++ b/tools/ci/runner-env.sh @@ -15,7 +15,8 @@ if [ "$(uname)" = Darwin ]; then echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV" # Builds go through the machine's sccache (shared with ~/fleet/rbuild), so the build folders runner-gc.sh # removes come back from the cache instead of compiling cold. - if [ -x /opt/homebrew/bin/sccache ]; then + # Not for a release (HORIZON_NO_SCCACHE=1, game-build.yml's trusted builds): pull requests' jobs write that cache. + if [ -x /opt/homebrew/bin/sccache ] && [ -z "${HORIZON_NO_SCCACHE:-}" ]; then { echo "RUSTC_WRAPPER=/opt/homebrew/bin/sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV" fi else @@ -40,7 +41,7 @@ else [ -n "$java_home" ] || { echo "::error::no JDK $java_major on this runner"; exit 1; } { echo "$bin"; echo "$java_home/bin"; } >> "$GITHUB_PATH" echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV" - if sccache=$(command -v sccache); then + if [ -z "${HORIZON_NO_SCCACHE:-}" ] && sccache=$(command -v sccache); then { echo "RUSTC_WRAPPER=$sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV" fi fi From 967a9363ceec4e58f8dd6a42e32aca6d2fd28898 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:35:07 +0100 Subject: [PATCH 209/221] entity_death_loot: give wolves their gear in the body slot Horizon now keeps a wolf's body armour in its head slot, as for the other BODY types. Co-Authored-By: Claude Opus 5.5 --- tools/test_entity_death_loot_parity.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/test_entity_death_loot_parity.py b/tools/test_entity_death_loot_parity.py index 2bb53ebbb..39aa6edda 100644 --- a/tools/test_entity_death_loot_parity.py +++ b/tools/test_entity_death_loot_parity.py @@ -31,7 +31,7 @@ SKIPPED = {'player', 'mannequin', 'armor_stand', 'ender_dragon', 'giant'} # Types Horizon keeps body armour for in the head slot: their corpus wears # body items instead of helmets. BODY = {'horse', 'donkey', 'mule', 'skeleton_horse', 'zombie_horse', 'camel', 'camel_husk', 'llama', 'trader_llama', - 'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube'} + 'happy_ghast', 'nautilus', 'zombie_nautilus', 'sulfur_cube', 'wolf'} WEAPONS = ['minecraft:iron_sword', 'minecraft:diamond_sword;looting:1', 'minecraft:diamond_sword;looting:2', 'minecraft:netherite_sword;looting:3', 'minecraft:golden_sword;fire_aspect:2', 'minecraft:diamond_axe;looting:3;fire_aspect:1'] ARMOUR = {'head': 'minecraft:iron_helmet', 'chest': 'minecraft:chainmail_chestplate', 'legs': 'minecraft:golden_leggings', From 1bd74d1b2f358bb878ddf432539fc5bcc015d6cd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:35:07 +0100 Subject: [PATCH 210/221] Skip the world spawn trip's teleport when the respawn already put the player there Vanilla teleports a respawning player once; the second, identical move showed up in the dedicated_server, pearl_death and cursor_death harnesses. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/server_travel.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index ac983dff1..e516d3f67 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -423,6 +423,9 @@ impl Game<'_> { let suggestion = [trip.target.x, trip.target.y, trip.target.z].map(|v| v.floor() as i32); match self.search_spawn(suggestion, &mut trip.finder) { + // The respawn already put the player on this column: + // vanilla teleports once, so no second move. + Ok(at) if host.hub.guests[i].position == [at.x, at.y, at.z] => continue, Ok(at) => (at, yaw), Err(chunk) => { self.spawn_wait.push(chunk); From 854bcb158f78d8af9c6cfea262603bca6ad5c245 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:35:08 +0100 Subject: [PATCH 211/221] random_tick probe: a fresh suspicious block's reset check changes nothing Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/examples/probe/block_update_fixture.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/examples/probe/block_update_fixture.rs b/crates/horizon-world/examples/probe/block_update_fixture.rs index 5be9be731..fdb5e20e0 100644 --- a/crates/horizon-world/examples/probe/block_update_fixture.rs +++ b/crates/horizon-world/examples/probe/block_update_fixture.rs @@ -427,9 +427,11 @@ pub fn main() -> Result<(), Box> { // A fresh shrieker has warning level 0 and so never responds, // and no player is near enough for a portal to spawn a piglin. // A fresh command block has no command and is neither powered - // nor always active: `CommandBlock.tick` changes nothing. + // nor always active: `CommandBlock.tick` changes nothing. A + // fresh suspicious block was never brushed, so + // `BrushableBlockEntity.checkReset` has nothing to reset. LevelEvent::BlockEvent { - kind: "shrieker_respond" | "portal_spawn" | "command_block", + kind: "shrieker_respond" | "portal_spawn" | "command_block" | "brushable", .. } => {} LevelEvent::BlockEvent { kind, .. } => { From 9914a8af4113d595361cad8c02c576e4f30e1667 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:47:06 +0100 Subject: [PATCH 212/221] Name the wither's client smoke tick client_smoke #2685 adds wither::client_tick for the side heads' turning on a client; a distinct name lets both land without a clash. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 2 +- crates/horizon-client/src/mobs/wither.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 7e145b952..8d6479076 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3796,7 +3796,7 @@ impl Game<'_> { S::Slime | S::MagmaCube | S::SulfurCube => cube::client_tick(m, &mut mob_fx), S::Nautilus | S::ZombieNautilus => nautilus::client_tick(m, &mut mob_fx), S::Illusioner => illusioner::client_tick(m, &mut mob_fx), - S::Wither => wither::client_tick(m, &mut mob_fx), + S::Wither => wither::client_smoke(m, &mut mob_fx), _ => {} } } diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index c8248106c..0a429b135 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -173,7 +173,7 @@ fn target_pos(w: &MobWorld, id: i32) -> Option<([f64; 3], f64, bool)> { /// (`radius` 0.3 of the wither's scale, which is 1 here). The heads' turning /// and the coloured particles need the server's targets and invulnerable /// ticks, which a client is not sent. -pub fn client_tick(m: &mut Mob, events: &mut Vec) { +pub fn client_smoke(m: &mut Mob, events: &mut Vec) { for i in 0..3 { let h = head_pos(m, i); let r = &mut m.random; From 8d2b2982534d6422dedd7257f3dbae0462e400fd Mon Sep 17 00:00:00 2001 From: leifiyoo Date: Tue, 27 Oct 2026 16:53:00 +0100 Subject: [PATCH 213/221] Keep long Microsoft sign-in secrets in several keychain items Credential Manager takes at most 2560 bytes per item. The secrets of a Microsoft sign-in (the refresh token and the Minecraft token) are longer, so saving them failed on Windows with "password encoded as UTF-16 is longer than platform limit of 2560 chars" and the sign-in did not finish. On macOS and Windows a secret is now split over the items ``, `.1`, `.2`... of at most 1000 UTF-8 bytes each (under 2560 bytes of UTF-16). Reads join the pieces, a write removes the leftovers of a longer secret, and sign-out removes all of them. Existing single items keep working. Co-Authored-By: Claude Haiku 5.5 --- docs/microsoft-account.md | 3 +- launcher/src/account.rs | 96 +++++++++++++++++++++++++++++++---- launcher/src/account/tests.rs | 30 +++++++++++ 3 files changed, 117 insertions(+), 12 deletions(-) diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 380aa0785..eeb63f56a 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -74,7 +74,8 @@ one is selected. "Sign out" deletes the account's secrets from the keychain. - Secrets (the Microsoft refresh token, the Minecraft access token and its expiry) go to the OS keychain, one item per account: Keychain on macOS, Credential Manager on Windows, the Secret Service (GNOME Keyring, KWallet) on Linux. Service name `dev.playhorizon.launcher`, account = the - Minecraft UUID. + Minecraft UUID. Credential Manager takes at most 2560 bytes per item, which the secrets of a sign-in + exceed: on macOS and Windows a longer secret is split over the items ``, `.1`, `.2`... - `accounts.json` in the launcher's data folder keeps only public data: UUID, name, skin URL, which account is selected. Never a token. - No keychain available (a Linux box without a Secret Service, a locked keychain): sign-in still diff --git a/launcher/src/account.rs b/launcher/src/account.rs index 257055911..313dbb2f8 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -580,28 +580,102 @@ impl SecretStore for SystemStore { } } -/// Keychain on macOS, Credential Manager on Windows (the keyring crate). +/// Keychain on macOS, Credential Manager on Windows (the keyring crate). Credential Manager takes at +/// most 2560 bytes of UTF-16 per item and a sign-in's secrets are longer, so a secret is kept in +/// pieces: the first under the account's key, the rest under `key.1`, `key.2`... #[cfg(any(target_os = "macos", target_os = "windows"))] pub struct SystemStore; + +/// Bytes of UTF-8 per keychain item: at most twice as many in UTF-16, well under 2560. +#[cfg(any(target_os = "macos", target_os = "windows"))] +const PIECE: usize = 1000; + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn piece_key(key: &str, n: usize) -> String { + if n == 0 { + key.to_string() + } else { + format!("{key}.{n}") + } +} + +/// `secret` cut into pieces of at most `PIECE` bytes, on character boundaries. +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn split_secret(mut secret: &str) -> Vec<&str> { + let mut pieces = Vec::new(); + while secret.len() > PIECE { + let mut cut = PIECE; + while !secret.is_char_boundary(cut) { + cut -= 1; + } + let (head, tail) = secret.split_at(cut); + pieces.push(head); + secret = tail; + } + pieces.push(secret); + pieces +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn read_item(key: &str) -> Result, String> { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.get_password()) { + Ok(secret) => Ok(Some(secret)), + Err(keyring::Error::NoEntry) => Ok(None), + Err(e) => Err(e.to_string()), + } +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn write_item(key: &str, secret: &str) -> Result<(), String> { + keyring::Entry::new(SERVICE, key) + .and_then(|e| e.set_password(secret)) + .map_err(|e| e.to_string()) +} + +/// Removes one item; false when there was none. +#[cfg(any(target_os = "macos", target_os = "windows"))] +fn remove_item(key: &str) -> Result { + match keyring::Entry::new(SERVICE, key).and_then(|e| e.delete_credential()) { + Ok(()) => Ok(true), + Err(keyring::Error::NoEntry) => Ok(false), + Err(e) => Err(e.to_string()), + } +} + #[cfg(any(target_os = "macos", target_os = "windows"))] impl SecretStore for SystemStore { fn get(&self, key: &str) -> Result, String> { - match keyring::Entry::new(SERVICE, key).and_then(|e| e.get_password()) { - Ok(secret) => Ok(Some(secret)), - Err(keyring::Error::NoEntry) => Ok(None), - Err(e) => Err(e.to_string()), + let Some(mut secret) = read_item(key)? else { + return Ok(None); + }; + for n in 1.. { + match read_item(&piece_key(key, n))? { + Some(piece) => secret.push_str(&piece), + None => break, + } } + Ok(Some(secret)) } fn set(&self, key: &str, secret: &str) -> Result<(), String> { - keyring::Entry::new(SERVICE, key) - .and_then(|e| e.set_password(secret)) - .map_err(|e| e.to_string()) + let pieces = split_secret(secret); + for (n, piece) in pieces.iter().enumerate() { + write_item(&piece_key(key, n), piece)?; + } + // Pieces left over from a longer secret would be read back as part of this one. + for n in pieces.len().. { + if !remove_item(&piece_key(key, n))? { + break; + } + } + Ok(()) } fn delete(&self, key: &str) -> Result<(), String> { - match keyring::Entry::new(SERVICE, key).and_then(|e| e.delete_credential()) { - Ok(()) | Err(keyring::Error::NoEntry) => Ok(()), - Err(e) => Err(e.to_string()), + for n in 0.. { + if !remove_item(&piece_key(key, n))? { + break; + } } + Ok(()) } fn persistent(&self) -> bool { true diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs index ec3766c7e..6d0152722 100644 --- a/launcher/src/account/tests.rs +++ b/launcher/src/account/tests.rs @@ -372,6 +372,36 @@ fn accounts_keep_secrets_in_the_store_only() { assert!(!store.persistent()); } +/// The OS keychain itself: Credential Manager and the Keychain take one secret per item, and a +/// sign-in's secrets are longer than one item holds. Ignored by default: it writes to the keychain +/// (a test key, removed again). +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +#[ignore = "writes to the OS keychain"] +fn system_keychain_keeps_long_secrets() { + let key = "test-long-secret"; + let secret = format!("{{\"refresh_token\":\"{}\"}}", "r".repeat(3000)); + SystemStore.set(key, &secret).unwrap(); + assert_eq!(SystemStore.get(key).unwrap(), Some(secret.clone())); + SystemStore.delete(key).unwrap(); + assert_eq!(SystemStore.get(key).unwrap(), None); +} + +#[cfg(any(target_os = "macos", target_os = "windows"))] +#[test] +fn long_secrets_split_into_keychain_sized_pieces() { + // Mixed 1-, 2- and 4-byte characters, so the cuts land inside some of them. + let secret = "aé🔑".repeat(300); + let pieces = split_secret(&secret); + assert!(pieces.len() > 1); + assert_eq!(pieces.concat(), secret); + for piece in &pieces { + assert!(piece.len() <= PIECE); + assert!(piece.encode_utf16().count() * 2 <= 2560); + } + assert_eq!(split_secret("short"), vec!["short"]); +} + #[test] fn session_files_are_private_and_complete() { let dir = std::env::temp_dir().join(format!("horizon-launcher-session-{}", std::process::id())); From 674596103f0ef695d8cb77ccf6a00fbbd4c755c3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:56:36 +0100 Subject: [PATCH 214/221] nightly: Online5277 is the third trusted reviewer, not levzzz5154 Ludovic asked for his top three contributors by merged pull requests: kacpherek, rdbtCVS and Online5277. Co-Authored-By: Claude Opus 5.5 --- .github/nightly-reviewers.txt | 2 +- docs/release-flow.md | 2 +- tests/test_nightly_set.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/nightly-reviewers.txt b/.github/nightly-reviewers.txt index 5b737439c..a2f9606aa 100644 --- a/.github/nightly-reviewers.txt +++ b/.github/nightly-reviewers.txt @@ -4,4 +4,4 @@ # A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work). kacpherek # added by Ludovic, 2026-10-27 rdbtCVS # added by Ludovic, 2026-10-27 -levzzz5154 # added by Ludovic, 2026-10-27 +Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests) diff --git a/docs/release-flow.md b/docs/release-flow.md index 1089b9444..5377b27bc 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -423,7 +423,7 @@ before the gate. ### Trusted reviewers pick the pull requests The Nightly is where contributors test pull requests before the gate. The trusted reviewers listed in -`.github/nightly-reviewers.txt` (kacpherek, rdbtCVS and levzzz5154 since 2026-10-27) and Ludovic pick them with a +`.github/nightly-reviewers.txt` (kacpherek, rdbtCVS and Online5277 since 2026-10-27) and Ludovic pick them with a comment on any issue or pull request (`.github/workflows/nightly-command.yml`, `tools/ci/nightly_set.py`): ```text diff --git a/tests/test_nightly_set.py b/tests/test_nightly_set.py index a235a29c1..4ba8d43d3 100644 --- a/tests/test_nightly_set.py +++ b/tests/test_nightly_set.py @@ -73,7 +73,7 @@ class AllowTests(unittest.TestCase): def test_the_repos_list_names_the_three_reviewers(self): reviewers = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text()) - self.assertEqual(reviewers.logins, {"kacpherek", "rdbtcvs", "levzzz5154"}) + self.assertEqual(reviewers.logins, {"kacpherek", "rdbtcvs", "online5277"}) self.assertFalse(reviewers.paused) class RefusalTests(unittest.TestCase): From ce64c617e98bb8ceeab670f00b5ba29fbe0638ab Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:16:55 +0100 Subject: [PATCH 215/221] launcher: Play needs a Microsoft account that owns Minecraft: Java Edition Like other launchers, the launcher now starts the game only while an account in it owns Java Edition (Ludovic's decision, 2026-10-27). - account::launch is the owner gate: it asks the Minecraft services again (entitlements and profile, after the token renewal), the selected account first, until one owns the game. Each answer is kept in the keychain item beside the tokens. No answer (no network) keeps the last one; "doesn't own" blocks at once. - Every Play goes through it: the window (Home, instances, packs), `horizon-launcher play` and `modpack play`, the MCP's play. - Offline names are added and played only beside an owner; signing the last owner out keeps them, unplayable. - Home shows "Sign in with a Microsoft account that owns Minecraft: Java Edition to play" with Sign in; the "coming soon" sign-in strings are gone. - The game binary, harnesses, CI and the servers are unchanged. Co-Authored-By: Claude Opus 5.5 --- README.md | 6 +- docs/launcher-commands.md | 6 +- docs/microsoft-account.md | 40 ++++- launcher/README.md | 17 +- launcher/lang/fr.json | 10 +- launcher/lang/ru.json | 10 +- launcher/src/account.rs | 306 +++++++++++++++++++++++++--------- launcher/src/account/tests.rs | 219 ++++++++++++++++++++---- launcher/src/backend.rs | 65 +++++--- launcher/src/cli.rs | 23 ++- launcher/src/main.rs | 99 +++++++---- launcher/src/mcp.rs | 2 + launcher/src/switch_page.rs | 4 +- launcher/tests/owner_gate.rs | 89 ++++++++++ 14 files changed, 685 insertions(+), 211 deletions(-) create mode 100644 launcher/tests/owner_gate.rs diff --git a/README.md b/README.md index 65078464e..ae85f7dbd 100644 --- a/README.md +++ b/README.md @@ -31,7 +31,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that re Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself. -**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install). +**You need** a Microsoft account that owns Minecraft: Java Edition (the launcher signs in with it, as other launchers do; see [Microsoft account](docs/microsoft-account.md)); Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install). @@ -47,7 +47,7 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these. - **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status). - **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings). - **Resource packs and data packs:** resource packs work, and data packs load functions, predicates and item modifiers. -- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). +- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining servers, online-mode ones with the Microsoft account the launcher signs in with. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). - **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods). Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders: @@ -158,7 +158,7 @@ them too (Rust uses Java's own float maths on each platform). ### Known issues -Horizon can't sign in to a Microsoft account yet, so it can't join online-mode servers (it joins offline-mode ones); skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; the creative hotbar keys (C/X) aren't wired to the hotbar loader; item tooltips lack attribute lines. +Skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; the creative hotbar keys (C/X) aren't wired to the hotbar loader; item tooltips lack attribute lines. ## Licence diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 900a10283..df098faa6 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -46,7 +46,7 @@ MCP: `prepare`. ## `horizon-launcher play` -Start the client. +Start the client (needs a signed-in Microsoft account that owns Minecraft: Java Edition). horizon-launcher play @@ -98,7 +98,7 @@ MCP: `account_list`. ## `horizon-launcher account sign-in` -Sign in with a Microsoft account in your browser (device code). +Sign in with a Microsoft account in your browser (device code). Play needs one that owns Minecraft: Java Edition. horizon-launcher account sign-in @@ -126,7 +126,7 @@ MCP: `account_select`. ## `horizon-launcher account offline` -Play offline, without an account: as NAME (kept to switch back to; 3 to 16 letters, digits or _), or as the name the game made up. +Play offline (LAN, offline-mode servers) beside a signed-in account that owns the game: as NAME (kept to switch back to; 3 to 16 letters, digits or _), or as the name the game made up. horizon-launcher account offline [NAME] diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 380aa0785..314115fb3 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -1,14 +1,16 @@ # Microsoft account sign-in and online-mode play Horizon signs players in with their Microsoft account in the launcher and joins online-mode -(authenticated) servers like vanilla 26.3 does. Offline profiles and offline/LAN play stay exactly as -they are. This note is the design, the status of each part and what Ludovic has to register. +(authenticated) servers like vanilla 26.3 does. The launcher plays only with an account that owns +Minecraft: Java Edition ([the owner gate](#the-owner-gate)); offline names, LAN and offline-mode +servers play behind it. This note is the design, the status of each part and what Ludovic has to +register. ## What Ludovic registers (needs his accounts) -Nothing below can be done by an agent: the app registrations belong to Ludovic. Until the client ID -is set, the launcher's sign-in shows "Coming soon" ("Microsoft sign-in is coming soon") and everything else -works as before. +Nothing below can be done by an agent: the app registrations belong to Ludovic. A build without +the client ID can't sign in, so its launcher can't start the game ("This build of the launcher has +no Microsoft sign-in"); release builds have it. 1. **Azure app registration** (https://portal.azure.com → Microsoft Entra ID → App registrations → New registration): @@ -64,14 +66,38 @@ All requests use HTTPS and JSON except the two OAuth calls (form-encoded): 7. **Profile**: `GET https://api.minecraftservices.com/minecraft/profile`: UUID, name, skins, capes. 404 = owns the game but has no profile yet ("Create your Minecraft profile on minecraft.net first"). +## The owner gate + +Decided 2026-10-27 (Ludovic, after a modder's suggestion): like other launchers, Horizon's +launcher starts the game only while an account in it owns Java Edition. Offline play stays +possible; the launcher just doesn't offer it on its own. + +- **Play needs an owner.** Every Play (Home, instances and packs, `horizon-launcher play`, + `modpack play`, the MCP's `play`) asks `account::launch` first. It asks the Minecraft services + again for each account, the selected one first, until one owns the game: the token renewal + (below) if due, then entitlements and profile. Without an owner the game doesn't start and Play + says "Sign in with a Microsoft account that owns Minecraft: Java Edition to play", with Sign in. +- **The answer lives with the tokens.** Each account's keychain item keeps the last answer + (`owns`), so no plain file can say yes. With no network (or a sign-in that can't be renewed) the + last answer stands: being offline never blocks a player who passed before, and the game starts + without a session, offline. An answer of "doesn't own" (or no profile) blocks at once. +- **Offline names play behind an owner.** They can be added and played only while an owning + account is signed in. Signing the last one out keeps them, and they play again once one is back. +- **Who isn't affected:** the game binary itself (`horizon-client`, `horizon-ctl launch`, the + harnesses, CI), the dedicated server and `horizon-server`, the website. There is no bypass flag: + the launcher's tests use accounts in a memory store (`MemoryStore`, and `HORIZON_NO_KEYCHAIN` + for the CLI and MCP tests, which then have no owner). + Refresh: the Minecraft token is renewed from the Microsoft refresh token (steps 2-5 with -`grant_type=refresh_token`) when it has less than an hour left, before every launch. A refused +`grant_type=refresh_token`) when it has less than an hour left, before every launch; steps 6-7 run +at every launch (the owner gate). A refused refresh token (`invalid_grant`) asks the player to sign in again. Several accounts can be signed in; one is selected. "Sign out" deletes the account's secrets from the keychain. ## Token storage -- Secrets (the Microsoft refresh token, the Minecraft access token and its expiry) go to the OS +- Secrets (the Microsoft refresh token, the Minecraft access token and its expiry, the last + ownership answer) go to the OS keychain, one item per account: Keychain on macOS, Credential Manager on Windows, the Secret Service (GNOME Keyring, KWallet) on Linux. Service name `dev.playhorizon.launcher`, account = the Minecraft UUID. diff --git a/launcher/README.md b/launcher/README.md index 6aec8b633..b2b497753 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -124,7 +124,9 @@ The opening, then Play ([clip](docs/opening.webm)): [instance] [--remove]`; `HORIZON_LAUNCHER_DESKTOP` points it at another folder. - **Accounts and quick switch**: the top bar's account chip opens a menu of everyone who can play: each signed-in Microsoft account, the offline names the player keeps, and the name the game - made up (`horizon-player.txt`). Picking one plays as it from the next Play. Settings > Account + made up (`horizon-player.txt`). Picking one plays as it from the next Play. Offline names play + only while an account that owns the game is signed in ([Microsoft accounts](#microsoft-accounts)); + signing the last one out keeps them, unplayable until one is back. Settings > Account adds offline names (3 to 16 letters, digits or `_`; the game gets `--name`) and forgets them; the Console's Share log takes them out of the log too. `horizon-launcher account offline [NAME]`, `account select ` (an account or an offline name), `account forget-offline @@ -364,10 +366,15 @@ The window, the command line and the MCP server all call the same core, `src/bac ## Microsoft accounts -Settings → Accounts signs in a Microsoft account to play on online-mode servers under your own -name and skin: the launcher shows a code, you enter it at microsoft.com/link, and the launcher -checks that the account owns Minecraft: Java Edition. The Play page says who plays ("Playing as"); -without an account the game plays offline, as before. Tokens live in the system keychain (Keychain, +The launcher starts the game only while a Microsoft account that owns Minecraft: Java Edition is +signed in, as other launchers do: without one, Play (Home, instances, `horizon-launcher play`, the +MCP's `play`) says "Sign in with a Microsoft account that owns Minecraft: Java Edition to play" +and starts nothing. Settings → Accounts signs in: the launcher shows a code, you enter it at +microsoft.com/link, and the launcher checks that the account owns the game. It asks again at every +Play, with the token renewal; with no network the last answer stands, and a "doesn't own" blocks +at once. The account also plays online-mode servers under your own name and skin; offline names +play LAN and offline-mode servers beside it. The game binary started directly (`horizon-client`, +`horizon-ctl launch`), the harnesses and the servers don't go through this check. Tokens live in the system keychain (Keychain, Credential Manager, or the Secret Service on Linux), never in a file, a log or the command line; `accounts.json` in the data folder keeps only names and UUIDs. Without a keychain you stay signed in until the launcher closes. When the game starts, it gets the session in a private file it diff --git a/launcher/lang/fr.json b/launcher/lang/fr.json index b92252a92..f15700ad3 100644 --- a/launcher/lang/fr.json +++ b/launcher/lang/fr.json @@ -48,11 +48,8 @@ "Applications menu": "Menu des applications", "Horizon and its icon are in your desktop's menu.": "Horizon et son icône sont dans le menu de votre bureau.", "Not in your desktop's menu.": "Pas dans le menu de votre bureau.", - "Microsoft account (coming soon)": "Compte Microsoft (bientôt)", "Microsoft account": "Compte Microsoft", "Another account": "Un autre compte", - "Microsoft sign-in is coming soon. Until then the game plays offline: single player, LAN and servers in offline mode work.": "La connexion Microsoft arrive bientôt. D'ici là, le jeu se joue hors ligne : solo, LAN et serveurs en mode hors ligne fonctionnent.", - "Coming soon": "Bientôt", "Microsoft account · plays": "Compte Microsoft · joue", "Microsoft account · signed in": "Compte Microsoft · connecté", "Asking Microsoft…": "Demande à Microsoft…", @@ -165,5 +162,10 @@ "Installing the nightly, {percent}%": "Installation de la Nightly, {percent} %", "The nightly could not be installed: {error}": "La Nightly n'a pas pu être installée : {error}", "{version} in the Nightly instance. Choose Horizon in the sidebar to play the release.": "{version} dans l'instance Nightly. Choisissez Horizon dans la barre latérale pour jouer la version publiée.", - "No nightly build yet.": "Pas encore de version Nightly." + "No nightly build yet.": "Pas encore de version Nightly.", + "This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game.": "Cette version du launcher n'a pas de connexion Microsoft (HORIZON_MSA_CLIENT_ID) : elle ne peut pas lancer le jeu.", + "Sign in with a Microsoft account that owns Minecraft: Java Edition to play": "Connectez-vous avec un compte Microsoft qui possède Minecraft: Java Edition pour jouer", + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers. It also plays online servers with your name and skin.": "Horizon a besoin d'un compte Microsoft qui possède Minecraft: Java Edition, comme les autres launchers. Il permet aussi de jouer sur les serveurs en ligne avec votre nom et votre skin.", + "Sign in": "Se connecter", + "Sign in with Microsoft": "Se connecter avec Microsoft" } diff --git a/launcher/lang/ru.json b/launcher/lang/ru.json index 753132e4b..ca14e22d7 100644 --- a/launcher/lang/ru.json +++ b/launcher/lang/ru.json @@ -48,11 +48,8 @@ "Applications menu": "Меню приложений", "Horizon and its icon are in your desktop's menu.": "Horizon и его значок есть в меню рабочего стола.", "Not in your desktop's menu.": "Нет в меню рабочего стола.", - "Microsoft account (coming soon)": "Аккаунт Microsoft (скоро)", "Microsoft account": "Аккаунт Microsoft", "Another account": "Другой аккаунт", - "Microsoft sign-in is coming soon. Until then the game plays offline: single player, LAN and servers in offline mode work.": "Вход через Microsoft скоро появится. А пока игра работает офлайн: одиночная игра, LAN и серверы в офлайн-режиме.", - "Coming soon": "Скоро", "Microsoft account · plays": "Аккаунт Microsoft · играет", "Microsoft account · signed in": "Аккаунт Microsoft · вход выполнен", "Asking Microsoft…": "Запрос к Microsoft…", @@ -165,5 +162,10 @@ "Installing the nightly, {percent}%": "Установка ночной сборки, {percent}%", "The nightly could not be installed: {error}": "Не удалось установить ночную сборку: {error}", "{version} in the Nightly instance. Choose Horizon in the sidebar to play the release.": "{version} в сборке Nightly. Выберите Horizon на боковой панели, чтобы играть в релиз.", - "No nightly build yet.": "Ночных сборок пока нет." + "No nightly build yet.": "Ночных сборок пока нет.", + "This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game.": "В этой сборке лаунчера нет входа через Microsoft (HORIZON_MSA_CLIENT_ID), поэтому она не может запустить игру.", + "Sign in with a Microsoft account that owns Minecraft: Java Edition to play": "Чтобы играть, войдите в аккаунт Microsoft, у которого есть Minecraft: Java Edition", + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers. It also plays online servers with your name and skin.": "Как и другим лаунчерам, Horizon нужен аккаунт Microsoft, у которого есть Minecraft: Java Edition. С ним вы также играете на онлайн-серверах под своим именем и со своим скином.", + "Sign in": "Войти", + "Sign in with Microsoft": "Войти через Microsoft" } diff --git a/launcher/src/account.rs b/launcher/src/account.rs index 257055911..751e58232 100644 --- a/launcher/src/account.rs +++ b/launcher/src/account.rs @@ -1,8 +1,13 @@ //! Microsoft account sign-in (docs/microsoft-account.md): the OAuth device-code flow, then Xbox //! Live, XSTS and the Minecraft services, the game ownership check and the profile. Secrets (the -//! Microsoft refresh token, the Minecraft access token) live in the OS keychain; accounts.json -//! keeps only names and UUIDs. The game gets the session in a file it reads once -//! (`--session-file`), never on its command line. Tokens never reach logs, errors or output. +//! Microsoft refresh token, the Minecraft access token, the last ownership answer) live in the OS +//! keychain; accounts.json keeps only names and UUIDs. The game gets the session in a file it +//! reads once (`--session-file`), never on its command line. Tokens never reach logs, errors or +//! output. +//! +//! The owner gate ([`launch`]): the launcher starts the game only while an account in it owns +//! Minecraft: Java Edition, as other launchers do. Offline names play behind such an account. +//! The game binary itself, its harnesses and the servers don't go through the launcher's gate. //! //! The Azure app (client ID) is Horizon's own and is configuration: `HORIZON_MSA_CLIENT_ID` at //! build time, or at run time to override it. Without one, sign-in says it is not configured. @@ -16,8 +21,15 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; pub const SERVICE: &str = "dev.playhorizon.launcher"; const SCOPE: &str = "XboxLive.signin offline_access"; pub const NOT_CONFIGURED: &str = - "Microsoft sign-in is coming soon. Until then the game plays offline: single player, \ - LAN and servers in offline mode work."; + "This build of the launcher has no Microsoft sign-in (HORIZON_MSA_CLIENT_ID), so it can't start the game."; +/// What every Play says while no account in the launcher owns the game. +pub const NEEDS_OWNER: &str = + "Sign in with a Microsoft account that owns Minecraft: Java Edition to play"; +const DOES_NOT_OWN: &str = "This account doesn't own Minecraft: Java Edition."; +const NO_PROFILE: &str = + "This account has no Minecraft profile yet. Create one at minecraft.net, then sign in again."; +const OTHER_PROFILE: &str = + "The Microsoft account now has another Minecraft profile. Sign in again."; const SIGN_IN_AGAIN: &str = "Your Microsoft sign-in expired. Sign in again."; /// The Minecraft token is renewed when it has less than this left. const RENEW_BEFORE: u64 = 3600; @@ -393,7 +405,8 @@ pub struct Account { pub cape: Option, } -fn profile(ep: &Endpoints, token: &str) -> Result { +/// The profile; none when the account has none (it doesn't own the game, or never made one). +fn profile(ep: &Endpoints, token: &str) -> Result, String> { let (status, v) = send( bearer( request_to("GET", &format!("{}/minecraft/profile", ep.minecraft)), @@ -403,7 +416,7 @@ fn profile(ep: &Endpoints, token: &str) -> Result { "the Minecraft services", )?; if status == 404 { - return Err("This account has no Minecraft profile yet. Create one at minecraft.net, then sign in again.".into()); + return Ok(None); } let (Some(uuid), Some(name)) = (str_field(&v, "id"), str_field(&v, "name")) else { return Err("Could not read the Minecraft profile.".into()); @@ -417,7 +430,7 @@ fn profile(ep: &Endpoints, token: &str) -> Result { }) .cloned() }; - Ok(Account { + Ok(Some(Account { uuid: uuid.replace('-', "").to_lowercase(), name, skin: active("skins").and_then(|s| { @@ -429,13 +442,7 @@ fn profile(ep: &Endpoints, token: &str) -> Result { )) }), cape: active("capes").and_then(|c| str_field(&c, "url")), - }) -} - -/// Whether the signed-in account still owns Minecraft: Java Edition, asked again now: the -/// launcher downloads the game's files only for an owner (sources.rs). -pub fn owns_minecraft(ep: &Endpoints, secrets: &Secrets) -> Result { - owns_game(ep, &secrets.minecraft_token) + })) } /// What the keychain keeps for one account. @@ -446,6 +453,14 @@ pub struct Secrets { minecraft_expires_at: u64, #[serde(default)] xuid: Option, + /// The last answer the Minecraft services gave: whether the account owns the game. It is + /// kept here, beside the tokens, so that no plain file can say yes. Accounts saved before it + /// existed passed the same check at sign-in, which refuses everyone else. + #[serde(default = "owned_at_sign_in")] + owns: bool, +} +fn owned_at_sign_in() -> bool { + true } impl std::fmt::Debug for Secrets { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -457,39 +472,69 @@ impl std::fmt::Debug for Secrets { pub fn finish_sign_in(ep: &Endpoints, ms: MsTokens) -> Result<(Account, Secrets), String> { let mc = minecraft_login(ep, &ms.access)?; if !owns_game(ep, &mc.token)? { - return Err("This account doesn't own Minecraft: Java Edition.".into()); + return Err(DOES_NOT_OWN.into()); } - let account = profile(ep, &mc.token)?; - Ok(( - account, - Secrets { - refresh_token: ms.refresh, + let account = profile(ep, &mc.token)?.ok_or(NO_PROFILE)?; + Ok((account, Secrets::new(ms.refresh, mc))) +} + +impl Secrets { + fn new(refresh_token: String, mc: Minecraft) -> Self { + Self { + refresh_token, minecraft_token: mc.token, minecraft_expires_at: mc.expires_at, xuid: mc.xuid, - }, - )) + owns: true, + } + } } -/// A Minecraft token with at least an hour left, renewed through the refresh token if needed. -/// The profile is read again on renewal (the name may have changed). -pub fn fresh( - ep: &Endpoints, - client_id: &str, - account: &Account, - secrets: Secrets, -) -> Result<(Account, Secrets), String> { - if secrets.minecraft_expires_at > now() + RENEW_BEFORE { - return Ok((account.clone(), secrets)); +/// What asking the Minecraft services again found for one account. +enum Check { + /// It owns the game: its profile as it is now (the name may have changed) and its tokens. + Owns(Account, Secrets), + /// The services said it doesn't own the game (or has no profile any more). + DoesNot(Secrets), + /// No answer (no network, a sign-in that can't be renewed): the last answer stands. + NoAnswer(String, Secrets), +} + +/// Asks whether `account` owns the game, with a Minecraft token renewed through the refresh token +/// first when it has less than an hour left. The secrets come back renewed whatever the answer. +fn check(ep: &Endpoints, client_id: Option<&str>, account: &Account, secrets: Secrets) -> Check { + let mut secrets = secrets; + if secrets.minecraft_expires_at <= now() + RENEW_BEFORE { + let renewed = client_id + .ok_or_else(|| NOT_CONFIGURED.to_string()) + .and_then(|id| refresh_ms(ep, id, &secrets.refresh_token)) + .and_then(|ms| Ok((minecraft_login(ep, &ms.access)?, ms.refresh))); + match renewed { + Ok((mc, refresh)) => { + secrets = Secrets { + owns: secrets.owns, + ..Secrets::new(refresh, mc) + } + } + Err(e) => return Check::NoAnswer(e, secrets), + } } - let ms = refresh_ms(ep, client_id, &secrets.refresh_token)?; - let (renewed, secrets) = finish_sign_in(ep, ms)?; - if renewed.uuid != account.uuid { - return Err( - "The Microsoft account now has another Minecraft profile. Sign in again.".into(), - ); + let token = &secrets.minecraft_token; + match owns_game(ep, token).and_then(|owns| Ok(if owns { profile(ep, token)? } else { None })) { + Err(e) => Check::NoAnswer(e, secrets), + Ok(None) => Check::DoesNot(Secrets { + owns: false, + ..secrets + }), + Ok(Some(p)) if p.uuid != account.uuid => Check::NoAnswer(OTHER_PROFILE.into(), secrets), + Ok(Some(p)) => Check::Owns( + p, + Secrets { + owns: true, + ..secrets + }, + ), } - Ok((renewed, secrets)) } // ----- The keychain -------------------------------------------------------------------------------- @@ -615,11 +660,15 @@ pub fn store() -> &'static dyn SecretStore { static STORE: OnceLock> = OnceLock::new(); STORE .get_or_init(|| { - #[cfg(any( - target_os = "linux", - target_os = "freebsd", - target_os = "macos", - target_os = "windows" + // Unit tests never reach the player's keychain. + #[cfg(all( + not(test), + any( + target_os = "linux", + target_os = "freebsd", + target_os = "macos", + target_os = "windows" + ) ))] if std::env::var_os("HORIZON_NO_KEYCHAIN").is_none() && SystemStore.get("probe").is_ok() { @@ -661,6 +710,18 @@ pub enum Player { GameName, } +const OFFLINE_NEEDS_OWNER: &str = + "Offline names need a Microsoft account that owns Minecraft: Java Edition in the launcher."; + +/// The secrets an account keeps in `store`, if it still has them there. +fn secrets_in(store: &dyn SecretStore, uuid: &str) -> Option { + store + .get(uuid) + .ok() + .flatten() + .and_then(|s| serde_json::from_str(&s).ok()) +} + /// Whether `name` can be an offline name: 3 to 16 letters, digits or `_`, as account names are. pub fn valid_offline_name(name: &str) -> bool { (3..=16).contains(&name.chars().count()) @@ -714,6 +775,14 @@ impl Accounts { } Ok(()) } + /// Whether an account here owned the game at its last check (the keychain's answer, no + /// request): what Play and offline names need. + pub fn has_owner(&self, store: &dyn SecretStore) -> bool { + self.accounts + .iter() + .any(|a| secrets_in(store, &a.uuid).is_some_and(|s| s.owns)) + } + /// Who plays now. pub fn player(&self) -> Player { match (self.selected(), &self.offline_selected) { @@ -723,8 +792,9 @@ impl Accounts { } } - /// Plays as `who`: an account, an offline name (kept), or the game's own name. - pub fn play_as(&mut self, who: Player) -> Result<(), String> { + /// Plays as `who`: an account, an offline name (kept, only beside an account that owns the + /// game), or the game's own name. + pub fn play_as(&mut self, store: &dyn SecretStore, who: Player) -> Result<(), String> { match who { Player::Microsoft(uuid) => { if !self.accounts.iter().any(|a| a.uuid == uuid) { @@ -733,6 +803,9 @@ impl Accounts { self.selected = Some(uuid); } Player::Offline(name) => { + if !self.has_owner(store) { + return Err(OFFLINE_NEEDS_OWNER.into()); + } let name = self.add_offline(&name)?; self.selected = None; self.offline_selected = Some(name); @@ -746,7 +819,7 @@ impl Accounts { } /// Keeps an offline name (once, in any case); returns it as kept. - pub fn add_offline(&mut self, name: &str) -> Result { + fn add_offline(&mut self, name: &str) -> Result { let name = name.trim(); if !valid_offline_name(name) { return Err(format!( @@ -802,7 +875,15 @@ impl Accounts { } } - /// Sign out: the secrets leave the keychain, the account the list. + /// A renewed profile (its name or skin changed) in place of the old one; who plays stays. + fn update(&mut self, account: Account) { + if let Some(a) = self.accounts.iter_mut().find(|a| a.uuid == account.uuid) { + *a = account; + } + } + + /// Sign out: the secrets leave the keychain, the account the list. Offline names stay, but + /// play only once an account that owns the game is back. pub fn remove(&mut self, store: &dyn SecretStore, uuid: &str) -> Result<(), String> { store.delete(uuid)?; self.accounts.retain(|a| a.uuid != uuid); @@ -813,32 +894,88 @@ impl Accounts { } } -/// The selected account with a token good for this game, renewed and saved if needed. -pub fn session_for_launch( +/// No account in the launcher owns Minecraft: Java Edition: the game must not start. +#[derive(Debug, PartialEq)] +pub struct NoOwner; +impl std::fmt::Display for NoOwner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{NEEDS_OWNER}.") + } +} + +/// The owner gate's pass for one launch. +#[derive(Debug, Default)] +pub struct Launch { + /// The selected account and its renewed session; none when an offline name plays, or when + /// its sign-in couldn't be renewed now (`offline` says why). + pub session: Option<(Account, Secrets)>, + /// Why the selected account plays without its session this time. + pub offline: Option, + /// An account the services said owns the game just now, the selected one first: who the + /// launcher may download the game for. + pub owner: Option<(Account, Secrets)>, +} + +/// The owner gate: the game starts only while an account in the launcher owns Minecraft: Java +/// Edition. The accounts are asked again, the selected one first, until one owns it; each keeps +/// the answer in the keychain. An account that gets no answer (no network) keeps its last one, so +/// being offline never blocks a player who passed before, while "doesn't own" blocks at once. +/// The caller saves `accounts` (renewed names and skins). +pub fn launch( ep: &Endpoints, + client_id: Option<&str>, store: &dyn SecretStore, accounts: &mut Accounts, -) -> Result, String> { - let Some(account) = accounts.selected().cloned() else { - return Ok(None); - }; - let secrets: Secrets = store - .get(&account.uuid)? - .and_then(|s| serde_json::from_str(&s).ok()) - .ok_or_else(|| { - format!( - "{} is no longer signed in on this computer. Sign in again.", - account.name - ) - })?; - let client_id = client_id().ok_or(NOT_CONFIGURED)?; - let before = secrets.minecraft_token.clone(); - let (renewed, secrets) = fresh(ep, &client_id, &account, secrets)?; - if renewed != account || secrets.minecraft_token != before { - accounts.add(store, renewed.clone(), &secrets)?; - accounts.save()?; +) -> Result { + let selected = accounts.selected.clone(); + let mut order = accounts.accounts.clone(); + order.sort_by_key(|a| Some(&a.uuid) != selected.as_ref()); + let mut pass = Launch::default(); + let mut owned = false; + for account in order { + if owned { + break; + } + let plays = Some(&account.uuid) == selected.as_ref(); + let Some(secrets) = secrets_in(store, &account.uuid) else { + if plays { + pass.offline = Some(format!( + "{} is no longer signed in on this computer. Sign in again.", + account.name + )); + } + continue; + }; + let before = serde_json::to_string(&secrets).ok(); + let (said, secrets) = match check(ep, client_id, &account, secrets) { + Check::Owns(renewed, secrets) => { + accounts.update(renewed.clone()); + if plays { + pass.session = Some((renewed.clone(), secrets.clone())); + } + pass.owner = Some((renewed, secrets.clone())); + (None, secrets) + } + Check::DoesNot(secrets) => (Some(DOES_NOT_OWN.to_string()), secrets), + Check::NoAnswer(e, secrets) => (Some(e), secrets), + }; + owned = secrets.owns; + if plays { + pass.offline = said; + } + let after = serde_json::to_string(&secrets).ok(); + if after != before { + if let Some(text) = after { + // A store that refuses costs only this answer: the next launch asks again. + let _ = store.set(&account.uuid, &text); + } + } + } + if owned { + Ok(pass) + } else { + Err(NoOwner) } - Ok(Some((renewed, secrets))) } /// Write the session for the game, readable by this user only, in a fresh file it deletes @@ -933,19 +1070,24 @@ impl SignIn { } } -/// Give the game the selected account's session, when there is one. -pub fn attach_session( - cmd: &mut std::process::Command, - game_home: &Path, -) -> Result, String> { +/// The owner gate for the game about to start, then the selected account's session in a file +/// for it: the file (none: offline) and why the account plays offline this time, if it does. +pub fn session_for_game(game_home: &Path) -> Result<(Option, Option), NoOwner> { let mut accounts = Accounts::load(); - let Some((account, secrets)) = session_for_launch(&Endpoints::live(), store(), &mut accounts)? - else { - return Ok(None); + let pass = launch( + &Endpoints::live(), + client_id().as_deref(), + store(), + &mut accounts, + )?; + let _ = accounts.save(); + let Some((account, secrets)) = pass.session else { + return Ok((None, pass.offline)); }; - let file = write_session_file(&game_home.join("sessions"), &account, &secrets)?; - cmd.arg("--session-file").arg(file); - Ok(Some(account)) + match write_session_file(&game_home.join("sessions"), &account, &secrets) { + Ok(file) => Ok((Some(file), None)), + Err(e) => Ok((None, Some(e))), + } } #[cfg(test)] diff --git a/launcher/src/account/tests.rs b/launcher/src/account/tests.rs index ec3766c7e..17c49ec8c 100644 --- a/launcher/src/account/tests.rs +++ b/launcher/src/account/tests.rs @@ -233,29 +233,58 @@ fn the_whole_chain() { assert!(!format!("{secrets:?}").contains("mc-token")); } -#[test] -fn refresh_only_when_the_token_runs_out() { - let (m, ep) = mock(|_| {}); - let account = Account { +fn notch() -> Account { + Account { uuid: UUID.into(), name: "Notch".into(), skin: None, cape: None, - }; - let good = Secrets { + } +} + +/// A signed-in account's secrets: a token good for two hours, and the last ownership answer. +fn secrets(token: &str, owns: bool) -> Secrets { + Secrets { refresh_token: "ms-refresh-1".into(), - minecraft_token: "old".into(), + minecraft_token: token.into(), minecraft_expires_at: now() + 7200, xuid: None, + owns, + } +} + +/// Nothing listens there: every request fails as with no network. +fn offline() -> Endpoints { + Endpoints { + microsoft: "http://127.0.0.1:9/ms".into(), + xbox_user: "http://127.0.0.1:9/xbl".into(), + xsts: "http://127.0.0.1:9/xsts".into(), + minecraft: "http://127.0.0.1:9/mc".into(), + } +} + +#[test] +fn refresh_only_when_the_token_runs_out() { + let (m, ep) = mock(|_| {}); + let Check::Owns(_, kept) = check( + &ep, + Some("test-client"), + ¬ch(), + secrets("mc-token", true), + ) else { + panic!("owns"); }; - let (_, kept) = fresh(&ep, "test-client", &account, good).unwrap(); - assert_eq!(kept.minecraft_token, "old"); - assert!(m.lock().unwrap().log.is_empty()); + assert_eq!(kept.refresh_token, "ms-refresh-1"); + // Entitlements and profile only: the token had two hours left. + assert_eq!(m.lock().unwrap().log.len(), 2); let stale = Secrets { minecraft_expires_at: now() + 60, ..kept.clone() }; - let (renewed_account, renewed) = fresh(&ep, "test-client", &account, stale).unwrap(); + let Check::Owns(renewed_account, renewed) = check(&ep, Some("test-client"), ¬ch(), stale) + else { + panic!("owns"); + }; assert_eq!( ( renewed.refresh_token.as_str(), @@ -269,25 +298,139 @@ fn refresh_only_when_the_token_runs_out() { minecraft_expires_at: 0, ..kept }; + assert!(matches!( + check(&ep, Some("test-client"), ¬ch(), revoked), + Check::NoAnswer(e, s) if e == SIGN_IN_AGAIN && s.owns + )); +} + +/// An accounts.json with Notch signed in and playing, his secrets in `store`. +fn signed_in(store: &MemoryStore, secrets: &Secrets) -> Accounts { + let mut accounts = Accounts::default(); + accounts.add(store, notch(), secrets).unwrap(); + accounts +} + +fn kept(store: &MemoryStore) -> Secrets { + secrets_in(store, UUID).unwrap() +} + +#[test] +fn an_owner_plays_with_a_session() { + let (_, ep) = mock(|_| {}); + let store = MemoryStore::default(); + let mut accounts = signed_in(&store, &secrets("mc-token", true)); + let pass = launch(&ep, Some("test-client"), &store, &mut accounts).unwrap(); + let (account, session) = pass.session.unwrap(); assert_eq!( - fresh(&ep, "test-client", &account, revoked).unwrap_err(), - SIGN_IN_AGAIN + (account.name.as_str(), session.minecraft_token.as_str()), + ("Notch", "mc-token") + ); + assert!(pass.owner.is_some() && pass.offline.is_none()); + // The profile as the services have it now (the skin is new). + assert!(accounts.selected().unwrap().skin.is_some()); +} + +#[test] +fn a_no_from_the_services_blocks_at_once() { + let (_, ep) = mock(|m| m.owns_game = false); + let store = MemoryStore::default(); + let mut accounts = signed_in(&store, &secrets("mc-token", true)); + assert!(accounts.has_owner(&store)); + assert_eq!( + launch(&ep, Some("test-client"), &store, &mut accounts).unwrap_err(), + NoOwner + ); + // The answer is kept beside the tokens: offline now, it still says no. + assert!(!kept(&store).owns && !accounts.has_owner(&store)); + assert_eq!( + launch(&offline(), Some("test-client"), &store, &mut accounts).unwrap_err(), + NoOwner + ); + assert_eq!( + NoOwner.to_string(), + "Sign in with a Microsoft account that owns Minecraft: Java Edition to play." ); } #[test] -fn ownership_is_asked_again_with_the_saved_token() { - let secrets = |token: &str| Secrets { - refresh_token: "ms-refresh-1".into(), - minecraft_token: token.into(), - minecraft_expires_at: now() + 7200, - xuid: None, +fn no_network_never_blocks_a_past_owner() { + let store = MemoryStore::default(); + let mut accounts = signed_in(&store, &secrets("mc-token", true)); + let pass = launch(&offline(), Some("test-client"), &store, &mut accounts).unwrap(); + // Plays, offline, and says why. + assert!(pass.session.is_none() && pass.owner.is_none()); + assert!(pass.offline.unwrap().contains("Could not reach")); + // A token to renew with no network, or a build without sign-in: the same. + let stale = Secrets { + minecraft_expires_at: 0, + ..secrets("mc-token", true) }; + let mut accounts = signed_in(&store, &stale); + assert!(launch(&offline(), Some("test-client"), &store, &mut accounts).is_ok()); + assert!(launch(&offline(), None, &store, &mut accounts).is_ok()); + // An account that never passed doesn't pass offline. + let mut accounts = signed_in(&store, &secrets("mc-token", false)); + assert!(launch(&offline(), Some("test-client"), &store, &mut accounts).is_err()); +} + +#[test] +fn accounts_from_before_the_gate_owned_the_game_at_sign_in() { + let old = r#"{"refresh_token":"r","minecraft_token":"t","minecraft_expires_at":1,"xuid":null}"#; + assert!(serde_json::from_str::(old).unwrap().owns); +} + +#[test] +fn any_owner_opens_the_gate_and_the_one_who_plays_brings_the_session() { let (m, ep) = mock(|_| {}); - assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(true)); - assert_eq!(m.lock().unwrap().log.len(), 1); - let (_, ep) = mock(|m| m.owns_game = false); - assert_eq!(owns_minecraft(&ep, &secrets("mc-token")), Ok(false)); + let store = MemoryStore::default(); + let mut accounts = signed_in(&store, &secrets("mc-token", true)); + // A second account, no longer in the keychain, plays. + accounts.accounts.push(Account { + uuid: "other".into(), + name: "Alex".into(), + skin: None, + cape: None, + }); + accounts.selected = Some("other".into()); + let pass = launch(&ep, Some("test-client"), &store, &mut accounts).unwrap(); + assert!(pass.session.is_none()); + assert!(pass + .offline + .unwrap() + .starts_with("Alex is no longer signed in")); + assert_eq!(pass.owner.unwrap().0.name, "Notch"); + // An offline name plays: Notch is asked, and no session goes to the game. + accounts.selected = None; + m.lock().unwrap().log.clear(); + let pass = launch(&ep, Some("test-client"), &store, &mut accounts).unwrap(); + assert!(pass.session.is_none() && pass.offline.is_none()); + assert_eq!(m.lock().unwrap().log.len(), 2); + // No account at all. + assert!(launch(&ep, Some("test-client"), &store, &mut Accounts::default()).is_err()); +} + +#[test] +fn offline_names_play_only_beside_an_owner() { + let store = MemoryStore::default(); + let mut accounts = Accounts::default(); + let refused = accounts.play_as(&store, Player::Offline("Builder_1".into())); + assert_eq!(refused.unwrap_err(), OFFLINE_NEEDS_OWNER); + assert!(accounts.offline.is_empty()); + let mut accounts = signed_in(&store, &secrets("mc-token", true)); + accounts + .play_as(&store, Player::Offline("Builder_1".into())) + .unwrap(); + // Signing the last owner out keeps the name, which no longer plays. + accounts.remove(&store, UUID).unwrap(); + assert_eq!(accounts.offline, ["Builder_1"]); + assert_eq!(accounts.player(), Player::Offline("Builder_1".into())); + assert!(!accounts.has_owner(&store)); + let (_, ep) = mock(|_| {}); + assert!(launch(&ep, Some("test-client"), &store, &mut accounts).is_err()); + assert!(accounts + .play_as(&store, Player::Offline("Builder_2".into())) + .is_err()); } #[test] @@ -305,10 +448,7 @@ fn refusals_have_messages() { .unwrap_err() .contains("child account")); let (_, ep) = mock(|m| m.owns_game = false); - assert_eq!( - finish_sign_in(&ep, tokens()).unwrap_err(), - "This account doesn't own Minecraft: Java Edition." - ); + assert_eq!(finish_sign_in(&ep, tokens()).unwrap_err(), DOES_NOT_OWN); let (_, ep) = mock(|m| m.no_profile = true); assert!(finish_sign_in(&ep, tokens()) .unwrap_err() @@ -318,12 +458,8 @@ fn refusals_have_messages() { "Sign-in was declined in the browser." ); // Nothing listening: a message, not a URL. - let dead = Endpoints { - microsoft: "http://127.0.0.1:9/ms".into(), - ..Endpoints::live() - }; assert_eq!( - device_code(&dead, "x").unwrap_err(), + device_code(&offline(), "x").unwrap_err(), "Could not reach Microsoft. Check your internet connection." ); } @@ -353,6 +489,7 @@ fn accounts_keep_secrets_in_the_store_only() { minecraft_token: "mc-secret".into(), minecraft_expires_at: 1, xuid: None, + owns: true, }; accounts.add(&store, account.clone(), &secrets).unwrap(); assert_eq!(accounts.selected(), Some(&account)); @@ -386,6 +523,7 @@ fn session_files_are_private_and_complete() { minecraft_token: "mc-token".into(), minecraft_expires_at: 1, xuid: Some("25".into()), + owns: true, }; let path = write_session_file(&dir, &account, &secrets).unwrap(); let v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); @@ -426,6 +564,10 @@ fn client_id_is_configuration() { #[test] fn offline_names_switch_with_accounts() { + let store = MemoryStore::default(); + store + .set("abc", &serde_json::to_string(&secrets("t", true)).unwrap()) + .unwrap(); let mut a = Accounts { accounts: vec![Account { uuid: "abc".into(), @@ -438,20 +580,23 @@ fn offline_names_switch_with_accounts() { }; assert_eq!(a.player(), Player::Microsoft("abc".into())); assert_eq!(a.name_arg(), None); - a.play_as(Player::Offline("Builder_1".into())).unwrap(); + a.play_as(&store, Player::Offline("Builder_1".into())) + .unwrap(); assert_eq!(a.player(), Player::Offline("Builder_1".into())); assert_eq!(a.name_arg(), Some("Builder_1")); // Kept once, as first written, whatever the case. - a.play_as(Player::Offline("builder_1".into())).unwrap(); + a.play_as(&store, Player::Offline("builder_1".into())) + .unwrap(); assert_eq!(a.offline, ["Builder_1"]); assert_eq!(a.name_arg(), Some("Builder_1")); assert!(a.add_offline("no spaces").is_err()); assert!(a.add_offline("ab").is_err()); assert!(a.add_offline("seventeen_letters").is_err()); - a.play_as(Player::Microsoft("abc".into())).unwrap(); + a.play_as(&store, Player::Microsoft("abc".into())).unwrap(); assert_eq!(a.name_arg(), None, "an account plays with its own name"); - assert!(a.play_as(Player::Microsoft("zzz".into())).is_err()); - a.play_as(Player::Offline("Builder_1".into())).unwrap(); + assert!(a.play_as(&store, Player::Microsoft("zzz".into())).is_err()); + a.play_as(&store, Player::Offline("Builder_1".into())) + .unwrap(); a.remove_offline("BUILDER_1").unwrap(); assert_eq!(a.player(), Player::GameName); assert!(a.remove_offline("Builder_1").is_err()); diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index d7a3992b2..2b97ecf6c 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1195,7 +1195,7 @@ fn preparer_binary(dir: &Path) -> Option { binary.is_file().then_some(binary) } -/// Downloads the pinned version from Mojang into `dir` when the signed-in account owns +/// Downloads the pinned version from Mojang into `dir` when an account in the launcher owns /// Minecraft (asked again now), else says what signing in would do, as the last line of the /// not-found error. fn download_for_owner( @@ -1205,17 +1205,20 @@ fn download_for_owner( log: &dyn Fn(String), ) -> Result<(), String> { let v = &pins.version; - let owner = (|| -> Result, String> { - let ep = account::Endpoints::live(); - let mut accounts = account::Accounts::load(); - let Some((a, secrets)) = account::session_for_launch(&ep, account::store(), &mut accounts)? - else { - return Ok(None); - }; - Ok(Some((a.name, account::owns_minecraft(&ep, &secrets)?))) - })(); - match owner { - Ok(Some((name, true))) => { + let mut accounts = account::Accounts::load(); + let pass = account::launch( + &account::Endpoints::live(), + account::client_id().as_deref(), + account::store(), + &mut accounts, + ); + let _ = accounts.save(); + match pass { + Ok(account::Launch { + owner: Some((owner, _)), + .. + }) => { + let name = owner.name; log(format!( "{name} owns Minecraft: downloading {v} from Mojang" )); @@ -1228,18 +1231,20 @@ fn download_for_owner( format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}") }) } - Ok(Some((name, false))) => Err(format!( - "\n • {name}, the signed-in account, doesn't own Minecraft: Java Edition, so Horizon \ - can't download it." + // An owner by its last answer, who can't be asked now. + Ok(pass) => Err(format!( + "\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \ + checked: {}", + pass.offline.unwrap_or_default() )), - Ok(None) => Err(format!( + Err(_) if !accounts.accounts.is_empty() => Err( + "\n • No signed-in account owns Minecraft: Java Edition, so Horizon can't download it." + .into(), + ), + Err(_) => Err(format!( "\n • Or sign in with the Microsoft account that owns Minecraft: Horizon then \ downloads {v} from Mojang itself." )), - Err(e) => Err(format!( - "\n • Downloading {v} from Mojang needs your Microsoft account, which could not be \ - checked: {e}" - )), } } @@ -1886,14 +1891,20 @@ pub fn need_prepared(tag: &str) -> Result<(), String> { } } -/// The client's command, once its resources are prepared. +/// The client's command, once the owner gate lets it start and its resources are prepared. Past +/// the gate, a sign-in that can't be renewed (no network, expired) still lets the game start, +/// offline. pub fn client(tag: &str) -> Result { + let (session, offline) = account::session_for_game(&game_home()) + .map_err(|refused| format!("{refused} Sign in with `horizon-launcher account sign-in`."))?; need_prepared(tag)?; complete_assets(tag); crate::browser::horizon::before_play(&game_home()); let mut cmd = client_command(tag); - // A sign-in that can't be renewed (no network, expired) still lets the game start, offline. - if let Err(e) = crate::account::attach_session(&mut cmd, &game_home()) { + if let Some(file) = session { + cmd.arg("--session-file").arg(file); + } + if let Some(e) = offline { eprintln!("Playing offline: {e}"); } append_game_args(&mut cmd); @@ -2441,9 +2452,11 @@ pub enum Msg { Reused(Vec<(String, String)>), /// Whether secrets are kept in the OS keychain (else only until the launcher closes). Keychain(bool), - /// The selected account's session file for the game about to start (none = offline), or - /// why it could not be renewed. - Session(Result, String>), + /// Whether an account in the launcher owned the game at its last check (the owner gate). + Owner(bool), + /// The owner gate's answer for the game about to start: the selected account's session + /// file (none = offline) and why it plays offline, if it does. + Session(Result<(Option, Option), crate::account::NoOwner>), /// A modpack step's line (`modpacks`). PackLine(String), /// A modpack step ended: the pack as it now is. diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index cf7770c65..6fb73af5d 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -79,7 +79,8 @@ enum ServersCmd { enum AccountCmd { /// The signed-in accounts and which one plays List, - /// Sign in with a Microsoft account in your browser (device code) + /// Sign in with a Microsoft account in your browser (device code). Play needs one that owns + /// Minecraft: Java Edition SignIn, /// Sign out: the account's tokens leave the keychain SignOut { @@ -88,8 +89,9 @@ enum AccountCmd { }, /// Play as this account, or as one of your offline names Select { who: String }, - /// Play offline, without an account: as NAME (kept to switch back to; 3 to 16 letters, - /// digits or _), or as the name the game made up + /// Play offline (LAN, offline-mode servers) beside a signed-in account that owns the game: + /// as NAME (kept to switch back to; 3 to 16 letters, digits or _), or as the name the game + /// made up Offline { name: Option }, /// Forget one of your offline names ForgetOffline { name: String }, @@ -556,7 +558,7 @@ enum Cmd { #[arg(long)] version: Option, }, - /// Start the client + /// Start the client (needs a signed-in Microsoft account that owns Minecraft: Java Edition) Play { #[arg(long)] version: Option, @@ -1312,9 +1314,13 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { "selected": accounts.player() == account::Player::Offline(n.clone()), })).collect::>(), "sign_in_configured": account::client_id().is_some(), + "owner": accounts.has_owner(account::store()), })); } else if accounts.accounts.is_empty() && accounts.offline.is_empty() { - println!("No Microsoft account signed in: the game plays offline."); + println!( + "No Microsoft account signed in. Play needs one that owns Minecraft: Java \ + Edition: horizon-launcher account sign-in" + ); } else { for a in &accounts.accounts { let mark = if accounts.selected.as_ref() == Some(&a.uuid) { @@ -1333,6 +1339,9 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { "Playing offline as the game's own name (`account select NAME` to switch)." ); } + if !accounts.has_owner(account::store()) { + println!("{}.", account::NEEDS_OWNER); + } } } AccountCmd::SignIn => { @@ -1372,7 +1381,7 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { ), (None, None) => return Err(find(&accounts, &who).unwrap_err()), }; - accounts.play_as(player)?; + accounts.play_as(account::store(), player)?; accounts.save()?; println!("The game plays as {name}."); } @@ -1381,7 +1390,7 @@ fn account_command(action: AccountCmd, as_json: bool) -> Result<(), String> { Some(n) => account::Player::Offline(n), None => account::Player::GameName, }; - accounts.play_as(player)?; + accounts.play_as(account::store(), player)?; accounts.save()?; match accounts.name_arg() { Some(n) => println!("The game plays offline as {n}."), diff --git a/launcher/src/main.rs b/launcher/src/main.rs index eefc653ac..fd3726da6 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -207,6 +207,9 @@ struct Launcher { sign_in: Option, sign_in_state: Option, keychain: bool, + /// Whether an account here owns the game, by the keychain's last answers (the owner gate); + /// none until the keychain has been read. + owner: Option, /// The game is waiting for its session (a token renewal) before it starts. starting_client: Option, /// Join a friend: the code typed on the Play page, and the one the game @@ -411,6 +414,7 @@ impl Launcher { sign_in: None, sign_in_state: None, keychain: true, + owner: None, starting_client: None, friend_code: String::new(), friend_focused: false, @@ -463,8 +467,11 @@ impl Launcher { let tx = this.tx.clone(); let keychain_tx = this.tx.clone(); // Asking the keychain can block (D-Bus), so not on this thread. + let accounts = this.accounts.clone(); std::thread::spawn(move || { - let _ = keychain_tx.send(Msg::Keychain(account::store().persistent())); + let store = account::store(); + let _ = keychain_tx.send(Msg::Keychain(store.persistent())); + let _ = keychain_tx.send(Msg::Owner(accounts.has_owner(store))); }); std::thread::spawn(move || { let reused = backend::reuse_prepared_everywhere(); @@ -632,17 +639,29 @@ impl Launcher { // The page reads is_prepared when drawn; `changed` redraws it. Msg::Reused(_) => self.installed = backend::installed(), Msg::Keychain(persistent) => self.keychain = persistent, + Msg::Owner(owns) => self.owner = Some(owns), Msg::Playing(playing) => self.playing = playing, Msg::Session(session) => { if let Some(tag) = self.starting_client.take() { let mut cmd = backend::client_command(&tag); - match session { - Ok(Some(file)) => { - cmd.arg("--session-file").arg(file); + let (file, offline) = match session { + Ok(pass) => pass, + Err(account::NoOwner) => { + self.owner = Some(false); + self.client_error = Some(format!("{}.", tr(account::NEEDS_OWNER))); + self.starting_pack = None; + self.joining = None; + self.quick_play = None; + continue; } - Ok(None) => {} - // Still play, offline, and say why. - Err(e) => self.client_error = Some(format!("Playing offline: {e}")), + }; + self.owner = Some(true); + if let Some(file) = file { + cmd.arg("--session-file").arg(file); + } + // Still play, offline, and say why. + if let Some(e) = offline { + self.client_error = Some(format!("Playing offline: {e}")); } self.accounts = Accounts::load(); // An offline name the player picked (the quick switch). @@ -896,6 +915,9 @@ impl Launcher { if changed_state { if let SignInState::Done(Ok(_)) = state { self.accounts = Accounts::load(); + // Sign-in refuses accounts that don't own the game. + self.owner = Some(true); + self.client_error = None; } self.sign_in_state = Some(state); changed = true; @@ -1061,23 +1083,19 @@ impl Launcher { let tx = self.tx.clone(); std::thread::spawn(move || { backend::complete_assets(&tag); - let session = (|| { - let mut accounts = Accounts::load(); - let Some((a, secrets)) = account::session_for_launch( - &account::Endpoints::live(), - account::store(), - &mut accounts, - )? - else { - return Ok(None); - }; - account::write_session_file(&backend::game_home().join("sessions"), &a, &secrets) - .map(Some) - })(); + let session = account::session_for_game(&backend::game_home()); let _ = tx.send(Msg::Session(session)); }); } + /// Starts the Microsoft sign-in; Settings shows its code. + fn start_sign_in(&mut self) { + if let Some(old) = self.sign_in.replace(SignIn::start()) { + old.cancel(); + } + self.sign_in_state = Some(SignInState::Starting); + } + fn choose_folder(&mut self, cx: &mut Context) { let paths = cx.prompt_for_paths(PathPromptOptions { files: false, @@ -2270,8 +2288,28 @@ impl Launcher { { rows = rows.child(self.join_friend_row(prepared && !running, cx)); // The top bar shows who plays; a row only when there is something to do about it: - // offline, in a build that can sign in. - if self.accounts.selected().is_none() && account::client_id().is_some() { + // no account that owns the game (Play needs one), or offline. + if self.owner == Some(false) { + rows = rows.child(index_row( + 5, + tr("Microsoft account"), + Some( + div() + .child(format!("{}.", tr(account::NEEDS_OWNER))) + .into_any_element(), + ), + Some( + button("gate-sign-in", "Sign in", Kind::Primary, &t) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.start_sign_in(); + this.go(Page::Settings); + cx.notify(); + })) + .into_any_element(), + ), + &t, + )); + } else if self.accounts.selected().is_none() && account::client_id().is_some() { rows = rows.child(index_row( 5, tr("Playing offline"), @@ -3129,6 +3167,7 @@ impl Launcher { this.sign_in_state = Some(SignInState::Done(Err(e))); } let _ = this.accounts.save(); + this.owner = Some(this.accounts.has_owner(store)); cx.notify(); }, )), @@ -3174,9 +3213,9 @@ impl Launcher { ), Some(SignInState::Done(Ok(a))) => div().child(format!("Signed in as {}.", a.name)), Some(SignInState::Done(Err(e))) => div().text_color(t.danger).child(e.clone()), - None if self.accounts.accounts.is_empty() => div().child( - "Sign in to play on online servers with your name and skin. Without an account the game plays offline.", - ), + None if self.accounts.accounts.is_empty() => div().child(tr( + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers. It also plays online servers with your name and skin.", + )), None => div().child(tr("Add another account.")), }; let detail = if self.keychain || self.accounts.accounts.is_empty() { @@ -3190,8 +3229,7 @@ impl Launcher { .child(div().child(account::NO_KEYCHAIN)) }; let action = if !configured { - // No client ID in this build: the button says what's coming and does nothing. - Some(button("sign-in", "Coming soon", Kind::Ghost, &t).into_any_element()) + None } else if let Some(SignInState::Code(code)) = &self.sign_in_state { let (uri, user_code) = (code.verification_uri.clone(), code.user_code.clone()); Some( @@ -3231,17 +3269,14 @@ impl Launcher { Some( button("sign-in", "Sign in with Microsoft", Kind::Secondary, &t) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.sign_in = Some(SignIn::start()); - this.sign_in_state = Some(SignInState::Starting); + this.start_sign_in(); cx.notify(); })) .into_any_element(), ) }; n += 1; - let title = if !configured { - "Microsoft account (coming soon)" - } else if self.accounts.accounts.is_empty() { + let title = if self.accounts.accounts.is_empty() { "Microsoft account" } else { "Another account" diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 962cd2925..e9a665f93 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -200,6 +200,8 @@ impl Session { "plays_as": accounts.selected().map(|a| a.name.clone()), "sign_in_configured": account::client_id().is_some(), "keychain": account::store().persistent(), + // Play needs an account that owns the game (the owner gate). + "owner": accounts.has_owner(account::store()), "sign_in": sign_in, })) .unwrap()) diff --git a/launcher/src/switch_page.rs b/launcher/src/switch_page.rs index eb1e0bbfc..deb3baed6 100644 --- a/launcher/src/switch_page.rs +++ b/launcher/src/switch_page.rs @@ -24,7 +24,9 @@ impl Launcher { pub(super) fn play_as(&mut self, who: Player) { let mut accounts = Accounts::load(); - let done = accounts.play_as(who).and_then(|()| accounts.save()); + let done = accounts + .play_as(account::store(), who) + .and_then(|()| accounts.save()); match done { Ok(()) => self.accounts = accounts, Err(e) => self.sign_in_state = Some(SignInState::Done(Err(e))), diff --git a/launcher/tests/owner_gate.rs b/launcher/tests/owner_gate.rs new file mode 100644 index 000000000..3a7869272 --- /dev/null +++ b/launcher/tests/owner_gate.rs @@ -0,0 +1,89 @@ +//! The owner gate from the outside: with no account that owns Minecraft: Java Edition in the +//! launcher, neither `horizon-launcher play` nor the MCP server's play starts the game. +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +const REFUSED: &str = "Sign in with a Microsoft account that owns Minecraft: Java Edition to play."; + +/// Fresh homes with one installed (not prepared) version and an offline name, as a player who +/// played offline before the gate has. +fn home(name: &str) -> PathBuf { + let root = + std::env::temp_dir().join(format!("horizon-owner-gate-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let version = root.join("launcher/versions/v2026.10.27.01"); + std::fs::create_dir_all(&version).unwrap(); + std::fs::write(version.join(".installed"), "").unwrap(); + std::fs::write( + root.join("launcher/accounts.json"), + r#"{"accounts":[],"selected":null,"offline":["Builder_1"],"offline_selected":"Builder_1"}"#, + ) + .unwrap(); + root +} + +fn launcher(root: &Path, args: &[&str]) -> Command { + let mut cmd = Command::new(env!("CARGO_BIN_EXE_horizon-launcher")); + cmd.args(args) + .env("HORIZON_HOME", root.join("game")) + .env("HORIZON_LAUNCHER_HOME", root.join("launcher")) + .env("XDG_DATA_HOME", root.join("data")) + .env("XDG_CONFIG_HOME", root.join("config")) + .env("HORIZON_LAUNCHER_NO_SELF_UPDATE", "1") + .env("HORIZON_NO_AUDIO", "1") + .env("HORIZON_TELEMETRY_URL", "off") + // Memory only: the test never reads the player's keychain. + .env("HORIZON_NO_KEYCHAIN", "1") + .env("HORIZON_MSA_CLIENT_ID", "test-client"); + cmd +} + +fn text(out: &Output) -> String { + String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr) +} + +#[test] +fn the_cli_refuses_to_play_without_an_owner() { + let root = home("cli"); + let out = launcher(&root, &["play"]).output().unwrap(); + let said = text(&out); + assert!(!out.status.success(), "{said}"); + assert!(said.contains(REFUSED), "{said}"); + assert!(said.contains("horizon-launcher account sign-in"), "{said}"); + // Nothing of the game ran, and the offline name is still there. + assert!(!root.join("game/sessions").exists()); + let accounts = std::fs::read_to_string(root.join("launcher/accounts.json")).unwrap(); + assert!(accounts.contains("Builder_1"), "{accounts}"); + let _ = std::fs::remove_dir_all(&root); +} + +#[test] +fn the_mcp_server_refuses_to_play_without_an_owner() { + let root = home("mcp"); + let mut child = launcher(&root, &["mcp"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let requests = [ + r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#, + r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"play","arguments":{}}}"#, + ]; + let mut stdin = child.stdin.take().unwrap(); + for r in requests { + writeln!(stdin, "{r}").unwrap(); + } + drop(stdin); + let out = child.wait_with_output().unwrap(); + let reply = String::from_utf8_lossy(&out.stdout) + .lines() + .map(|l| serde_json::from_str::(l).unwrap()) + .find(|v| v["id"] == 2) + .expect("a reply to play"); + assert_eq!(reply["result"]["isError"], true, "{reply}"); + let said = reply["result"]["content"][0]["text"].as_str().unwrap(); + assert!(said.contains(REFUSED), "{said}"); + let _ = std::fs::remove_dir_all(&root); +} From f6e96e484c5ba974b4d87e200c8be609e9d0a935 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:23:53 +0100 Subject: [PATCH 216/221] Nightly: the scheduled run deletes nightly/build-* branches older than 7 days Ludovic's decision (2026-10-27). `nightly.py prune-builds` runs in the scheduled `pick` only, with main's code, and lists each deletion in the run summary. It deletes only branches named nightly/build-- older than 7 days, never the newest build, and never one a published `nightly` or nightly- release points to. nightly-state and every other branch are left alone. tests/test_nightly.py pins it. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/nightly-build.yml | 8 +++++ docs/release-flow.md | 3 ++ tests/test_nightly.py | 36 ++++++++++++++++++++++ tools/ci/nightly.py | 48 +++++++++++++++++++++++++++++ 4 files changed, 95 insertions(+) diff --git a/.github/workflows/nightly-build.yml b/.github/workflows/nightly-build.yml index 24b6974a5..3fa440bd1 100644 --- a/.github/workflows/nightly-build.yml +++ b/.github/workflows/nightly-build.yml @@ -95,6 +95,14 @@ jobs: run: | python3 tools/ci/nightly.py pick ${FORCE:+--force} | tee -a "$GITHUB_STEP_SUMMARY" { echo; cat nightly-notes.md; } >> "$GITHUB_STEP_SUMMARY" + - name: Old nightly/build-* branches deleted (scheduled runs only) + # Ludovic, 2026-10-27: older than 7 days, but never the newest build or one a published nightly points to; + # nothing but nightly/build-* (nightly.py stale_builds, tests/test_nightly.py). + if: github.event_name == 'schedule' + env: + GH_TOKEN: ${{ github.token }} + run: | + { echo "### nightly/build-* branches"; python3 tools/ci/nightly.py prune-builds --days 7; } | tee -a "$GITHUB_STEP_SUMMARY" - uses: actions/upload-artifact@v4 with: name: nightly-notes diff --git a/docs/release-flow.md b/docs/release-flow.md index 5377b27bc..09565bd2e 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -447,6 +447,9 @@ comment on any issue or pull request (`.github/workflows/nightly-command.yml`, ` Equal inputs give the same commit, so an unchanged set and main publish nothing new. On a conflict the build stops and answers which two pull requests conflict and where; a reviewer can then open an integration pull request from their fork that combines them, and pick that one instead. +- **Old builds.** The scheduled run deletes the `nightly/build-*` branches older than 7 days (Ludovic, + 2026-10-27), and lists each in its summary. It never deletes the newest build, a build a published `nightly` or + `nightly-` release points to, or any other branch (`nightly.py prune-builds`). - **Refused.** A pull request that changes a path CODEOWNERS gives to Ludovic (`.github/`, `tools/ci/`, the signing and update code, `launcher/src/backend.rs`, `launcher/links.json`…), more than 30 in a set, and more than 6 builds a day (the scheduled one always runs). diff --git a/tests/test_nightly.py b/tests/test_nightly.py index c44416044..567b3d86e 100644 --- a/tests/test_nightly.py +++ b/tests/test_nightly.py @@ -120,3 +120,39 @@ class UntrustedBuildTests(unittest.TestCase): self.assertEqual(self.game.count("HORIZON_NO_SCCACHE: ${{ inputs.trusted && '1' || '' }}"), calls) env = (Path(__file__).resolve().parents[1] / "tools/ci/runner-env.sh").read_text() self.assertEqual(env.count('-z "${HORIZON_NO_SCCACHE:-}"'), 2) + + +class PruneBuildsTests(unittest.TestCase): + TODAY = dt.date(2026, 11, 10) + + def test_only_old_unpublished_builds_go(self): + branches = { + "nightly/build-2026-10-27-1": "a", # old: goes + "nightly/build-2026-10-27-2": "pub", # old, but a published nightly- points to it: stays + "nightly/build-2026-11-02-1": "c", # old enough by one day: goes + "nightly/build-2026-11-03-1": "d", # exactly 7 days: stays + "nightly/build-2026-11-09-3": "e", # recent: stays + } + self.assertEqual(nightly.stale_builds(branches, {"pub"}, self.TODAY, 7), + ["nightly/build-2026-10-27-1", "nightly/build-2026-11-02-1"]) + + def test_the_newest_build_always_stays(self): + branches = {"nightly/build-2026-10-01-1": "a", "nightly/build-2026-10-01-2": "b"} + self.assertEqual(nightly.stale_builds(branches, set(), self.TODAY, 7), ["nightly/build-2026-10-01-1"]) + self.assertEqual(nightly.stale_builds({"nightly/build-2026-10-01-1": "a"}, set(), self.TODAY, 7), []) + # the newest by number, not by text: -10 is newer than -9 + branches = {"nightly/build-2026-10-01-9": "a", "nightly/build-2026-10-01-10": "b"} + self.assertEqual(nightly.stale_builds(branches, set(), self.TODAY, 7), ["nightly/build-2026-10-01-9"]) + + def test_nothing_else_is_touched(self): + branches = {"nightly-state": "s", "nightly/build-x": "x", "main": "m", "nightly/build-2026-10-01-1-fix": "f", + "feature/nightly/build-2026-10-01-1": "g", "nightly/build-2026-10-02-1": "n"} + self.assertEqual(nightly.stale_builds(branches, set(), self.TODAY, 7), []) + + def test_the_workflow_prunes_on_schedule_only(self): + build = (WORKFLOWS / "nightly-build.yml").read_text() + step = build.split("Old nightly/build-* branches deleted", 1)[1].split("- uses:", 1)[0] + self.assertIn("if: github.event_name == 'schedule'", step) + self.assertIn("prune-builds --days 7", step) + self.assertIn("GITHUB_STEP_SUMMARY", step) + diff --git a/tools/ci/nightly.py b/tools/ci/nightly.py index 9a6dd8a3b..e04b99ddd 100644 --- a/tools/ci/nightly.py +++ b/tools/ci/nightly.py @@ -4,6 +4,8 @@ nightly.py pick [--force] which commit tonight's nightly builds: GitHub outputs and nightly-notes.md nightly.py rotate renames the current `nightly` pre-release to nightly-, frees the tag nightly.py prune [--days 7] deletes the nightly- pre-releases and tags older than that, nothing else + nightly.py prune-builds [--days 7] deletes the nightly/build-- branches older than that, but the + newest and any a published nightly points to (Ludovic, 2026-10-27) A nightly builds main plus the pull requests the trusted reviewers picked (the set: tools/ci/nightly_set.py), merged in their order and pushed as nightly/build--. With no set it builds the newest union branch on origin @@ -264,17 +266,63 @@ def prune(days: int) -> None: print(f"deleted {tag}") +BUILD = re.compile(r"^nightly/build-(\d{4}-\d{2}-\d{2})-(\d+)$") + + +def stale_builds(branches: dict[str, str], published: set[str], today: dt.date, days: int) -> list[str]: + """The nightly/build-- branches (name -> commit) to delete: older than `days`, never the newest build, + never one whose commit a published nightly release points to, never a branch not named like a build.""" + builds = {name: sha for name, sha in branches.items() if BUILD.match(name)} + if not builds: + return [] + order = lambda name: (BUILD.match(name).group(1), int(BUILD.match(name).group(2))) # noqa: E731 + newest = max(builds, key=order) + cutoff = today - dt.timedelta(days=days) + return sorted(name for name, sha in builds.items() if name != newest and sha not in published + and dt.date.fromisoformat(BUILD.match(name).group(1)) < cutoff) + + +def remote_refs(pattern: str) -> dict[str, str]: + """origin's refs matching `pattern`: short name -> commit (annotated tags peeled).""" + refs: dict[str, str] = {} + for line in git("ls-remote", "origin", pattern).splitlines(): + sha, ref = line.split("\t", 1) + name = ref.removeprefix("refs/heads/").removeprefix("refs/tags/") + if name.endswith("^{}"): + refs[name[:-3]] = sha # the peeled commit wins over the tag object + else: + refs.setdefault(name, sha) + return refs + + +def prune_builds(days: int) -> None: + """Deletes old nightly/build-* branches on origin through the API, one line per deletion (the run summary).""" + branches = remote_refs("refs/heads/nightly/build-*") + tags = {name: sha for name, sha in remote_refs("refs/tags/nightly*").items() + if name == "nightly" or DATED.match(name)} + today = dt.datetime.now(dt.timezone.utc).date() + doomed = stale_builds(branches, set(tags.values()), today, days) + for name in doomed: + gh("api", "-X", "DELETE", f"repos/{os.environ['GITHUB_REPOSITORY']}/git/refs/heads/{name}") + print(f"- deleted `{name}` ({branches[name][:7]})") + print(f"{len(doomed)} of {len(branches)} nightly/build-* branches deleted (kept: the newest, the published " + f"nightlies' and the last {days} days')") + + def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) sub = ap.add_subparsers(dest="cmd", required=True) sub.add_parser("pick").add_argument("--force", action="store_true") sub.add_parser("rotate") sub.add_parser("prune").add_argument("--days", type=int, default=7) + sub.add_parser("prune-builds").add_argument("--days", type=int, default=7) args = ap.parse_args() if args.cmd == "pick": pick(args.force) elif args.cmd == "rotate": rotate() + elif args.cmd == "prune-builds": + prune_builds(args.days) else: prune(args.days) From 7afb41a1285e418a3e3440374f6e0f99796b9713 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:25:30 +0100 Subject: [PATCH 217/221] launcher: the owner gate's screen, once for offline players and on a refused Play A player without an account that owns Minecraft: Java Edition sees one screen when the launcher opens (once) and whenever Play is refused: why Horizon needs the account, like other launchers, that worlds, offline names and settings stay where they are, and Sign in, which runs the device-code sign-in on the same screen. Not now closes it; Home keeps its Sign in row, which now opens this screen. Co-Authored-By: Claude Opus 5.5 --- docs/microsoft-account.md | 5 ++ launcher/lang/fr.json | 6 +- launcher/lang/ru.json | 6 +- launcher/src/backend.rs | 4 + launcher/src/main.rs | 24 ++++-- launcher/src/owner_page.rs | 157 +++++++++++++++++++++++++++++++++++++ 6 files changed, 194 insertions(+), 8 deletions(-) create mode 100644 launcher/src/owner_page.rs diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 314115fb3..9c457f8a0 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -77,6 +77,11 @@ possible; the launcher just doesn't offer it on its own. again for each account, the selected one first, until one owns the game: the token renewal (below) if due, then entitlements and profile. Without an owner the game doesn't start and Play says "Sign in with a Microsoft account that owns Minecraft: Java Edition to play", with Sign in. +- **The window says it once.** A player without an owner (one who played offline until now) sees + the gate's screen once when the launcher opens: why Horizon needs the account ("like other + launchers"), that worlds, offline names and settings stay where they are, and Sign in, which shows + the device code on the same screen. It comes back whenever Play is refused; Not now closes it, + and Home keeps a Sign in row (`launcher/src/owner_page.rs`). - **The answer lives with the tokens.** Each account's keychain item keeps the last answer (`owns`), so no plain file can say yes. With no network (or a sign-in that can't be renewed) the last answer stands: being offline never blocks a player who passed before, and the game starts diff --git a/launcher/lang/fr.json b/launcher/lang/fr.json index f15700ad3..85c8238e8 100644 --- a/launcher/lang/fr.json +++ b/launcher/lang/fr.json @@ -167,5 +167,9 @@ "Sign in with a Microsoft account that owns Minecraft: Java Edition to play": "Connectez-vous avec un compte Microsoft qui possède Minecraft: Java Edition pour jouer", "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers. It also plays online servers with your name and skin.": "Horizon a besoin d'un compte Microsoft qui possède Minecraft: Java Edition, comme les autres launchers. Il permet aussi de jouer sur les serveurs en ligne avec votre nom et votre skin.", "Sign in": "Se connecter", - "Sign in with Microsoft": "Se connecter avec Microsoft" + "Sign in with Microsoft": "Se connecter avec Microsoft", + "Not now": "Pas maintenant", + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Horizon a besoin d'un compte Microsoft qui possède Minecraft: Java Edition, comme les autres launchers.", + "Your worlds, offline names and settings stay where they are.": "Vos mondes, vos noms hors ligne et vos réglages restent où ils sont.", + "Open {link} in your browser and enter this code:": "Ouvrez {link} dans votre navigateur et entrez ce code :" } diff --git a/launcher/lang/ru.json b/launcher/lang/ru.json index ca14e22d7..8c8458a55 100644 --- a/launcher/lang/ru.json +++ b/launcher/lang/ru.json @@ -167,5 +167,9 @@ "Sign in with a Microsoft account that owns Minecraft: Java Edition to play": "Чтобы играть, войдите в аккаунт Microsoft, у которого есть Minecraft: Java Edition", "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers. It also plays online servers with your name and skin.": "Как и другим лаунчерам, Horizon нужен аккаунт Microsoft, у которого есть Minecraft: Java Edition. С ним вы также играете на онлайн-серверах под своим именем и со своим скином.", "Sign in": "Войти", - "Sign in with Microsoft": "Войти через Microsoft" + "Sign in with Microsoft": "Войти через Microsoft", + "Not now": "Не сейчас", + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Как и другим лаунчерам, Horizon нужен аккаунт Microsoft, у которого есть Minecraft: Java Edition.", + "Your worlds, offline names and settings stay where they are.": "Ваши миры, офлайн-имена и настройки остаются на месте.", + "Open {link} in your browser and enter this code:": "Откройте {link} в браузере и введите этот код:" } diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 2b97ecf6c..aacdf81ec 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -2625,6 +2625,10 @@ pub struct Settings { /// first-run question, or on the Play page once if they answered that before it existed. #[serde(default)] pub ping_notice_seen: bool, + /// The player without an account that owns the game has read, once, why the launcher needs + /// one now (the owner gate's screen). + #[serde(default)] + pub owner_notice_seen: bool, /// Seconds the sidebar's partner banner has been on screen, over every start, up to /// `partner::SEEN_BEFORE_HIDE`: only then can the player hide it. #[serde(default)] diff --git a/launcher/src/main.rs b/launcher/src/main.rs index fd3726da6..15ec943f2 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -27,6 +27,7 @@ mod modpacks_page; mod mods_page; mod mods_project; mod multiplayer_page; +mod owner_page; mod packs_page; mod partner; mod perf; @@ -210,6 +211,8 @@ struct Launcher { /// Whether an account here owns the game, by the keychain's last answers (the owner gate); /// none until the keychain has been read. owner: Option, + /// Play was refused (or Home's Sign in pressed): the owner gate's screen is open. + owner_screen_open: bool, /// The game is waiting for its session (a token renewal) before it starts. starting_client: Option, /// Join a friend: the code typed on the Play page, and the one the game @@ -415,6 +418,7 @@ impl Launcher { sign_in_state: None, keychain: true, owner: None, + owner_screen_open: false, starting_client: None, friend_code: String::new(), friend_focused: false, @@ -648,6 +652,7 @@ impl Launcher { Ok(pass) => pass, Err(account::NoOwner) => { self.owner = Some(false); + self.owner_screen_open = true; self.client_error = Some(format!("{}.", tr(account::NEEDS_OWNER))); self.starting_pack = None; self.joining = None; @@ -917,7 +922,12 @@ impl Launcher { self.accounts = Accounts::load(); // Sign-in refuses accounts that don't own the game. self.owner = Some(true); + self.owner_screen_open = false; self.client_error = None; + if !self.settings.owner_notice_seen { + self.settings.owner_notice_seen = true; + self.settings.save(); + } } self.sign_in_state = Some(state); changed = true; @@ -1088,7 +1098,7 @@ impl Launcher { }); } - /// Starts the Microsoft sign-in; Settings shows its code. + /// Starts the Microsoft sign-in; Settings and the owner gate's screen show its code. fn start_sign_in(&mut self) { if let Some(old) = self.sign_in.replace(SignIn::start()) { old.cancel(); @@ -2301,8 +2311,7 @@ impl Launcher { Some( button("gate-sign-in", "Sign in", Kind::Primary, &t) .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.start_sign_in(); - this.go(Page::Settings); + this.sign_in_to_play(); cx.notify(); })) .into_any_element(), @@ -3201,9 +3210,9 @@ impl Launcher { .flex() .flex_col() .gap(px(6.)) - .child(format!( - "Open {} in your browser and enter this code:", - code.verification_uri + .child(trf( + "Open {link} in your browser and enter this code:", + &[("link", &code.verification_uri)], )) .child( text(theme::HEADING) @@ -3907,6 +3916,9 @@ impl Render for Launcher { if self.asking_consent() { root = root.child(self.consent_screen(cx)); } + if self.asking_owner() { + root = root.child(self.owner_screen(cx)); + } if let Some(opening) = &self.opening { // The wordmark arrives letter by letter, then gives way to the launcher; a click or // a key skips ahead. diff --git a/launcher/src/owner_page.rs b/launcher/src/owner_page.rs new file mode 100644 index 000000000..5a27b064b --- /dev/null +++ b/launcher/src/owner_page.rs @@ -0,0 +1,157 @@ +//! The owner gate in the window (`horizon_launcher::account::launch`): the screen that asks for a +//! Microsoft account that owns Minecraft: Java Edition. It covers the launcher once for players +//! without one (those who played offline before the gate), and again whenever Play is refused. +//! The sign-in runs on it, code and all. +use super::*; + +impl Launcher { + /// Whether the screen covers the window: no owner, and either Play was refused or the player + /// hasn't read it yet. The data question comes first. + pub(crate) fn asking_owner(&self) -> bool { + self.owner == Some(false) + && (self.owner_screen_open || !self.settings.owner_notice_seen) + && !self.asking_consent() + && self.opening.is_none() + } + + /// Opens the screen and starts the sign-in on it. + pub(crate) fn sign_in_to_play(&mut self) { + self.owner_screen_open = true; + self.start_sign_in(); + } + + /// Closes it; it comes back with the next refused Play. + fn close_owner_screen(&mut self) { + if let Some(s) = self.sign_in.take() { + s.cancel(); + } + self.sign_in_state = None; + self.owner_screen_open = false; + if !self.settings.owner_notice_seen { + self.settings.owner_notice_seen = true; + self.settings.save(); + } + } + + pub(crate) fn owner_screen(&mut self, cx: &mut Context) -> Stateful
{ + let t = self.theme; + let configured = account::client_id().is_some(); + let mut body = div() + .flex() + .flex_col() + .gap(px(12.)) + .p(px(28.)) + .child(caps(tr("Microsoft account")).text_color(t.muted)) + .child( + text(theme::HEADING) + .text_color(t.ink) + .child(format!("{}.", tr(account::NEEDS_OWNER))), + ) + .child(text(theme::UI).text_color(t.muted).child(tr( + "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.", + ))) + .child(text(theme::UI).text_color(t.muted).child(tr( + "Your worlds, offline names and settings stay where they are.", + ))); + let status = match &self.sign_in_state { + _ if !configured => Some(div().child(tr(account::NOT_CONFIGURED))), + Some(SignInState::Starting) => Some(div().child(tr("Asking Microsoft…"))), + Some(SignInState::Code(code)) => Some( + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(trf( + "Open {link} in your browser and enter this code:", + &[("link", &code.verification_uri)], + )) + .child( + text(theme::HEADING) + .font_family(theme::MONO) + .text_color(t.ink) + .child(code.user_code.clone()), + ), + ), + Some(SignInState::Done(Err(e))) => Some(div().text_color(t.danger).child(e.clone())), + Some(SignInState::Done(Ok(_))) | None => None, + }; + body = body.children(status.map(|s| { + plate(&t) + .p(px(16.)) + .text_size(px(theme::UI.px)) + .text_color(t.ink_soft) + .child(s) + })); + let mut answers = div() + .flex() + .justify_end() + .gap(px(12.)) + .px(px(28.)) + .pb(px(28.)) + .child( + button("owner-later", "Not now", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.close_owner_screen(); + cx.notify(); + }, + )), + ); + answers = match &self.sign_in_state { + Some(SignInState::Code(code)) => { + let (uri, user_code) = (code.verification_uri.clone(), code.user_code.clone()); + answers + .child( + button("owner-copy", "Copy code", Kind::Secondary, &t).on_click( + move |_, _, cx| { + copy_to_clipboard( + cx, + gpui::ClipboardItem::new_string(user_code.clone()), + ) + }, + ), + ) + .child( + button("owner-open", "Open link", Kind::Primary, &t) + .on_click(move |_, _, cx| cx.open_url(&uri)), + ) + } + Some(SignInState::Starting) => answers, + _ if !configured => answers, + _ => answers.child( + button("owner-sign-in", "Sign in", Kind::Primary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.sign_in_to_play(); + cx.notify(); + }, + )), + ), + }; + let card = plate(&t) + .flex() + .flex_col() + // A set width: text measured at it wraps where it is drawn. + .w(px(560.)) + .max_w_full() + .bg(t.page) + .border_1() + .border_color(t.rule) + .child(body) + .child(answers); + div() + .id("owner-gate") + .absolute() + .top_0() + .left_0() + .size_full() + .flex() + .flex_col() + .items_center() + .justify_center() + .px(px(32.)) + .py(px(24.)) + .bg(t.page.opacity(0.92)) + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .occlude() + .child(card) + } +} From 610c2f3c10ff5cdda4408afd17463e8aaad85a1f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:33:53 +0100 Subject: [PATCH 218/221] launcher: Download and prepare, from Mojang, for an account that owns the game With the owner gate in place, a signed-in owner no longer needs another launcher first (brief mc-download-1, Ludovic 2026-10-27). - The Play page's Resources row offers an owner "Download and prepare" and "From my install"; without an owner it asks to sign in first. - `horizon-launcher prepare --download` does the same. - Every file from Mojang must have the size and sha1 Mojang lists. - The download shows its progress and has Cancel; files already whole are kept, so the next try goes on where it stopped. Co-Authored-By: Claude Opus 5.5 --- docs/launcher-commands.md | 3 +- docs/microsoft-account.md | 11 +++ launcher/README.md | 9 +++ launcher/lang/fr.json | 7 +- launcher/lang/ru.json | 7 +- launcher/src/backend.rs | 41 +++++++--- launcher/src/cli.rs | 21 ++++- launcher/src/main.rs | 86 ++++++++++++++++++-- launcher/src/mojang.rs | 85 ++++++++++++++++---- launcher/src/mojang_tests.rs | 148 ++++++++++++++++++++++++++++++++--- launcher/src/servers_page.rs | 2 +- 11 files changed, 367 insertions(+), 53 deletions(-) diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index df098faa6..d5ed3491a 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -36,11 +36,12 @@ MCP: `remove`, needs `confirm: true`. ## `horizon-launcher prepare` -Prepare a version's resources from your own Minecraft install. +Prepare a version's resources from your own Minecraft install, or from Mojang. horizon-launcher prepare - `--minecraft`: The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, ATLauncher or GDLauncher (default: the launcher's, then every launcher's default) +- `--download`: Download Minecraft from Mojang for the signed-in account that owns it, instead of using an install MCP: `prepare`. diff --git a/docs/microsoft-account.md b/docs/microsoft-account.md index 9c457f8a0..33207da33 100644 --- a/docs/microsoft-account.md +++ b/docs/microsoft-account.md @@ -93,6 +93,17 @@ possible; the launcher just doesn't offer it on its own. the launcher's tests use accounts in a memory store (`MemoryStore`, and `HORIZON_NO_KEYCHAIN` for the CLI and MCP tests, which then have no owner). +## Downloading the game for an owner + +Decided 2026-10-27. This is the only exception to "Horizon never downloads the game", and it +applies only on the player's machine, for an account the owner gate just asked about. The +launcher's "Download and prepare" (`horizon-launcher prepare --download`) fetches the pinned +version straight from Mojang (`launcher/src/mojang.rs`): the version file, the client jar, +libraries, the asset index and the assets, each checked against the size and sha1 Mojang lists. +They go to `minecraft/` in the launcher's data folder, and the preparation runs as usual. The +download can be cancelled and goes on where it stopped. CI, agents, harnesses and the repo never +download or keep Mojang's files. + Refresh: the Minecraft token is renewed from the Microsoft refresh token (steps 2-5 with `grant_type=refresh_token`) when it has less than an hour left, before every launch; steps 6-7 run at every launch (the owner gate). A refused diff --git a/launcher/README.md b/launcher/README.md index b2b497753..9ded5d621 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -24,6 +24,15 @@ The opening, then Play ([clip](docs/opening.webm)): preparation reuses checksum-verified game jars and libraries from the current or another installed Horizon version, so the original Minecraft install is only required when no valid imported copy exists. +- **Download and prepare**: for a signed-in account that owns the game (asked again first), + the launcher downloads the pinned version from Mojang itself (piston-meta, piston-data, + libraries.minecraft.net, resources.download.minecraft.net; never a mirror) into `minecraft/` + in its data folder, in the official launcher's layout: the version file, the client jar, this + system's libraries, the asset index and the assets. Every file must have the size and sha1 + Mojang lists. The Play page shows how far it is and has Cancel; files already whole are kept, + so the next try goes on from there. **From my install** prepares from the player's own launcher + instead, and an install that lacks the version falls back to the download. Without an owner, + the Play page asks to sign in first. `horizon-launcher prepare --download`. - **Mods**: search Modrinth (CurseForge support is coming soon) for resource packs and modpacks, each marked Works, Partly or Doesn't run in Horizon; Java mod jars are never offered. Install puts a pack and what it needs in diff --git a/launcher/lang/fr.json b/launcher/lang/fr.json index 85c8238e8..a8532491e 100644 --- a/launcher/lang/fr.json +++ b/launcher/lang/fr.json @@ -171,5 +171,10 @@ "Not now": "Pas maintenant", "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Horizon a besoin d'un compte Microsoft qui possède Minecraft: Java Edition, comme les autres launchers.", "Your worlds, offline names and settings stay where they are.": "Vos mondes, vos noms hors ligne et vos réglages restent où ils sont.", - "Open {link} in your browser and enter this code:": "Ouvrez {link} dans votre navigateur et entrez ce code :" + "Open {link} in your browser and enter this code:": "Ouvrez {link} dans votre navigateur et entrez ce code :", + "From my install": "Depuis mon installation", + "Download and prepare": "Télécharger et préparer", + "Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.": "Pas préparé. Horizon peut télécharger Minecraft {version} depuis Mojang pour votre compte, ou utiliser votre propre installation.", + "Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.": "Pas préparé. Connectez-vous d'abord avec le compte Microsoft qui possède Minecraft {version}.", + "Cancel": "Annuler" } diff --git a/launcher/lang/ru.json b/launcher/lang/ru.json index 8c8458a55..9fa58b990 100644 --- a/launcher/lang/ru.json +++ b/launcher/lang/ru.json @@ -171,5 +171,10 @@ "Not now": "Не сейчас", "Horizon needs a Microsoft account that owns Minecraft: Java Edition, like other launchers.": "Как и другим лаунчерам, Horizon нужен аккаунт Microsoft, у которого есть Minecraft: Java Edition.", "Your worlds, offline names and settings stay where they are.": "Ваши миры, офлайн-имена и настройки остаются на месте.", - "Open {link} in your browser and enter this code:": "Откройте {link} в браузере и введите этот код:" + "Open {link} in your browser and enter this code:": "Откройте {link} в браузере и введите этот код:", + "From my install": "Из моей установки", + "Download and prepare": "Скачать и подготовить", + "Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.": "Не подготовлено. Horizon может скачать Minecraft {version} у Mojang для вашего аккаунта или взять вашу установку.", + "Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.": "Не подготовлено. Сначала войдите в аккаунт Microsoft, у которого есть Minecraft {version}.", + "Cancel": "Отмена" } diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index aacdf81ec..cd72440a6 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -1227,7 +1227,7 @@ fn download_for_owner( sources::Os::MacOs => "osx", sources::Os::Windows => "windows", }; - mojang::download(pins, dir, os, 8, fetch, log).map_err(|e| { + mojang::download(pins, dir, os, 8, fetch, &mojang::CANCEL, log).map_err(|e| { format!("\n • Horizon tried to download {v} from Mojang for {name}, but: {e}") }) } @@ -1299,7 +1299,8 @@ fn java( Ok(body) }; let runtime = data_dir().join("minecraft").join("runtime"); - let home = mojang::java_runtime(&component, &runtime, 8, &fetch, log).map_err(|e| { + let home = mojang::java_runtime(&component, &runtime, 8, &fetch, &mojang::CANCEL, log) + .map_err(|e| { format!("{missing}\n • Horizon also tried to download Minecraft's own Java from Mojang, but: {e}") })?; find(major, &[home]).map(|jdk| jdk.home()) @@ -1351,6 +1352,16 @@ fn assets_folder( } } +/// Where the preparation takes Minecraft's files from. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MinecraftFrom { + /// The player's own install (any launcher's); Mojang only when none has the version and an + /// account that owns the game is signed in. + Install, + /// Mojang, for the signed-in account that owns the game ("Download and prepare"). + Mojang, +} + /// Checks what the preparation needs and picks how to run it. PLAY.txt describes the same /// steps: the player's own launcher install, the server jar from that version's own json, and /// Java (and Python, for versions before horizon-prepare). Also returns the Minecraft folder @@ -1359,6 +1370,7 @@ fn assets_folder( pub fn preparer( tag: &str, minecraft: &Path, + from: MinecraftFrom, log: &dyn Fn(String), ) -> Result<(Preparer, PathBuf), String> { let version = game_version(tag); @@ -1386,16 +1398,23 @@ pub fn preparer( Ok(body) }; let linked = data_dir().join("linked-minecraft"); - let resolved = sources::resolve(minecraft, &pins, &known, &linked, &fetch, log); - if reused { - assets_folder(resolved, &chosen, &version, log) + if from == MinecraftFrom::Mojang { + // Straight from Mojang (what is already there and whole is kept), for an owner only. + download_for_owner(&pins, &own, &fetch, log) + .map_err(|e| e.trim_start_matches("\n • ").to_string())?; + own } else { - match resolved? { - sources::Resolved::Folder(dir) => dir, - sources::Resolved::NotFound(checked) => { - let not_found = sources::not_found(&version, &checked, minecraft); - download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?; - own + let resolved = sources::resolve(minecraft, &pins, &known, &linked, &fetch, log); + if reused { + assets_folder(resolved, &chosen, &version, log) + } else { + match resolved? { + sources::Resolved::Folder(dir) => dir, + sources::Resolved::NotFound(checked) => { + let not_found = sources::not_found(&version, &checked, minecraft); + download_for_owner(&pins, &own, &fetch, log).map_err(|e| not_found + &e)?; + own + } } } } diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 6fb73af5d..7d71084f3 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -548,12 +548,16 @@ enum Cmd { Install { tag: String }, /// Remove an installed version Remove { tag: String }, - /// Prepare a version's resources from your own Minecraft install + /// Prepare a version's resources from your own Minecraft install, or from Mojang Prepare { /// The game folder of the official launcher, Prism Launcher, MultiMC, the Modrinth App, /// ATLauncher or GDLauncher (default: the launcher's, then every launcher's default) - #[arg(long)] + #[arg(long, conflicts_with = "download")] minecraft: Option, + /// Download Minecraft from Mojang for the signed-in account that owns it, instead of + /// using an install + #[arg(long)] + download: bool, /// The installed version (default: the selected one) #[arg(long)] version: Option, @@ -974,11 +978,20 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { backend::remove_version(&tag)?; println!("Removed {tag}."); } - Cmd::Prepare { minecraft, version } => { + Cmd::Prepare { + minecraft, + download, + version, + } => { let tag = backend::resolve_version(version.as_deref())?; let minecraft = backend::minecraft_dir(minecraft)?; + let from = if download { + backend::MinecraftFrom::Mojang + } else { + backend::MinecraftFrom::Install + }; let (preparer, minecraft) = - backend::preparer(&tag, &minecraft, &|line| eprintln!("{line}"))?; + backend::preparer(&tag, &minecraft, from, &|line| eprintln!("{line}"))?; backend::sounds(&tag, &minecraft, &|line| println!("{line}")); match preparer { backend::Preparer::Process(cmd) => attached(cmd)?, diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 15ec943f2..135769376 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -1021,10 +1021,13 @@ impl Launcher { }); } - fn prepare(&mut self) { + /// Prepares the selected version, its Minecraft files from the player's install or, for an + /// owner who asks, from Mojang. + fn prepare(&mut self, from: backend::MinecraftFrom) { let Some(tag) = self.selected().cloned() else { return; }; + horizon_launcher::mojang::CANCEL.store(false, Ordering::Relaxed); let minecraft = self .settings .minecraft_dir @@ -1040,7 +1043,7 @@ impl Launcher { let log = |line| { let _ = tx.send(Msg::Line(Job::Prepare, line)); }; - let result = backend::preparer(&tag, &minecraft, &log) + let result = backend::preparer(&tag, &minecraft, from, &log) .inspect(|(_, minecraft)| backend::sounds(&tag, minecraft, &log)) .and_then(|(p, _)| match p { backend::Preparer::Process(cmd) => { @@ -2232,10 +2235,22 @@ impl Launcher { .child(play), ); - let resources_value = if self.preparing { - tr("Preparing…").to_string() - } else { - backend::resources_summary(prepared, !silent, &version) + // Not prepared: an owner can have Horizon download Minecraft from Mojang; without an + // owner there is nothing to play, so signing in comes first. + let first = (!prepared && !self.preparing) + .then_some(self.owner) + .flatten(); + let resources_value = match first { + _ if self.preparing => tr("Preparing…").to_string(), + Some(true) => trf( + "Not prepared. Horizon can download Minecraft {version} from Mojang for your account, or use your own install.", + &[("version", &version)], + ), + Some(false) => trf( + "Not prepared. Sign in with the Microsoft account that owns Minecraft {version} first.", + &[("version", &version)], + ), + None => backend::resources_summary(prepared, !silent, &version), }; let mut prepare = button( "prepare", @@ -2251,10 +2266,44 @@ impl Launcher { prepare = disabled(prepare); } else { prepare = prepare.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.prepare(); + this.prepare(backend::MinecraftFrom::Install); cx.notify(); })); } + let prepare = match first { + Some(true) => div() + .flex() + .gap(px(8.)) + .child( + button("prepare-install", "From my install", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.prepare(backend::MinecraftFrom::Install); + cx.notify(); + }), + ), + ) + .child( + button( + "prepare-download", + "Download and prepare", + Kind::Secondary, + &t, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.prepare(backend::MinecraftFrom::Mojang); + cx.notify(); + })), + ), + Some(false) => div().child( + button("prepare-sign-in", "Sign in", Kind::Secondary, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.sign_in_to_play(); + cx.notify(); + }, + )), + ), + None => div().child(prepare), + }; let minecraft = self.settings.minecraft_dir.as_deref().map_or_else( || { div() @@ -2394,12 +2443,33 @@ impl Launcher { // looks after pressing Prepare, not below the fold (#666). if self.preparing { let last = self.prepare_log.back().cloned().unwrap_or_default(); + // A download from Mojang shows how far it is, and can stop (it goes on from there + // next time). + let download = horizon_launcher::mojang::progress(); + let cancel = download.map(|_| { + button("download-cancel", "Cancel", Kind::Ghost, &t).on_click(|_, _, _| { + horizon_launcher::mojang::CANCEL.store(true, Ordering::Relaxed) + }) + }); page = page.child( div() .flex() .flex_col() .gap(px(10.)) - .child(progress_bar(None, &t)) + .child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child(progress_bar( + download.map(|(done, total)| { + let f = done as f32 / total as f32; + (f, f) + }), + &t, + )) + .children(cancel), + ) .child( text(theme::MICRO) .text_color(t.muted) diff --git a/launcher/src/mojang.rs b/launcher/src/mojang.rs index f242672b9..32688f667 100644 --- a/launcher/src/mojang.rs +++ b/launcher/src/mojang.rs @@ -3,12 +3,16 @@ //! jar, this system's libraries and the assets (the sounds), each checked against its sha1, //! in the official launcher's layout in the launcher's data folder. sources.rs then finds them //! there like any launcher's. Nothing of Mojang's is part of Horizon. +//! +//! Each file is checked against the size and sha1 Mojang lists, and written whole. A download +//! stopped half way (cancelled, no network) keeps the files it finished: the next one fetches +//! only the rest. -use crate::sources::{fetch_checked, fetch_manifest, sha1_file, write_file, Fetch, Pins}; +use crate::sources::{fetch_checked, fetch_manifest, sha1_file, sha1_hex, write_file, Fetch, Pins}; use serde_json::Value; use std::fs; use std::path::{Component, Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering::Relaxed}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering::Relaxed}; use std::sync::Mutex; use std::time::Duration; @@ -16,22 +20,38 @@ const OBJECTS: &str = "https://resources.download.minecraft.net"; /// The index of Mojang's Java runtimes, the one the official launcher reads. const JAVA_RUNTIMES: &str = "https://launchermeta.mojang.com/v1/products/java-runtime/2ec0cc96c44e5a76b9c8b7c39df7210883d12871/all.json"; -/// One file to download. +/// Set to stop the download under way (the window's Cancel); cleared when a preparation starts. +pub static CANCEL: AtomicBool = AtomicBool::new(false); +/// The download under way: files done, of how many (0 when none runs). +static DONE: AtomicUsize = AtomicUsize::new(0); +static TOTAL: AtomicUsize = AtomicUsize::new(0); + +/// How far the download under way is, files done of how many; none when none runs. +pub fn progress() -> Option<(usize, usize)> { + let total = TOTAL.load(Relaxed); + (total > 0).then(|| (DONE.load(Relaxed).min(total), total)) +} + +const CANCELLED: &str = "Download cancelled. Download again to go on where it stopped."; + +/// One file to download, with the size Mojang lists for it when it lists one. struct File { url: String, sha1: String, + size: Option, path: PathBuf, } /// Downloads the pinned version into `dir`, `jobs` files at a time; files already there and /// whole are kept. An asset that fails is a line in the log (the game is then partly silent), -/// anything else an error. +/// anything else an error. `cancel` stops it between files. pub fn download( pins: &Pins, dir: &Path, os: &str, jobs: usize, fetch: Fetch, + cancel: &AtomicBool, log: &dyn Fn(String), ) -> Result<(), String> { let v = &pins.version; @@ -43,6 +63,7 @@ pub fn download( let mut game = vec![File { url: text(client, "url")?, sha1: pins.client_sha1.clone(), + size: client["size"].as_u64(), path: versions.join(format!("{v}.jar")), }]; let libraries = manifest["libraries"] @@ -56,6 +77,7 @@ pub fn download( game.push(File { url: text(artifact, "url")?, sha1: text(artifact, "sha1")?, + size: artifact["size"].as_u64(), path: dir .join("libraries") .join(relative(&text(artifact, "path")?)?), @@ -65,23 +87,26 @@ pub fn download( "Downloading Minecraft {v} from Mojang: the game and {} libraries", game.len() - 1 )); - fetch_all(&game, jobs, fetch, log)?; + fetch_all(&game, jobs, fetch, cancel, log)?; let index = &manifest["assetIndex"]; let index = File { url: text(index, "url")?, sha1: text(index, "sha1")?, + size: index["size"].as_u64(), path: dir .join("assets/indexes") .join(relative(&format!("{}.json", text(index, "id")?))?), }; - let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, log) + let assets = fetch_all(std::slice::from_ref(&index), 1, fetch, cancel, log) .and_then(|_| objects(&read_json(&index.path)?, dir)) .and_then(|objects| { log(format!("Downloading the sounds ({} files)", objects.len())); - fetch_all(&objects, jobs, fetch, log) + fetch_all(&objects, jobs, fetch, cancel, log) }); - if let Err(e) = assets { - log(format!("The sounds could not all be downloaded: {e}")); + match assets { + Err(e) if e == CANCELLED => return Err(e), + Err(e) => log(format!("The sounds could not all be downloaded: {e}")), + Ok(()) => {} } Ok(()) } @@ -110,6 +135,7 @@ pub fn java_runtime( runtime: &Path, jobs: usize, fetch: Fetch, + cancel: &AtomicBool, log: &dyn Fn(String), ) -> Result { let platform = java_platform().ok_or("Mojang has no Java for this system")?; @@ -144,6 +170,7 @@ pub fn java_runtime( downloads.push(File { url: text(raw, "url")?, sha1: text(raw, "sha1")?, + size: raw["size"].as_u64(), path, }); } @@ -156,7 +183,7 @@ pub fn java_runtime( "Downloading Minecraft's Java {name} from Mojang ({} files)", downloads.len() )); - fetch_all(&downloads, jobs, fetch, log)?; + fetch_all(&downloads, jobs, fetch, cancel, log)?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; @@ -243,6 +270,10 @@ fn objects(index: &Value, dir: &Path) -> Result, String> { let objects = index["objects"] .as_object() .ok_or("The asset index has no objects")?; + let sizes: std::collections::HashMap<&str, u64> = objects + .values() + .filter_map(|o| Some((o["hash"].as_str()?, o["size"].as_u64()?))) + .collect(); let mut hashes: Vec<&str> = objects .values() .filter_map(|o| o["hash"].as_str()) @@ -259,23 +290,42 @@ fn objects(index: &Value, dir: &Path) -> Result, String> { Ok(File { url: format!("{OBJECTS}/{path}"), sha1: hash.to_string(), + size: sizes.get(hash).copied(), path: dir.join("assets/objects").join(path), }) }) .collect() } -/// Downloads the files not already there, `jobs` at a time, with a line every few seconds; -/// stops at the first error. +/// One file from Mojang, refused unless it has the size and sha1 Mojang lists. +fn fetch_file(fetch: Fetch, file: &File) -> Result, String> { + let body = fetch(&file.url)?; + if let Some(size) = file.size.filter(|&size| size != body.len() as u64) { + return Err(format!( + "is {} bytes, not the {size} Mojang lists", + body.len() + )); + } + match sha1_hex(&body) { + actual if actual == file.sha1 => Ok(body), + actual => Err(format!("is not the one Horizon pins (sha1 {actual})")), + } +} + +/// Downloads the files not already there, `jobs` at a time, with a line every second; stops at +/// the first error, or between files once `cancel` is set. fn fetch_all( files: &[File], jobs: usize, fetch: Fetch, + cancel: &AtomicBool, log: &dyn Fn(String), ) -> Result<(), String> { let next = AtomicUsize::new(0); let done = AtomicUsize::new(0); let failed = Mutex::new(None); + DONE.store(0, Relaxed); + TOTAL.store(files.len(), Relaxed); std::thread::scope(|scope| { let workers: Vec<_> = (0..jobs.clamp(1, files.len().max(1))) .map(|_| { @@ -284,15 +334,19 @@ fn fetch_all( if failed.lock().unwrap().is_some() { break; } + if cancel.load(Relaxed) { + failed.lock().unwrap().get_or_insert(CANCELLED.to_string()); + break; + } if sha1_file(&file.path).as_ref() != Some(&file.sha1) { - let got = fetch_checked(fetch, &file.url, &file.sha1) + let got = fetch_file(fetch, file) .map_err(|e| format!("{} {e}", file.url)) .and_then(|body| write_file(&file.path, &body)); if let Err(e) = got { failed.lock().unwrap().get_or_insert(e); } } - done.fetch_add(1, Relaxed); + DONE.store(done.fetch_add(1, Relaxed) + 1, Relaxed); } }) }) @@ -301,11 +355,12 @@ fn fetch_all( while !workers.iter().all(|w| w.is_finished()) { std::thread::sleep(Duration::from_millis(100)); waited += 1; - if waited % 50 == 0 { + if waited % 10 == 0 { log(format!("{} of {} files", done.load(Relaxed), files.len())); } } }); + TOTAL.store(0, Relaxed); failed.into_inner().unwrap().map_or(Ok(()), Err) } diff --git a/launcher/src/mojang_tests.rs b/launcher/src/mojang_tests.rs index cd32e4c79..310fd72c2 100644 --- a/launcher/src/mojang_tests.rs +++ b/launcher/src/mojang_tests.rs @@ -8,6 +8,8 @@ const COMMON: &[u8] = b"a library every system uses"; const LINUX: &[u8] = b"a linux native"; const SOUND: &[u8] = b"a fake ogg"; const LANG: &[u8] = b"{}"; +/// Never cancelled. +static GO: AtomicBool = AtomicBool::new(false); /// The fake version file, asset index and files, by URL. fn mojang() -> (Pins, HashMap>) { @@ -28,7 +30,7 @@ fn mojang() -> (Pins, HashMap>) { "id": "26.3", "assetIndex": {"id": "34", "sha1": sha1_hex(index.as_bytes()), "url": "https://piston-meta.mojang.com/v1/packages/i/34.json"}, - "downloads": {"client": {"sha1": sha1_hex(CLIENT), "url": "https://piston-data.mojang.com/client.jar"}}, + "downloads": {"client": {"sha1": sha1_hex(CLIENT), "size": CLIENT.len(), "url": "https://piston-data.mojang.com/client.jar"}}, "libraries": [ {"name": "org.fake:common:1", "downloads": {"artifact": artifact("common", COMMON)}}, {"name": "org.fake:linux:1", "downloads": {"artifact": artifact("linux", LINUX)}, @@ -112,9 +114,15 @@ fn an_owner_gets_the_official_layout_with_this_systems_libraries() { }; let dir = scratch("layout"); let logged = Mutex::new(Vec::new()); - download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|line| { - logged.lock().unwrap().push(line) - }) + download( + &pins, + &dir, + "linux", + 3, + &|url| server.fetch(url), + &GO, + &|line| logged.lock().unwrap().push(line), + ) .unwrap(); assert_eq!( fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(), @@ -156,7 +164,16 @@ fn an_owner_gets_the_official_layout_with_this_systems_libraries() { &|_| {}, ); assert_eq!(found, Ok(Resolved::Folder(dir.clone()))); - download(&pins, &dir, "linux", 3, &|url| server.fetch(url), &|_| {}).unwrap(); + download( + &pins, + &dir, + "linux", + 3, + &|url| server.fetch(url), + &GO, + &|_| {}, + ) + .unwrap(); assert_eq!(server.asked(), Vec::::new()); fs::remove_dir_all(&dir).unwrap(); } @@ -169,7 +186,16 @@ fn macos_skips_what_its_rules_disallow() { asked: Mutex::new(Vec::new()), }; let dir = scratch("osx"); - download(&pins, &dir, "osx", 2, &|url| server.fetch(url), &|_| {}).unwrap(); + download( + &pins, + &dir, + "osx", + 2, + &|url| server.fetch(url), + &GO, + &|_| {}, + ) + .unwrap(); let libraries = dir.join("libraries/org/fake"); assert!(libraries.join("common/1/common-1.jar").is_file()); assert!(!libraries.join("linux").exists()); @@ -182,14 +208,23 @@ fn a_file_that_is_not_the_pinned_one_stops_the_download() { let (pins, mut files) = mojang(); files.insert( "https://piston-data.mojang.com/client.jar".into(), - b"something else".to_vec(), + b"fake client JAR".to_vec(), ); let server = Server { files, asked: Mutex::new(Vec::new()), }; let dir = scratch("bad-jar"); - let error = download(&pins, &dir, "linux", 2, &|url| server.fetch(url), &|_| {}).unwrap_err(); + let error = download( + &pins, + &dir, + "linux", + 2, + &|url| server.fetch(url), + &GO, + &|_| {}, + ) + .unwrap_err(); assert!( error.starts_with("https://piston-data.mojang.com/client.jar is not the one Horizon pins"), "{error}" @@ -209,9 +244,15 @@ fn missing_sounds_are_a_line_in_the_log_not_an_error() { }; let dir = scratch("no-sound"); let logged = Mutex::new(Vec::new()); - download(&pins, &dir, "linux", 1, &|url| server.fetch(url), &|line| { - logged.lock().unwrap().push(line) - }) + download( + &pins, + &dir, + "linux", + 1, + &|url| server.fetch(url), + &GO, + &|line| logged.lock().unwrap().push(line), + ) .unwrap(); assert!(dir.join("versions/26.3/26.3.jar").is_file()); let last = logged.lock().unwrap().last().cloned().unwrap(); @@ -290,6 +331,7 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() { &dir, 2, &|url| server.fetch(url), + &GO, &|_| {}, ) .unwrap(); @@ -316,6 +358,7 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() { &dir, 2, &|url| server.fetch(url), + &GO, &|_| {}, ) .unwrap(); @@ -325,8 +368,91 @@ fn java_runtime_lays_out_mojangs_runtime_with_its_executables_and_links() { &dir, 2, &|url| server.fetch(url), + &GO, &|_| {} ) .is_err()); fs::remove_dir_all(&dir).unwrap(); } + +#[test] +fn a_file_of_another_size_than_mojang_lists_is_refused() { + let (pins, mut files) = mojang(); + // A cut-off body: its size says so before its sha1. + files.insert( + "https://piston-data.mojang.com/client.jar".into(), + CLIENT[..4].to_vec(), + ); + let server = Server { + files, + asked: Mutex::new(Vec::new()), + }; + let dir = scratch("size"); + let error = download( + &pins, + &dir, + "linux", + 2, + &|url| server.fetch(url), + &GO, + &|_| {}, + ) + .unwrap_err(); + assert!( + error.ends_with(&format!( + "is 4 bytes, not the {} Mojang lists", + CLIENT.len() + )), + "{error}" + ); + assert!(!dir.join("versions/26.3/26.3.jar").exists()); + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn a_cancelled_download_goes_on_where_it_stopped() { + let (pins, files) = mojang(); + let server = Server { + files, + asked: Mutex::new(Vec::new()), + }; + let dir = scratch("cancel"); + let cancel = AtomicBool::new(false); + // Cancelled once the client jar has arrived: one job, so nothing after it starts. + let fetch = |url: &str| { + let body = server.fetch(url); + if url.ends_with("client.jar") { + cancel.store(true, Relaxed); + } + body + }; + let error = download(&pins, &dir, "linux", 1, &fetch, &cancel, &|_| {}).unwrap_err(); + assert_eq!(error, CANCELLED); + assert_eq!( + fs::read(dir.join("versions/26.3/26.3.jar")).unwrap(), + CLIENT + ); + assert!(!dir.join("libraries").exists()); + // Again: the version file and the jar are kept, only the rest is fetched. + cancel.store(false, Relaxed); + server.asked(); + download( + &pins, + &dir, + "linux", + 1, + &|url| server.fetch(url), + &cancel, + &|_| {}, + ) + .unwrap(); + let asked = server.asked(); + assert!( + !asked + .iter() + .any(|u| u.ends_with("client.jar") || u.ends_with("26.3.json")), + "{asked:#?}" + ); + assert_eq!(asked.len(), 6, "{asked:#?}"); + fs::remove_dir_all(&dir).unwrap(); +} diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index e3ed4f441..49ca08ddd 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -782,7 +782,7 @@ impl Launcher { self.servers.create = None; self.go(Page::Play); if !self.preparing { - self.prepare(); + self.prepare(backend::MinecraftFrom::Install); } } }, From d87b081c3471e2aaaa62db53f4d60430845cbd42 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 19:21:08 +0100 Subject: [PATCH 219/221] Trusted reviewers triage on GitHub: /close, /reopen, /label, /unlabel One list (.github/trusted-reviewers.txt) now governs /nightly and the triage commands. Co-Authored-By: Claude Sonnet 5.5 --- .github/nightly-reviewers.txt | 7 - .github/trusted-reviewers.txt | 8 + .github/workflows/nightly-command.yml | 4 +- .github/workflows/triage-command.yml | 48 +++++ docs/release-flow.md | 34 +++- tests/test_triage_command.py | 239 +++++++++++++++++++++++ tools/ci/nightly_set.py | 4 +- tools/ci/triage_command.py | 270 ++++++++++++++++++++++++++ 8 files changed, 599 insertions(+), 15 deletions(-) delete mode 100644 .github/nightly-reviewers.txt create mode 100644 .github/trusted-reviewers.txt create mode 100644 .github/workflows/triage-command.yml create mode 100644 tests/test_triage_command.py create mode 100644 tools/ci/triage_command.py diff --git a/.github/nightly-reviewers.txt b/.github/nightly-reviewers.txt deleted file mode 100644 index a2f9606aa..000000000 --- a/.github/nightly-reviewers.txt +++ /dev/null @@ -1,7 +0,0 @@ -# Trusted reviewers: they pick the pull requests the Nightly holds with `/nightly 2640 2642` in any issue or pull -# request (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). Ludovic is always allowed and isn't -# listed. One GitHub login per line, with who added it and when. Removing a line revokes that login at once. -# A line with only `paused` stops every reviewer's `/nightly` (Ludovic's still work). -kacpherek # added by Ludovic, 2026-10-27 -rdbtCVS # added by Ludovic, 2026-10-27 -Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests) diff --git a/.github/trusted-reviewers.txt b/.github/trusted-reviewers.txt new file mode 100644 index 000000000..550c528cc --- /dev/null +++ b/.github/trusted-reviewers.txt @@ -0,0 +1,8 @@ +# Trusted reviewers: one list for two things (docs/release-flow.md "Trusted reviewers"). +# - `/nightly 2640 2642` picks the pull requests the Nightly holds (tools/ci/nightly_set.py); +# - `/close`, `/reopen`, `/label`, `/unlabel` triage issues and pull requests (tools/ci/triage_command.py). +# Ludovic is always allowed and isn't listed. One GitHub login per line, with who added it and when. Removing a +# line revokes that login at once. A line with only `paused` stops both for every reviewer (Ludovic's still work). +kacpherek # added by Ludovic, 2026-10-27 +rdbtCVS # added by Ludovic, 2026-10-27 +Online5277 # added by Ludovic, 2026-10-27 (his top three by merged pull requests) diff --git a/.github/workflows/nightly-command.yml b/.github/workflows/nightly-command.yml index 340988d93..aef5c957b 100644 --- a/.github/workflows/nightly-command.yml +++ b/.github/workflows/nightly-command.yml @@ -1,5 +1,5 @@ name: nightly command -# `/nightly …` comments: the trusted reviewers in .github/nightly-reviewers.txt (and Ludovic) pick the pull requests +# `/nightly …` comments: the trusted reviewers in .github/trusted-reviewers.txt (and Ludovic) pick the pull requests # the Nightly holds (docs/release-flow.md "Nightly channel", tools/ci/nightly_set.py). This job only checks who asked, # saves the set on the nightly-state branch, starts `nightly build` and answers in the thread. # @@ -33,7 +33,7 @@ jobs: persist-credentials: false sparse-checkout: | .github/CODEOWNERS - .github/nightly-reviewers.txt + .github/trusted-reviewers.txt tools/ci/nightly_set.py sparse-checkout-cone-mode: false - name: Run the command diff --git a/.github/workflows/triage-command.yml b/.github/workflows/triage-command.yml new file mode 100644 index 000000000..938bbc337 --- /dev/null +++ b/.github/workflows/triage-command.yml @@ -0,0 +1,48 @@ +name: triage command +# `/close`, `/reopen`, `/label`, `/unlabel` comments: the trusted reviewers in .github/trusted-reviewers.txt (and +# Ludovic) triage issues and pull requests without any repository role (docs/release-flow.md "Trusted reviewers", +# tools/ci/triage_command.py). +# +# Why no pull request's code runs here, though the token can write: +# - `issue_comment` always runs this file from main, whoever comments and wherever. +# - It checks out main's script and list only, never a pull request; it reads threads through the API. +# - The comment's text and author reach the script as env vars, never in a shell line. The token stays in the step. +on: + issue_comment: + types: [created] +permissions: + contents: read +jobs: + command: + # Every other comment skips here, before a runner starts. + if: >- + github.event.comment.user.type != 'Bot' && ( + startsWith(github.event.comment.body, '/close') || + startsWith(github.event.comment.body, '/reopen') || + startsWith(github.event.comment.body, '/label') || + startsWith(github.event.comment.body, '/unlabel')) + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + issues: write + pull-requests: write + steps: + - uses: actions/checkout@v4 + with: + ref: main + persist-credentials: false + sparse-checkout: | + .github/trusted-reviewers.txt + tools/ci/nightly_set.py + tools/ci/triage_command.py + sparse-checkout-cone-mode: false + - name: Run the command + env: + GH_TOKEN: ${{ github.token }} + BODY: ${{ github.event.comment.body }} + AUTHOR: ${{ github.event.comment.user.login }} + ISSUE: ${{ github.event.issue.number }} + REPO: ${{ github.repository }} + COMMENT_URL: ${{ github.event.comment.html_url }} + run: python3 tools/ci/triage_command.py command diff --git a/docs/release-flow.md b/docs/release-flow.md index 09565bd2e..feadaa0a1 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -420,10 +420,36 @@ than main's head and holds something main lacks, otherwise main (`tools/ci/night new publishes nothing. A Nightly can include pull requests not reviewed yet: that is what it is for, playing them before the gate. -### Trusted reviewers pick the pull requests +### Trusted reviewers + +One list, `.github/trusted-reviewers.txt`, governs two things for the people on it (kacpherek, rdbtCVS and +Online5277 since 2026-10-27) and for Ludovic, with no repository role: `/nightly` (below) and triage by comment. + +```text +/close closes an issue as completed; a pull request is closed without merging +/close not planned closes an issue as not planned +/close duplicate of #123 comments "Duplicate of #123", closes as a duplicate +/reopen +/label bug, good first issue existing labels only; never creates one +/unlabel bug +``` + +- **Where.** On the first line of a comment on the issue or pull request (`.github/workflows/triage-command.yml`, + `tools/ci/triage_command.py`). The workflow answers with one comment, `🤖 Triage: , on behalf of @login`, + linking the comment that asked; a refusal answers too. +- **Refused.** Any label with `release` in its name (`release-now`, `release-blocker`, `skip-release`) and + `full-parity`; anything on Ludovic's own issues and pull requests; a merged pull request; a locked thread; more + than 60 actions per reviewer in 24 hours (counted from the workflow's own comments). +- **Safety.** Same as `/nightly`: main's copy of the workflow runs, no pull request's code is checked out or run, + the comment reaches the script as env vars, and the token has `issues` and `pull-requests` write only. +- **Ludovic stays in charge.** A one-line pull request removing a login from the list revokes it as soon as it merges + (the file is his under CODEOWNERS). A line `paused` stops `/nightly` and the triage commands for every reviewer; + his own still work. + +### Trusted reviewers pick the Nightly's pull requests The Nightly is where contributors test pull requests before the gate. The trusted reviewers listed in -`.github/nightly-reviewers.txt` (kacpherek, rdbtCVS and Online5277 since 2026-10-27) and Ludovic pick them with a +`.github/trusted-reviewers.txt` (kacpherek, rdbtCVS and Online5277 since 2026-10-27) and Ludovic pick them with a comment on any issue or pull request (`.github/workflows/nightly-command.yml`, `tools/ci/nightly_set.py`): ```text @@ -458,9 +484,9 @@ comment on any issue or pull request (`.github/workflows/nightly-command.yml`, ` - **Ludovic stays in charge.** - Ludovic's `/nightly clear` or `/nightly remove` always applies. A pull request he removed can only come back when he adds it. - - A one-line pull request removing a login from `.github/nightly-reviewers.txt` revokes it as soon as it merges + - A one-line pull request removing a login from `.github/trusted-reviewers.txt` revokes it as soon as it merges (the file is his under CODEOWNERS). - - A line `paused` in that file stops every reviewer's `/nightly`; his own still work. + - A line `paused` in that file stops every reviewer's `/nightly` (and triage commands); his own still work. - Main, the gate and releases don't change: picks reach only players who turned Nightly on. - **Jobs.** `pick` chooses or assembles the commit and writes the notes (each pull request in it with its title, diff --git a/tests/test_triage_command.py b/tests/test_triage_command.py new file mode 100644 index 000000000..2dbf14592 --- /dev/null +++ b/tests/test_triage_command.py @@ -0,0 +1,239 @@ +import unittest +from datetime import datetime, timezone +from pathlib import Path + +from tools.ci import nightly_set as ns +from tools.ci import triage_command as tc + +ROOT = Path(__file__).resolve().parents[1] +NOW = datetime(2026, 10, 28, 12, tzinfo=timezone.utc) +URL = "https://github.com/ludovic111/horizon/issues/5#issuecomment-1" +LIST = ns.read_reviewers("kacpherek\nrdbtCVS\n") + + +def thread(state="open", user="dev", labels=("bug",), pr=False, merged=False, locked=False): + t = {"state": state, "user": {"login": user}, "labels": [{"name": n} for n in labels], "locked": locked} + if pr: + t["pull_request"] = {"merged_at": "2026-10-27T00:00:00Z" if merged else None} + return t + + +class Fake: + def __init__(self, threads=None, labels=("bug", "good first issue", "release-now", "skip-release"), past=()): + self.threads = {5: thread()} if threads is None else threads + self.labels, self.past, self.calls = list(labels), list(past), [] + + def issue(self, n): + return self.threads.get(n) + + def label(self, name): + return next((l for l in self.labels if l.lower() == name.lower()), None) + + def add_labels(self, n, names): + self.calls.append(("add", n, names)) + + def remove_label(self, n, name): + self.calls.append(("remove", n, name)) + + def close(self, n, reason): + self.calls.append(("close", n, reason)) + + def reopen(self, n): + self.calls.append(("reopen", n)) + + def comment(self, n, text): + self.calls.append(("comment", n, text)) + + def recent_comments(self, since): + return self.past + + +def do(text, api=None, login="kacpherek", reviewers=LIST, n=5): + api = api or Fake() + return tc.run(api, tc.parse(text), login, n, URL, reviewers, NOW), api + + +class ParseTests(unittest.TestCase): + def test_commands_and_case(self): + self.assertEqual(tc.parse("/close"), tc.Command("close", "completed")) + self.assertEqual(tc.parse(" /CLOSE Not Planned "), tc.Command("close", "not_planned")) + self.assertEqual(tc.parse("/close completed"), tc.Command("close", "completed")) + self.assertEqual(tc.parse("/close duplicate of #123"), tc.Command("close", "duplicate", 123)) + self.assertEqual(tc.parse("/Close duplicate of 7"), tc.Command("close", "duplicate", 7)) + self.assertEqual(tc.parse("/reopen"), tc.Command("reopen")) + self.assertEqual(tc.parse("/label bug, good first issue ,bug"), tc.Command("label", labels=("bug", "good first issue"))) + self.assertEqual(tc.parse("/unlabel bug"), tc.Command("unlabel", labels=("bug",))) + + def test_first_line_only(self): + self.assertEqual(tc.parse("/close\n/label release-now"), tc.Command("close", "completed")) + self.assertIsNone(tc.parse("thanks\n/close")) + self.assertEqual(tc.parse("\n\n/reopen\nwhy"), tc.Command("reopen")) + + def test_not_commands(self): + for text in ("", "hello", "/nightly 5", "/closed", "/labels bug", "/closer", "close", "/unlabeled x"): + self.assertIsNone(tc.parse(text), text) + + def test_malformed(self): + for text in ("/close maybe", "/close duplicate of", "/reopen now", "/label", "/label ,", "/unlabel a, b", + "/label " + ",".join(str(i) for i in range(11))): + with self.assertRaises(tc.Refused, msg=text): + tc.parse(text) + + def test_quoting_is_safe(self): + with self.assertRaises(tc.Refused) as e: + tc.parse("/close @ludovic111 [x](http://evil)") + self.assertNotIn("@", str(e.exception)) + self.assertNotIn("](", str(e.exception)) + + +class AllowTests(unittest.TestCase): + def test_listed_and_ludovic(self): + do("/close", login="RDBTcvs") + do("/close", login="ludovic111") + + def test_stranger_refused(self): + with self.assertRaisesRegex(tc.Refused, "Only Ludovic"): + do("/close", login="someone") + + def test_paused(self): + paused = ns.read_reviewers("kacpherek\npaused\n") + with self.assertRaisesRegex(tc.Refused, "paused"): + do("/close", reviewers=paused) + do("/close", reviewers=paused, login="ludovic111") + + def test_the_repos_list_is_the_nightlys(self): + self.assertEqual(ns.REVIEWERS, ".github/trusted-reviewers.txt") + listed = ns.read_reviewers((ROOT / ns.REVIEWERS).read_text()) + self.assertEqual(listed.logins, {"kacpherek", "rdbtcvs", "online5277"}) + self.assertFalse(listed.paused) + + +class ActionTests(unittest.TestCase): + def test_close_issue(self): + text, api = do("/close not planned") + self.assertEqual(api.calls, [("close", 5, "not_planned")]) + self.assertIn("on behalf of @kacpherek", text) + self.assertIn(URL, text) + self.assertTrue(text.startswith("🤖 Triage: ")) + + def test_close_pr_has_no_reason(self): + api = Fake({5: thread(pr=True)}) + text, _ = do("/close", api) + self.assertEqual(api.calls, [("close", 5, None)]) + self.assertIn("without merging", text) + + def test_duplicate(self): + api = Fake({5: thread(), 9: thread()}) + text, _ = do("/close duplicate of #9", api) + self.assertEqual(api.calls, [("comment", 5, "Duplicate of #9"), ("close", 5, "duplicate")]) + self.assertIn("#9", text) + + def test_duplicate_of_missing_or_itself(self): + with self.assertRaisesRegex(tc.Refused, "no #9"): + do("/close duplicate of #9") + with self.assertRaisesRegex(tc.Refused, "itself"): + do("/close duplicate of #5") + + def test_reopen(self): + _, api = do("/reopen", Fake({5: thread("closed")})) + self.assertEqual(api.calls, [("reopen", 5)]) + with self.assertRaisesRegex(tc.Refused, "already open"): + do("/reopen") + with self.assertRaisesRegex(tc.Refused, "already closed"): + do("/close", Fake({5: thread("closed")})) + + def test_label_uses_the_real_name_and_skips_present(self): + _, api = do("/label Good First Issue, BUG") + self.assertEqual(api.calls, [("add", 5, ["good first issue"])]) + with self.assertRaisesRegex(tc.Refused, "already has"): + do("/label bug") + + def test_label_must_exist(self): + with self.assertRaisesRegex(tc.Refused, "no label"): + do("/label nonsense") + + def test_unlabel(self): + _, api = do("/unlabel BUG") + self.assertEqual(api.calls, [("remove", 5, "bug")]) + with self.assertRaisesRegex(tc.Refused, "doesn't have"): + do("/unlabel good first issue") + + +class RefusalTests(unittest.TestCase): + def test_release_and_parity_labels(self): + for name in ("release-now", "Release-Blocker", "skip-release", "full-parity", "prerelease"): + for verb in ("/label", "/unlabel"): + with self.assertRaisesRegex(tc.Refused, "release or parity", msg=name): + do(f"{verb} {name}", Fake(labels=(name,))) + with self.assertRaises(tc.Refused): + do("/label bug, release-now") + + def test_ludovics_threads(self): + for text in ("/close", "/label bug", "/unlabel bug", "/reopen"): + for t in (thread(user="ludovic111", state="closed" if text == "/reopen" else "open"), + thread(user="Ludovic111", pr=True)): + with self.assertRaisesRegex(tc.Refused, "Ludovic's"): + do(text, Fake({5: t})) + + def test_merged_pr(self): + for text in ("/close", "/reopen", "/label bug", "/unlabel bug"): + with self.assertRaisesRegex(tc.Refused, "merged"): + do(text, Fake({5: thread("closed", pr=True, merged=True)})) + + def test_locked(self): + for text in ("/close", "/label good first issue", "/unlabel bug"): + with self.assertRaisesRegex(tc.Refused, "locked"): + do(text, Fake({5: thread(locked=True)})) + + def test_missing_thread(self): + with self.assertRaisesRegex(tc.Refused, "no such"): + do("/close", Fake({})) + + def test_nothing_written_on_refusal(self): + api = Fake({5: thread(user="ludovic111")}) + with self.assertRaises(tc.Refused): + do("/close", api) + self.assertEqual(api.calls, []) + + +def past(login, n, who="github-actions[bot]"): + return [{"user": who, "body": f"🤖 Triage: closed as completed, on behalf of @{login} ([their comment](u))."} + for _ in range(n)] + + +class LimitTests(unittest.TestCase): + def test_sixty_a_day(self): + with self.assertRaisesRegex(tc.Refused, "60"): + do("/close", Fake(past=past("kacpherek", 60))) + do("/close", Fake(past=past("kacpherek", 59))) + + def test_other_reviewers_and_forged_comments_dont_count(self): + do("/close", Fake(past=past("rdbtcvs", 80))) + do("/close", Fake(past=past("kacpherek", 80, who="someone"))) + + def test_refusals_dont_count(self): + refusals = [{"user": "github-actions[bot]", "body": "🤖 Triage: refused, nope (asked by @kacpherek)"}] * 70 + do("/close", Fake(past=refusals)) + + def test_counts_case_insensitively(self): + with self.assertRaises(tc.Refused): + do("/close", Fake(past=past("kacpherek", 60)), login="Kacpherek") + + def test_ludovic_is_unlimited(self): + do("/close", Fake(past=past("ludovic111", 100)), login="ludovic111") + + +class WorkflowTests(unittest.TestCase): + def test_workflow_is_safe(self): + text = (ROOT / ".github/workflows/triage-command.yml").read_text() + run_lines = [l for l in text.splitlines() if l.strip().startswith("run:")] + self.assertEqual(run_lines, [" run: python3 tools/ci/triage_command.py command"]) + self.assertIn("persist-credentials: false", text) + self.assertNotIn("pull_request_target", text) + for perm in ("issues: write", "pull-requests: write", "contents: read"): + self.assertIn(perm, text) + self.assertNotIn("contents: write", text) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ci/nightly_set.py b/tools/ci/nightly_set.py index a192993d4..8122a8d1c 100644 --- a/tools/ci/nightly_set.py +++ b/tools/ci/nightly_set.py @@ -4,7 +4,7 @@ nightly_set.py command one `/nightly …` comment (nightly-command.yml): checks who asked, updates the set, starts the build and answers in the thread -A comment by Ludovic or by a login in .github/nightly-reviewers.txt, on any issue or pull request: +A comment by Ludovic or by a login in .github/trusted-reviewers.txt, on any issue or pull request: /nightly 2640 2642 the set becomes these pull requests, merged onto main in this order; builds now /nightly add 2650 adds one, or takes its newest head again; builds now @@ -35,7 +35,7 @@ from pathlib import Path from typing import Callable OWNER = "ludovic111" -REVIEWERS = ".github/nightly-reviewers.txt" +REVIEWERS = ".github/trusted-reviewers.txt" CODEOWNERS = ".github/CODEOWNERS" # What CODEOWNERS guards today, refused even if the file moved: what builds, signs and checks releases. ALWAYS_GUARDED = ["/.github/", "/tools/ci/", "/crates/horizon-release-sign/", "/crates/horizon-server/src/update.rs", diff --git a/tools/ci/triage_command.py b/tools/ci/triage_command.py new file mode 100644 index 000000000..6639bd8fc --- /dev/null +++ b/tools/ci/triage_command.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +"""Trusted reviewers triage issues and pull requests with comment commands (docs/release-flow.md "Trusted reviewers"). + + triage_command.py command one comment (triage-command.yml): checks who asked, acts, answers in the thread + +A comment by Ludovic or by a login in .github/trusted-reviewers.txt, on the first line: + + /close [completed|not planned] closes an issue (a pull request: closes it without merging) + /close duplicate of #123 comments "Duplicate of #123" and closes it as a duplicate + /reopen + /label bug, good first issue existing labels only; never creates one + /unlabel bug + +Refused with a one-line answer: a label with `release` in it or `full-parity`; anything by Ludovic (his issues and +pull requests); a merged pull request; a locked thread; more than 60 actions per reviewer in 24 hours. No code of any +pull request is read or run: only the comment's text, its author and the API's answers, which reach this script as +env vars. +""" +from __future__ import annotations + +import json +import os +import re +import subprocess +import sys +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Callable + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import nightly_set as ns # noqa: E402 (the same list, owner and paused rule as /nightly) + +MAX_PER_DAY = 60 +PREFIX = "🤖 Triage: " +COMMANDS = ("close", "reopen", "label", "unlabel") +REASONS = {"completed": "completed", "not planned": "not_planned", "not_planned": "not_planned"} +DUPLICATE = re.compile(r"^(?:as\s+)?(?:a\s+)?duplicate\s+of\s+#?(\d{1,7})$", re.I) +USAGE = ("Use `/close`, `/close not planned`, `/close duplicate of #123`, `/reopen`, `/label bug, good first issue` " + "or `/unlabel bug`.") + + +class Refused(Exception): + """A command that changes nothing; its text is the answer.""" + + +@dataclass +class Command: + verb: str # close, reopen, label, unlabel + reason: str | None = None # close: completed, not_planned, duplicate + original: int | None = None # close duplicate of #N + labels: tuple[str, ...] = () + + +def safe(text: str) -> str: + """Text of a comment, fit to quote back: no markdown, no mentions.""" + return re.sub(r"[^\w#:. -]", "", text)[:60].strip() or "?" + + +def parse(body: str) -> Command | None: + """The command on a comment's first line; None when it isn't one. Raises Refused when it is one, but wrong.""" + line = next((line.strip() for line in body.splitlines() if line.strip()), "") + m = re.match(r"^/(\w+)(?:\s+(.*))?$", line) + if not m or m.group(1).lower() not in COMMANDS: + return None + verb, rest = m.group(1).lower(), (m.group(2) or "").strip() + if verb == "reopen": + if rest: + raise Refused(f"`/reopen` takes no arguments. {USAGE}") + return Command("reopen") + if verb == "close": + if not rest: + return Command("close", "completed") + dup = DUPLICATE.match(rest) + if dup: + return Command("close", "duplicate", int(dup.group(1))) + reason = REASONS.get(" ".join(rest.lower().split())) + if not reason: + raise Refused(f"`{safe(rest)}` isn't a way to close. {USAGE}") + return Command("close", reason) + names = tuple(dict.fromkeys(n.strip() for n in rest.split(",") if n.strip())) + if not names: + raise Refused(f"`/{verb}` needs a label name. {USAGE}") + if verb == "unlabel" and len(names) > 1: + raise Refused(f"`/unlabel` takes one label. {USAGE}") + if len(names) > 10: + raise Refused("At most 10 labels at once.") + return Command(verb, labels=names) + + +def label_refusal(name: str) -> str | None: + low = name.lower() + if "release" in low or low == "full-parity": + return f"`{safe(name)}` is a release or parity label: only Ludovic's side touches those." + return None + + +def authorize(login: str, reviewers: ns.Reviewers) -> None: + """Ludovic always; a listed reviewer unless the list is paused; nobody else.""" + if ns.is_owner(login): + return + if login.lower() not in reviewers.logins: + raise Refused(f"Only Ludovic and the trusted reviewers listed in `{ns.REVIEWERS}` can triage this way.") + if reviewers.paused: + raise Refused(f"Triage commands are paused: Ludovic stopped them in `{ns.REVIEWERS}`.") + + +def target_refusal(issue: dict, cmd: Command, login: str) -> str | None: + """Why this thread can't be acted on (None when it can). `issue` is GitHub's issue object.""" + is_pr = "pull_request" in issue + kind = "pull request" if is_pr else "issue" + if not ns.is_owner(login) and ns.is_owner((issue.get("user") or {}).get("login", "")): + return f"This {kind} is Ludovic's: triage commands don't touch it." + if is_pr and (issue["pull_request"] or {}).get("merged_at"): + return "That pull request is already merged." + if issue.get("locked"): + return f"This {kind} is locked: triage commands don't act on it." + closed = issue.get("state") == "closed" + if cmd.verb == "close" and closed: + return f"This {kind} is already closed." + if cmd.verb == "reopen" and not closed: + return f"This {kind} is already open." + return None + + +def names_of(issue: dict) -> set[str]: + return {str(l.get("name", "") if isinstance(l, dict) else l).lower() for l in issue.get("labels", [])} + + +# --- GitHub ------------------------------------------------------------------------------------------------------ + + +def gh(*args: str, check: bool = True) -> str: + r = subprocess.run(["gh", *args], capture_output=True, text=True) + if check and r.returncode != 0: + raise RuntimeError(f"gh {args[0]} {args[1] if len(args) > 1 else ''}: {r.stderr.strip()[:300]}") + return r.stdout.strip() if r.returncode == 0 else "" + + +class Api: + """The few GitHub calls this needs; tests replace it.""" + + def __init__(self, repo: str): + self.repo = repo + + def issue(self, n: int) -> dict | None: + raw = gh("api", f"repos/{self.repo}/issues/{n}", check=False) + return json.loads(raw) if raw else None + + def label(self, name: str) -> str | None: + """The label's real name, or None when the repository has no such label.""" + raw = gh("api", f"repos/{self.repo}/labels/{name.replace('/', '%2F').replace(' ', '%20')}", check=False) + return json.loads(raw)["name"] if raw else None + + def add_labels(self, n: int, names: list[str]) -> None: + args = ["api", f"repos/{self.repo}/issues/{n}/labels"] + for name in names: + args += ["-f", f"labels[]={name}"] + gh(*args) + + def remove_label(self, n: int, name: str) -> None: + gh("api", "-X", "DELETE", f"repos/{self.repo}/issues/{n}/labels/{name.replace(' ', '%20')}") + + def close(self, n: int, reason: str | None) -> None: + args = ["api", "-X", "PATCH", f"repos/{self.repo}/issues/{n}", "-f", "state=closed"] + if reason: + args += ["-f", f"state_reason={reason}"] + gh(*args) + + def reopen(self, n: int) -> None: + gh("api", "-X", "PATCH", f"repos/{self.repo}/issues/{n}", "-f", "state=open") + + def comment(self, n: int, text: str) -> None: + gh("api", f"repos/{self.repo}/issues/{n}/comments", "-f", f"body={text}") + + def recent_comments(self, since: str) -> list[dict]: + """Comments of the whole repository since a time (ISO 8601), as {user, body}.""" + raw = gh("api", "--paginate", f"repos/{self.repo}/issues/comments?since={since}&per_page=100", "--jq", + '.[] | {user: .user.login, body: .body}') + return [json.loads(line) for line in raw.splitlines() if line.strip()] + + +def actions_by(api, login: str, now: datetime) -> int: + """Actions this workflow answered for `login` in the last 24 h, counted from its own comments.""" + since = (now - timedelta(hours=24)).strftime("%Y-%m-%dT%H:%M:%SZ") + tag = f"on behalf of @{login.lower()}" + return sum(1 for c in api.recent_comments(since) + if c["user"] == "github-actions[bot]" and c["body"].startswith(PREFIX) + and c["body"].split("\n", 1)[0].lower().count(tag)) + + +def say(action: str, login: str, url: str) -> str: + return f"{PREFIX}{action}, on behalf of @{login} ([their comment]({url}))." + + +def run(api, cmd: Command, login: str, number: int, url: str, reviewers: ns.Reviewers, now: datetime) -> str: + """Does the command; returns the comment to post. Raises Refused for a refusal.""" + authorize(login, reviewers) + for name in cmd.labels: + if (why := label_refusal(name)): + raise Refused(why) + issue = api.issue(number) + if issue is None: + raise Refused("There is no such issue or pull request.") + if (why := target_refusal(issue, cmd, login)): + raise Refused(why) + if cmd.original is not None: + if cmd.original == number: + raise Refused("An item cannot be a duplicate of itself.") + if api.issue(cmd.original) is None: + raise Refused(f"There is no #{cmd.original} in Horizon.") + if not ns.is_owner(login) and actions_by(api, login, now) >= MAX_PER_DAY: + raise Refused(f"You used your {MAX_PER_DAY} triage actions of the last 24 hours. Try again later.") + is_pr = "pull_request" in issue + if cmd.verb == "reopen": + api.reopen(number) + return say("reopened", login, url) + if cmd.verb == "close": + if cmd.reason == "duplicate": + api.comment(number, f"Duplicate of #{cmd.original}") + api.close(number, None if is_pr else "duplicate") + return say(f"closed as a duplicate of #{cmd.original}", login, url) + api.close(number, None if is_pr else cmd.reason) + how = "closed without merging" if is_pr else f"closed as {cmd.reason.replace('_', ' ')}" + return say(how, login, url) + have = names_of(issue) + real: list[str] = [] + for name in cmd.labels: + found = api.label(name) + if found is None: + raise Refused(f"There is no label `{safe(name)}` in Horizon: triage doesn't create new ones.") + if (why := label_refusal(found)): + raise Refused(why) + real.append(found) + if cmd.verb == "label": + new = [n for n in real if n.lower() not in have] + if not new: + raise Refused("It already has " + ("that label." if len(real) == 1 else "those labels.")) + api.add_labels(number, new) + return say("added " + ", ".join(f"`{n}`" for n in new), login, url) + name = real[0] + if name.lower() not in have: + raise Refused(f"It doesn't have `{name}`.") + api.remove_label(number, name) + return say(f"removed `{name}`", login, url) + + +def command() -> int: + body, login = os.environ["BODY"], os.environ["AUTHOR"] + number, url, repo = int(os.environ["ISSUE"]), os.environ.get("COMMENT_URL", ""), os.environ["REPO"] + api: Api = Api(repo) + try: + cmd = parse(body) + if cmd is None: + return 0 + reviewers = ns.read_reviewers(Path(ns.REVIEWERS).read_text()) + text = run(api, cmd, login, number, url, reviewers, datetime.now(timezone.utc)) + except Refused as e: + text = f"{PREFIX}refused, {e} (asked by @{safe(login)})" + except RuntimeError as e: + print(e, file=sys.stderr) + text = f"{PREFIX}GitHub refused that, nothing more was done (asked by @{safe(login)})." + api.comment(number, text) + return 0 + + +if __name__ == "__main__": + if sys.argv[1:] != ["command"]: + sys.exit(__doc__) + sys.exit(command()) From d2b0347777e42b39717ed568f6a2414a1fe46f21 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 27 Oct 2026 21:28:04 +0100 Subject: [PATCH 220/221] Point links at the horizon-rust organization The repositories moved from ludovic111 to the horizon-rust organization. GitHub redirects repository URLs but not GitHub Pages, so the mod index moved to https://horizon-rust.github.io/horizon-mods/: the launcher and the game read it there. The launcher still accepts icons and files from the old addresses, which a mirror keeps serving for launchers released before the move. Release notes thanked ludovic111 once the repository's owner became the organization (verify failed on main): the maintainer is now named. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CONTRIBUTING.md | 2 +- README.md | 8 +- ROADMAP.md | 132 +++++++++--------- .../server-equal-mixed-2026-10-18/README.md | 2 +- .../server-four-way-2026-10-19/README.md | 2 +- benchmarks/server-mixed-2026-10-18/README.md | 2 +- crates/cargo-horizon-mod/src/main.rs | 2 +- crates/cargo-horizon-mod/src/registry.rs | 4 +- crates/horizon-client/src/moved_extras.rs | 2 +- crates/horizon-friends/src/reach.rs | 2 +- crates/horizon-mod-registry/README.md | 4 +- crates/horizon-mod-registry/src/lib.rs | 2 +- crates/horizon-mods/src/index.rs | 2 +- crates/horizon-mods/src/index/registry.rs | 2 +- .../horizon-mods/src/index/registry/tests.rs | 8 +- crates/horizon-mods/src/index/tests.rs | 2 +- crates/horizon-mods/tests/index/index-v1.json | 14 +- crates/horizon-port-pack/src/modrinth.rs | 2 +- crates/horizon-server/src/service.rs | 2 +- crates/horizon-server/src/update.rs | 2 +- crates/horizon-telemetry-server/README.md | 4 +- .../horizon-telemetry-server/src/classes.rs | 2 +- crates/horizon-telemetry-server/src/lib.rs | 2 +- .../horizon-telemetry-server/src/summary.rs | 2 +- .../tests/fixtures/benchmarks/README.md | 2 +- crates/horizon-telemetry-server/tests/hub.rs | 4 +- .../horizon-telemetry-server/tests/summary.rs | 2 +- docs/api/README.md | 2 +- docs/api/mod-index.md | 8 +- docs/api/mods.md | 2 +- docs/design-system.md | 2 +- docs/hosting.md | 16 +-- docs/how-horizon-is-built.md | 8 +- docs/microsoft-account.md | 2 +- docs/mod-browser.md | 2 +- docs/mods.md | 6 +- docs/release-flow.md | 4 +- docs/research-lab.md | 2 +- docs/resource-packs.md | 12 +- docs/server.md | 4 +- docs/surface-generation-benchmark.md | 2 +- docs/telemetry.md | 2 +- docs/version-ports.md | 6 +- docs/versioning.md | 4 +- launcher/README.md | 2 +- launcher/src/backend.rs | 4 +- launcher/src/browser/download.rs | 6 +- launcher/src/browser/horizon.rs | 8 +- launcher/src/browser/images.rs | 6 +- launcher/src/signed.rs | 2 +- packaging/PLAY.txt | 2 +- packaging/server/install.ps1 | 4 +- packaging/server/install.sh | 4 +- roadmap/README.md | 2 +- tests/test_release_train.py | 4 +- tests/test_roadmap.py | 4 +- tests/test_triage_command.py | 2 +- tools/ci/legacy_releases.py | 2 +- tools/ci/linux-runner.sh | 4 +- tools/ci/new_release_key.sh | 2 +- tools/ci/protect_pipeline.sh | 2 +- tools/ci/version-port-daily.sh | 2 +- tools/parity_main.py | 2 +- tools/release_train.py | 6 +- tools/remote.sh | 2 +- tools/roadmap.py | 6 +- tools/server_bench.py | 2 +- 68 files changed, 194 insertions(+), 188 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e5561f7b5..ef232a1e2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -58,7 +58,7 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se Other top-level folders: `tools/` (harnesses and dev scripts), `tests/` (Python unit tests: `python3 -m unittest discover -s tests`), `mods/horizon/src/test/java/dev/horizonlab/parity/` (Java oracles), -`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private ludovic111/horizon-site: its build +`docs/`, `.github/workflows/`. The website (playhorizon.dev) is the private horizon-rust/horizon-site: its build reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` and `crates/horizon-theme/tokens.css` from main. ## Build and test fast diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03f3bd97b..42959f950 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -98,5 +98,5 @@ new pushes, we add it again. ## Talk to us -[Discord](https://discord.gg/HcTeMZxe5E) for questions and ideas, [issues](https://github.com/ludovic111/horizon/issues) +[Discord](https://discord.gg/HcTeMZxe5E) for questions and ideas, [issues](https://github.com/horizon-rust/horizon/issues) for bugs. If you want to take something on, say so in its issue so nobody else starts the same work. diff --git a/README.md b/README.md index ae85f7dbd..83a98975e 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@

- CI + CI Minecraft Java 26.3 Rust Vanilla parity 100% @@ -15,7 +15,7 @@ Website · Download · Documentation · - Release notes · + Release notes · Roadmap · Project status · Contributing @@ -29,7 +29,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that re ## Download -Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself. +Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/horizon-rust/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself. **You need** a Microsoft account that owns Minecraft: Java Edition (the launcher signs in with it, as other launchers do; see [Microsoft account](docs/microsoft-account.md)); Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install). @@ -99,7 +99,7 @@ Horizon contains no game files and never downloads them. It builds its resources 2. **Server jar:** the 26.3 server jar, from the `downloads.server.url` in your launcher's `versions/26.3/26.3.json` (or [minecraft.net/download/server](https://www.minecraft.net/en-us/download/server) while 26.3 is the current release). Pass it with `--server-jar` or set `HORIZON_SERVER_JAR`. It is only needed the first time. ```sh -git clone https://github.com/ludovic111/horizon.git +git clone https://github.com/horizon-rust/horizon.git cd horizon cargo run --release -p horizon-prepare -- --prepare --server-jar ~/Downloads/server.jar # needs JDK 25 cargo run --release -p horizon-prepare -- sounds # optional: sounds from your launcher install diff --git a/ROADMAP.md b/ROADMAP.md index 9b82f4fac..eacc5e75d 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -32,7 +32,7 @@ Making Horizon faster than vanilla on every computer, with smooth camera movemen

Technical -Frame pacing at render distance 32 ([#678](https://github.com/ludovic111/horizon/issues/678)): long frames come from work competing with the render thread. In review: world generation workers build free structure starts instead of queueing them ([#1760](https://github.com/ludovic111/horizon/issues/1760)), the worker pool leaves one core as vanilla does ([#1778](https://github.com/ludovic111/horizon/issues/1778)), and the terrain vertex arena is read as storage where flat draws run ([#1742](https://github.com/ludovic111/horizon/issues/1742)). Still open: far terrain at 48 to 64 chunks ([#718](https://github.com/ludovic111/horizon/issues/718)) and CPU-bound fields of block entities ([#717](https://github.com/ludovic111/horizon/issues/717)). Every change shows before and after numbers from `tools/perf_bench.py` against vanilla 26.3 ([docs/benchmark.md](docs/benchmark.md)). +Frame pacing at render distance 32 ([#678](https://github.com/horizon-rust/horizon/issues/678)): long frames come from work competing with the render thread. In review: world generation workers build free structure starts instead of queueing them ([#1760](https://github.com/horizon-rust/horizon/issues/1760)), the worker pool leaves one core as vanilla does ([#1778](https://github.com/horizon-rust/horizon/issues/1778)), and the terrain vertex arena is read as storage where flat draws run ([#1742](https://github.com/horizon-rust/horizon/issues/1742)). Still open: far terrain at 48 to 64 chunks ([#718](https://github.com/horizon-rust/horizon/issues/718)) and CPU-bound fields of block entities ([#717](https://github.com/horizon-rust/horizon/issues/717)). Every change shows before and after numbers from `tools/perf_bench.py` against vanilla 26.3 ([docs/benchmark.md](docs/benchmark.md)).
@@ -42,7 +42,7 @@ Speeding up the code that reads and writes the blocks of the world, which almost
Technical -`PalettedContainer` and `PackedStorage` find an entry's word by multiply and shift instead of an integer division ([#1790](https://github.com/ludovic111/horizon/issues/1790), [#1794](https://github.com/ludovic111/horizon/issues/1794)); meshing looks up baked models by index, not by name ([#1747](https://github.com/ludovic111/horizon/issues/1747)). Each change keeps the paletted storage harnesses identical and shows its microbenchmark ([docs/performance/paletted-container-access-results.md](docs/performance/paletted-container-access-results.md)). +`PalettedContainer` and `PackedStorage` find an entry's word by multiply and shift instead of an integer division ([#1790](https://github.com/horizon-rust/horizon/issues/1790), [#1794](https://github.com/horizon-rust/horizon/issues/1794)); meshing looks up baked models by index, not by name ([#1747](https://github.com/horizon-rust/horizon/issues/1747)). Each change keeps the paletted storage harnesses identical and shows its microbenchmark ([docs/performance/paletted-container-access-results.md](docs/performance/paletted-container-access-results.md)).
@@ -54,7 +54,7 @@ Making the world-generation mods of popular modpacks (new structures, YUNG's dun
Technical -`horizon-port-pack` carries a pack's data-driven content over; structure mods that need code get a native port: YUNG's worldgen as written ([#1746](https://github.com/ludovic111/horizon/issues/1746)), Lithostitched's limited and guaranteed elements with pool and processor modifiers ([#1777](https://github.com/ludovic111/horizon/issues/1777)), its processors as the game's own types ([#1765](https://github.com/ludovic111/horizon/issues/1765)). Proved by the structure blocks and layout harnesses ([#1753](https://github.com/ludovic111/horizon/issues/1753), [#1757](https://github.com/ludovic111/horizon/issues/1757)). Mods whose Java code does more than world generation don't run ([docs/modpacks.md](docs/modpacks.md)). +`horizon-port-pack` carries a pack's data-driven content over; structure mods that need code get a native port: YUNG's worldgen as written ([#1746](https://github.com/horizon-rust/horizon/issues/1746)), Lithostitched's limited and guaranteed elements with pool and processor modifiers ([#1777](https://github.com/horizon-rust/horizon/issues/1777)), its processors as the game's own types ([#1765](https://github.com/horizon-rust/horizon/issues/1765)). Proved by the structure blocks and layout harnesses ([#1753](https://github.com/horizon-rust/horizon/issues/1753), [#1757](https://github.com/horizon-rust/horizon/issues/1757)). Mods whose Java code does more than world generation don't run ([docs/modpacks.md](docs/modpacks.md)).
@@ -66,7 +66,7 @@ When you play on a server, other players, mobs, items and menus look and behave
Technical -Client-of-a-server fixes in `game/remote*.rs` and `horizon-protocol`: mobs' aggressive and item-use flags ([#1802](https://github.com/ludovic111/horizon/issues/1802), [#1798](https://github.com/ludovic111/horizon/issues/1798)), ghost items after a remote menu ([#1795](https://github.com/ludovic111/horizon/issues/1795)), skins ([#1652](https://github.com/ludovic111/horizon/issues/1652)), cookies and transfer packets for proxy networks ([#1650](https://github.com/ludovic111/horizon/issues/1650)), firework boosts ([#1671](https://github.com/ludovic111/horizon/issues/1671)), living-entity attributes and simulation distance ([#1731](https://github.com/ludovic111/horizon/issues/1731)), styled item names ([#1702](https://github.com/ludovic111/horizon/issues/1702)), primed TNT between updates ([#1710](https://github.com/ludovic111/horizon/issues/1710)). +Client-of-a-server fixes in `game/remote*.rs` and `horizon-protocol`: mobs' aggressive and item-use flags ([#1802](https://github.com/horizon-rust/horizon/issues/1802), [#1798](https://github.com/horizon-rust/horizon/issues/1798)), ghost items after a remote menu ([#1795](https://github.com/horizon-rust/horizon/issues/1795)), skins ([#1652](https://github.com/horizon-rust/horizon/issues/1652)), cookies and transfer packets for proxy networks ([#1650](https://github.com/horizon-rust/horizon/issues/1650)), firework boosts ([#1671](https://github.com/horizon-rust/horizon/issues/1671)), living-entity attributes and simulation distance ([#1731](https://github.com/horizon-rust/horizon/issues/1731)), styled item names ([#1702](https://github.com/horizon-rust/horizon/issues/1702)), primed TNT between updates ([#1710](https://github.com/horizon-rust/horizon/issues/1710)).
@@ -76,7 +76,7 @@ Servers that show dialogs, such as the register and login screens of AuthMe, wil
Technical -26.3's dialog packets and model ([#1720](https://github.com/ludovic111/horizon/issues/1720)), the dialog screen with its buttons and actions ([#1734](https://github.com/ludovic111/horizon/issues/1734)), then text and boolean inputs ([#1735](https://github.com/ludovic111/horizon/issues/1735)). +26.3's dialog packets and model ([#1720](https://github.com/horizon-rust/horizon/issues/1720)), the dialog screen with its buttons and actions ([#1734](https://github.com/horizon-rust/horizon/issues/1734)), then text and boolean inputs ([#1735](https://github.com/horizon-rust/horizon/issues/1735)).
@@ -86,7 +86,7 @@ A /pregen command that builds an area of the world ahead of time, so players don
Technical -Generates, lights and saves an area before anyone walks there ([#1805](https://github.com/ludovic111/horizon/issues/1805), a contributor's pull request, in review). Useful on servers, and it moves the generation cost away from the first visit; the generation speed-ups are under 'Steady frames at long render distances'. +Generates, lights and saves an area before anyone walks there ([#1805](https://github.com/horizon-rust/horizon/issues/1805), a contributor's pull request, in review). Useful on servers, and it moves the generation cost away from the first visit; the generation speed-ups are under 'Steady frames at long render distances'.
@@ -98,7 +98,7 @@ One place for mods, modpacks and resource packs made for Horizon: browse them on
Technical -Merged: the registry index (schema 1, `.hpack`, checks before install, [#1634](https://github.com/ludovic111/horizon/issues/1634)), `cargo horizon-mod check` ([#1642](https://github.com/ludovic111/horizon/issues/1642)) and the submission service (`crates/horizon-mod-registry`, [#1659](https://github.com/ludovic111/horizon/issues/1659)). In review: the website's /mods ([#1596](https://github.com/ludovic111/horizon/issues/1596)) and /mods/submit ([#1635](https://github.com/ludovic111/horizon/issues/1635)), and in the launcher the registry as a source ([#1636](https://github.com/ludovic111/horizon/issues/1636)), install, enable and takedowns ([#1637](https://github.com/ludovic111/horizon/issues/1637)), the Mods page ([#1638](https://github.com/ludovic111/horizon/issues/1638)) and modpacks as their own profiles ([#1640](https://github.com/ludovic111/horizon/issues/1640)). +Merged: the registry index (schema 1, `.hpack`, checks before install, [#1634](https://github.com/horizon-rust/horizon/issues/1634)), `cargo horizon-mod check` ([#1642](https://github.com/horizon-rust/horizon/issues/1642)) and the submission service (`crates/horizon-mod-registry`, [#1659](https://github.com/horizon-rust/horizon/issues/1659)). In review: the website's /mods ([#1596](https://github.com/horizon-rust/horizon/issues/1596)) and /mods/submit ([#1635](https://github.com/horizon-rust/horizon/issues/1635)), and in the launcher the registry as a source ([#1636](https://github.com/horizon-rust/horizon/issues/1636)), install, enable and takedowns ([#1637](https://github.com/horizon-rust/horizon/issues/1637)), the Mods page ([#1638](https://github.com/horizon-rust/horizon/issues/1638)) and modpacks as their own profiles ([#1640](https://github.com/horizon-rust/horizon/issues/1640)). More: [docs/mods.md](docs/mods.md) @@ -110,7 +110,7 @@ Mods that run on the server side of a world, so a dedicated server or a LAN worl
Technical -API 0.3, experimental first ([#1833](https://github.com/ludovic111/horizon/issues/1833), in review): the same sandboxed component runs on the server thread and the dedicated server, with world events (block broken or placed, entity spawned or killed, player joined or left), game rules and server commands with typed arguments. The world, item and entity interfaces come after (see 'Mods that read and change the world'). [docs/api/mods.md](docs/api/mods.md), [docs/mods.md](docs/mods.md). +API 0.3, experimental first ([#1833](https://github.com/horizon-rust/horizon/issues/1833), in review): the same sandboxed component runs on the server thread and the dedicated server, with world events (block broken or placed, entity spawned or killed, player joined or left), game rules and server commands with typed arguments. The world, item and entity interfaces come after (see 'Mods that read and change the world'). [docs/api/mods.md](docs/api/mods.md), [docs/mods.md](docs/mods.md).
@@ -120,7 +120,7 @@ Mods will be able to open their own screens and settings pages and react to keys
Technical -Capability `ui` is in review ([#1864](https://github.com/ludovic111/horizon/issues/1864)): mod-owned screens and a settings page under Options > Mods, built from vanilla's widgets. Still to design: `input` (an item's use, key binds, the crosshair target), `render` (a budgeted draw list on the native shader API) and `world` (changing blocks). Orbital Laser is the acceptance test: it needs all four today through its author's fork (see 'Orbital Laser on the normal game'). +Capability `ui` is in review ([#1864](https://github.com/horizon-rust/horizon/issues/1864)): mod-owned screens and a settings page under Options > Mods, built from vanilla's widgets. Still to design: `input` (an item's use, key binds, the crosshair target), `render` (a budgeted draw list on the native shader API) and `world` (changing blocks). Orbital Laser is the acceptance test: it needs all four today through its author's fork (see 'Orbital Laser on the normal game'). More: [docs/mods.md](docs/mods.md) @@ -132,7 +132,7 @@ Better tools for mod makers: a test runner that needs no game window, templates
Technical -`cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/ludovic111/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/ludovic111/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/ludovic111/horizon/issues/1859), [#1810](https://github.com/ludovic111/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable. +`cargo horizon-mod test` runs a mod's test scripts against a fake game snapshot ([#1816](https://github.com/horizon-rust/horizon/issues/1816)) and, for server mods, scripted server events ([#1837](https://github.com/horizon-rust/horizon/issues/1837)); the content template and the guides are merged ([#1859](https://github.com/horizon-rust/horizon/issues/1859), [#1810](https://github.com/horizon-rust/horizon/issues/1810), [docs/api/stability.md](docs/api/stability.md)). Left: templates for hud, server and machine mods, typed wrappers in the SDK, a frozen 0.1 compatibility mod that every runtime must load, a CI check that fails when a stable reference entry is removed without a new major version, and the SDK on crates.io once the API is stable. More: [https://playhorizon.dev/docs/test-a-mod](https://playhorizon.dev/docs/test-a-mod) @@ -146,7 +146,7 @@ Single player now runs a small server in the background, as vanilla does. We are
Technical -Since [#1514](https://github.com/ludovic111/horizon/issues/1514) single player runs on the server thread (`game/integrated.rs`) and the window joins it as a client; `--in-frame` keeps the old path. The open `[server-thread]` issues list the gaps. In review: a tool that changes a block ends the click ([#1797](https://github.com/ludovic111/horizon/issues/1797)), potions keep their potion over the connection ([#1796](https://github.com/ludovic111/horizon/issues/1796)), mobs' aggression and arm swings ([#1802](https://github.com/ludovic111/horizon/issues/1802)). [docs/server-levels.md](docs/server-levels.md). +Since [#1514](https://github.com/horizon-rust/horizon/issues/1514) single player runs on the server thread (`game/integrated.rs`) and the window joins it as a client; `--in-frame` keeps the old path. The open `[server-thread]` issues list the gaps. In review: a tool that changes a block ends the click ([#1797](https://github.com/horizon-rust/horizon/issues/1797)), potions keep their potion over the connection ([#1796](https://github.com/horizon-rust/horizon/issues/1796)), mobs' aggression and arm swings ([#1802](https://github.com/horizon-rust/horizon/issues/1802)). [docs/server-levels.md](docs/server-levels.md).
@@ -156,7 +156,7 @@ Item names, container titles and server messages follow the language you pick, a
Technical -Translatable components resolved through the selected language for items, containers and server text ([#1806](https://github.com/ludovic111/horizon/issues/1806)), on top of the bundled languages the prepared resources carry ([#1594](https://github.com/ludovic111/horizon/issues/1594)). Left: the client's own screens ([#1672](https://github.com/ludovic111/horizon/issues/1672)) and the main menu with zh_cn ([#1774](https://github.com/ludovic111/horizon/issues/1774)). +Translatable components resolved through the selected language for items, containers and server text ([#1806](https://github.com/horizon-rust/horizon/issues/1806)), on top of the bundled languages the prepared resources carry ([#1594](https://github.com/horizon-rust/horizon/issues/1594)). Left: the client's own screens ([#1672](https://github.com/horizon-rust/horizon/issues/1672)) and the main menu with zh_cn ([#1774](https://github.com/horizon-rust/horizon/issues/1774)).
@@ -166,9 +166,9 @@ After you throw an ender pearl, its slot should show the cooldown sweeping away,
Technical -Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/ludovic111/horizon/issues/1763). +Vanilla draws `ItemCooldowns`' percent as a white overlay over the slot (`GuiGraphicsExtractor.itemDecorations` and `itemCooldown`) in the hotbar and in inventories. Issue [#1763](https://github.com/horizon-rust/horizon/issues/1763). -More: [#1933](https://github.com/ludovic111/horizon/issues/1933) +More: [#1933](https://github.com/horizon-rust/horizon/issues/1933)
@@ -178,9 +178,9 @@ The Hidden and Commands Only chat settings should hide chat, and team prefixes s
Technical -Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/ludovic111/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/ludovic111/horizon/issues/1378)). Both issues have exact steps to reproduce. +Vanilla checks `ChatVisiblity` before it delivers chat and system messages ([#1376](https://github.com/horizon-rust/horizon/issues/1376)), and chat uses the team-formatted display name ([#1378](https://github.com/horizon-rust/horizon/issues/1378)). Both issues have exact steps to reproduce. -More: [#1932](https://github.com/ludovic111/horizon/issues/1932) · [#1841](https://github.com/ludovic111/horizon/issues/1841) +More: [#1932](https://github.com/horizon-rust/horizon/issues/1932) · [#1841](https://github.com/horizon-rust/horizon/issues/1841)
@@ -190,9 +190,9 @@ The mouse pointer should turn into a pointing hand over menu buttons, as in vani
Technical -26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/ludovic111/horizon/issues/1347). +26.3's `AbstractWidget` asks for a cursor from `CursorTypes` when it is hovered; winit's `CursorIcon::Pointer` gives the same shape. Issue [#1347](https://github.com/horizon-rust/horizon/issues/1347). -More: [#1897](https://github.com/ludovic111/horizon/issues/1897) +More: [#1897](https://github.com/horizon-rust/horizon/issues/1897)
@@ -202,9 +202,9 @@ Ctrl+Backspace should delete a whole word in the creative search, and every list
Technical -`EditBox` deletes by word with Ctrl ([#1764](https://github.com/ludovic111/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/ludovic111/horizon/issues/1782), after [#978](https://github.com/ludovic111/horizon/issues/978)). +`EditBox` deletes by word with Ctrl ([#1764](https://github.com/horizon-rust/horizon/issues/1764)); the Game Rules and Statistics lists' scroll bars can't be dragged ([#1782](https://github.com/horizon-rust/horizon/issues/1782), after [#978](https://github.com/horizon-rust/horizon/issues/978)). -More: [#1884](https://github.com/ludovic111/horizon/issues/1884) · [#1931](https://github.com/ludovic111/horizon/issues/1931) +More: [#1884](https://github.com/horizon-rust/horizon/issues/1884) · [#1931](https://github.com/horizon-rust/horizon/issues/1931)
@@ -214,9 +214,9 @@ Chickens should flap their wings while they fall, not stand still in the air.
Technical -Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/ludovic111/horizon/issues/1706). +Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't on the ground, and the model's wings follow them. Issue [#1706](https://github.com/horizon-rust/horizon/issues/1706). -More: [#1892](https://github.com/ludovic111/horizon/issues/1892) +More: [#1892](https://github.com/horizon-rust/horizon/issues/1892)
@@ -228,9 +228,9 @@ Shader packs were removed and are being rebuilt from scratch. They come back, of
Technical -A clean-room rewrite in `horizon-shaderpack`, from the packs' public format documentation only: reading packs, the preprocessor and `.properties` files are merged ([#1584](https://github.com/ludovic111/horizon/issues/1584), [#1585](https://github.com/ludovic111/horizon/issues/1585), [#1586](https://github.com/ludovic111/horizon/issues/1586)); translating programs to WGSL through naga, buffers, uniforms and the terrain, entity, sky, weather and hand stages are in review ([#1698](https://github.com/ludovic111/horizon/issues/1698) to [#1801](https://github.com/ludovic111/horizon/issues/1801)). +A clean-room rewrite in `horizon-shaderpack`, from the packs' public format documentation only: reading packs, the preprocessor and `.properties` files are merged ([#1584](https://github.com/horizon-rust/horizon/issues/1584), [#1585](https://github.com/horizon-rust/horizon/issues/1585), [#1586](https://github.com/horizon-rust/horizon/issues/1586)); translating programs to WGSL through naga, buffers, uniforms and the terrain, entity, sky, weather and hand stages are in review ([#1698](https://github.com/horizon-rust/horizon/issues/1698) to [#1801](https://github.com/horizon-rust/horizon/issues/1801)). -More: [#1561](https://github.com/ludovic111/horizon/issues/1561) · [#1771](https://github.com/ludovic111/horizon/issues/1771) · [#1786](https://github.com/ludovic111/horizon/issues/1786) +More: [#1561](https://github.com/horizon-rust/horizon/issues/1561) · [#1771](https://github.com/horizon-rust/horizon/issues/1771) · [#1786](https://github.com/horizon-rust/horizon/issues/1786)
@@ -240,7 +240,7 @@ Horizon's own way to make shader packs, with tools to write and test them. Every
Technical -`horizon-shader-api` (API 0.1, experimental): WGSL stages with typed inputs inside the renderer's passes, options as WGSL override constants, and the `horizon-shader new|check|pack` tool with templates and the example pack Golden Hour. Merged: the check every pack passes ([#1820](https://github.com/ludovic111/horizon/issues/1820)) and the tool, templates and guide ([#1822](https://github.com/ludovic111/horizon/issues/1822)). In review: the post stage running in the game with hot reload ([#1861](https://github.com/ludovic111/horizon/issues/1861)), the sky stage ([#1863](https://github.com/ludovic111/horizon/issues/1863)) and registry checks that use the game's own check ([#1855](https://github.com/ludovic111/horizon/issues/1855)). Left: the material, lighting and shadow stages, a last-good fallback on reload, a GPU-time overlay per stage and budgets ([docs/shaders.md](docs/shaders.md), [docs/api/shaders.md](docs/api/shaders.md)). The Iris/OptiFine loader is a separate item, 'Shader packs, written again from scratch'. +`horizon-shader-api` (API 0.1, experimental): WGSL stages with typed inputs inside the renderer's passes, options as WGSL override constants, and the `horizon-shader new|check|pack` tool with templates and the example pack Golden Hour. Merged: the check every pack passes ([#1820](https://github.com/horizon-rust/horizon/issues/1820)) and the tool, templates and guide ([#1822](https://github.com/horizon-rust/horizon/issues/1822)). In review: the post stage running in the game with hot reload ([#1861](https://github.com/horizon-rust/horizon/issues/1861)), the sky stage ([#1863](https://github.com/horizon-rust/horizon/issues/1863)) and registry checks that use the game's own check ([#1855](https://github.com/horizon-rust/horizon/issues/1855)). Left: the material, lighting and shadow stages, a last-good fallback on reload, a GPU-time overlay per stage and budgets ([docs/shaders.md](docs/shaders.md), [docs/api/shaders.md](docs/api/shaders.md)). The Iris/OptiFine loader is a separate item, 'Shader packs, written again from scratch'.
@@ -252,7 +252,7 @@ Your Discord profile can show that you are playing Horizon, with a switch to tur
Technical -A Discord IPC client on its own thread ([#1787](https://github.com/ludovic111/horizon/issues/1787)) and the presence with its setting ([#1788](https://github.com/ludovic111/horizon/issues/1788)). Merged: it ships with the next release. +A Discord IPC client on its own thread ([#1787](https://github.com/horizon-rust/horizon/issues/1787)) and the presence with its setting ([#1788](https://github.com/horizon-rust/horizon/issues/1788)). Merged: it ships with the next release.
@@ -264,7 +264,7 @@ Cleaning up Horizon's code: removing what nothing uses and making it quicker to
Technical -A review of the whole tree: dead code and stubs removed ([#1432](https://github.com/ludovic111/horizon/issues/1432), [#1658](https://github.com/ludovic111/horizon/issues/1658)), one probe binary per crate ([#1453](https://github.com/ludovic111/horizon/issues/1453), [#1454](https://github.com/ludovic111/horizon/issues/1454)), shared harness helpers ([#1448](https://github.com/ludovic111/horizon/issues/1448)), clippy clean on the whole tree ([#1707](https://github.com/ludovic111/horizon/issues/1707)). [docs/architecture.md](docs/architecture.md) maps each feature to its files and harnesses. +A review of the whole tree: dead code and stubs removed ([#1432](https://github.com/horizon-rust/horizon/issues/1432), [#1658](https://github.com/horizon-rust/horizon/issues/1658)), one probe binary per crate ([#1453](https://github.com/horizon-rust/horizon/issues/1453), [#1454](https://github.com/horizon-rust/horizon/issues/1454)), shared harness helpers ([#1448](https://github.com/horizon-rust/horizon/issues/1448)), clippy clean on the whole tree ([#1707](https://github.com/horizon-rust/horizon/issues/1707)). [docs/architecture.md](docs/architecture.md) maps each feature to its files and harnesses.
@@ -278,7 +278,7 @@ New public numbers comparing Horizon with vanilla on many kinds of computers, me
Technical -Redo the comparison after the current performance work ([#1073](https://github.com/ludovic111/horizon/issues/1073)); reliability, coverage and presentation ([#1346](https://github.com/ludovic111/horizon/issues/1346)); a scene must count as loaded only once its first chunk arrives ([#1749](https://github.com/ludovic111/horizon/issues/1749)). Next: a performance history across releases (an automatic comparison of each release with the last, on a timeline), more report fields (server TPS and MSPT, power, battery drain, temperature, throttling) and more hardware (a MacBook on battery, low-end laptops, community reports). Players' reports come in through `--benchmark` and `horizon-launcher data benchmark` ([docs/benchmark.md](docs/benchmark.md)). +Redo the comparison after the current performance work ([#1073](https://github.com/horizon-rust/horizon/issues/1073)); reliability, coverage and presentation ([#1346](https://github.com/horizon-rust/horizon/issues/1346)); a scene must count as loaded only once its first chunk arrives ([#1749](https://github.com/horizon-rust/horizon/issues/1749)). Next: a performance history across releases (an automatic comparison of each release with the last, on a timeline), more report fields (server TPS and MSPT, power, battery drain, temperature, throttling) and more hardware (a MacBook on battery, low-end laptops, community reports). Players' reports come in through `--benchmark` and `horizon-launcher data benchmark` ([docs/benchmark.md](docs/benchmark.md)).
@@ -288,7 +288,7 @@ Creating a world and joining it should be quick even on a four-thread laptop, wh
Technical -Cut the per-column generation cost (noise sampling, surface rules, aquifers) and the lock convoy on structure starts, and leave one core free for the rest of the game as vanilla does ([#1760](https://github.com/ludovic111/horizon/issues/1760) and [#1778](https://github.com/ludovic111/horizon/issues/1778), in review, are listed under 'Steady frames at long render distances'). Still to profile on small CPUs: the first seconds of a fresh world deliver no chunk, and fluids remesh for about a minute after loading. Measured with `tools/perf_bench.py` ([docs/benchmark.md](docs/benchmark.md), [docs/profiling.md](docs/profiling.md)). +Cut the per-column generation cost (noise sampling, surface rules, aquifers) and the lock convoy on structure starts, and leave one core free for the rest of the game as vanilla does ([#1760](https://github.com/horizon-rust/horizon/issues/1760) and [#1778](https://github.com/horizon-rust/horizon/issues/1778), in review, are listed under 'Steady frames at long render distances'). Still to profile on small CPUs: the first seconds of a fresh world deliver no chunk, and fluids remesh for about a minute after loading. Measured with `tools/perf_bench.py` ([docs/benchmark.md](docs/benchmark.md), [docs/profiling.md](docs/profiling.md)).
@@ -320,7 +320,7 @@ Draw the game at a lower resolution and sharpen it to your screen's size, in the
Technical -A render-scale setting below the window size with an upscaler of our own that runs on every wgpu backend. Proof: frame time against native resolution on integrated GPUs, and screenshots for image quality. Issue [#1403](https://github.com/ludovic111/horizon/issues/1403). +A render-scale setting below the window size with an upscaler of our own that runs on every wgpu backend. Proof: frame time against native resolution on integrated GPUs, and screenshots for image quality. Issue [#1403](https://github.com/horizon-rust/horizon/issues/1403).
@@ -330,7 +330,7 @@ Several smaller speed-ups, each measured: idle block entities that sleep, cheape
Technical -Block entities and hoppers that skip work when idle (the hopper item scan is already skipped when no item is near); a particle frustum test first (also a parity gap), then particle quads built on the GPU; jigsaw shortcuts that skip blocked connectors and pool elements known not to fit, with layouts unchanged (trial chambers and ancient cities first); batched raw mouse input on Windows for 8000 Hz mice; a better atlas packer for huge resource packs (a 64x pack builds a 704 MiB atlas for 452 MiB of textures); sign-heavy scenes ([#1461](https://github.com/ludovic111/horizon/issues/1461)). Profile first, keep what pays, show before and after numbers. +Block entities and hoppers that skip work when idle (the hopper item scan is already skipped when no item is near); a particle frustum test first (also a parity gap), then particle quads built on the GPU; jigsaw shortcuts that skip blocked connectors and pool elements known not to fit, with layouts unchanged (trial chambers and ancient cities first); batched raw mouse input on Windows for 8000 Hz mice; a better atlas packer for huge resource packs (a 64x pack builds a 704 MiB atlas for 452 MiB of textures); sign-heavy scenes ([#1461](https://github.com/horizon-rust/horizon/issues/1461)). Profile first, keep what pays, show before and after numbers. More: [docs/profiling.md](docs/profiling.md) @@ -364,7 +364,7 @@ Making mods that add machines, magic and mobs work in Horizon, in steps, startin
Technical -333 of the 496 mods in a big pack (ATM10) contain code. Issue [#1854](https://github.com/ludovic111/horizon/issues/1854) ranks the API gaps (ticking block entities, networking, rendering, menus, inventories) that unlock them in tiers, with machines first as the recommended path and a furnace ported tick for tick as proof. The first API step is a draft ([#1189](https://github.com/ludovic111/horizon/issues/1189), see 'Machines and blocks with inventories'). The path isn't started yet ([docs/modpacks.md](docs/modpacks.md)). +333 of the 496 mods in a big pack (ATM10) contain code. Issue [#1854](https://github.com/horizon-rust/horizon/issues/1854) ranks the API gaps (ticking block entities, networking, rendering, menus, inventories) that unlock them in tiers, with machines first as the recommended path and a furnace ported tick for tick as proof. The first API step is a draft ([#1189](https://github.com/horizon-rust/horizon/issues/1189), see 'Machines and blocks with inventories'). The path isn't started yet ([docs/modpacks.md](docs/modpacks.md)).
@@ -386,7 +386,7 @@ Set up Horizon, a server first, without Java on your computer: published tables
Technical -Today `horizon-prepare` runs Mojang's exporters with Java. Issue [#1750](https://github.com/ludovic111/horizon/issues/1750) proposes publishing the computed version tables once from CI and assembling the rest locally from the player's own jar and assets, provided the tables hold no Mojang content; a contributor offered a pull request, and it would help phones too. A server-only prepare from `server.jar` alone is the first step ([docs/server.md](docs/server.md)). +Today `horizon-prepare` runs Mojang's exporters with Java. Issue [#1750](https://github.com/horizon-rust/horizon/issues/1750) proposes publishing the computed version tables once from CI and assembling the rest locally from the player's own jar and assets, provided the tables hold no Mojang content; a contributor offered a pull request, and it would help phones too. A server-only prepare from `server.jar` alone is the first step ([docs/server.md](docs/server.md)).
@@ -406,7 +406,7 @@ Smoother hosting: a real Windows service, a backup before every update, backups
Technical -A Windows service wrapper instead of the logon scheduled task; `backups.before_update`; hot reload of config for view distance and the message of the day (needs engine support); backups that keep world and player state ([#1808](https://github.com/ludovic111/horizon/issues/1808), a contributor's draft, in review). [docs/hosting.md](docs/hosting.md), docs/server.md. +A Windows service wrapper instead of the logon scheduled task; `backups.before_update`; hot reload of config for view distance and the message of the day (needs engine support); backups that keep world and player state ([#1808](https://github.com/horizon-rust/horizon/issues/1808), a contributor's draft, in review). [docs/hosting.md](docs/hosting.md), docs/server.md.
@@ -464,7 +464,7 @@ Mods that add machines: blocks that tick, hold items and have their own menus. T
Technical -Block entities and menus: ticking machines with slots, server menu logic and the menu protocol to clients, energy, item and fluid transfer, data attachments, accessory slots and custom recipe types, with a typed client and server channel and typed config beside them. A draft ([#1189](https://github.com/ludovic111/horizon/issues/1189)) proves a furnace ported tick for tick and holds the ATM10 code-mods plan; the design is redone through the API policy before it merges ([docs/modpacks.md](docs/modpacks.md), docs/api/stability.md). +Block entities and menus: ticking machines with slots, server menu logic and the menu protocol to clients, energy, item and fluid transfer, data attachments, accessory slots and custom recipe types, with a typed client and server channel and typed config beside them. A draft ([#1189](https://github.com/horizon-rust/horizon/issues/1189)) proves a furnace ported tick for tick and holds the ATM10 code-mods plan; the design is redone through the API policy before it merges ([docs/modpacks.md](docs/modpacks.md), docs/api/stability.md).
@@ -486,7 +486,7 @@ Pistons and slime blocks will push players, mobs and items as in vanilla. Today
Technical -Port `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` (honey), the slime bounce and `Entity.limitPistonMovement` for `MoverType.PISTON`, in single player and for a server's players. Issues [#1496](https://github.com/ludovic111/horizon/issues/1496), [#1609](https://github.com/ludovic111/horizon/issues/1609), [#1608](https://github.com/ludovic111/horizon/issues/1608), [#1704](https://github.com/ludovic111/horizon/issues/1704), [#1758](https://github.com/ludovic111/horizon/issues/1758). +Port `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` (honey), the slime bounce and `Entity.limitPistonMovement` for `MoverType.PISTON`, in single player and for a server's players. Issues [#1496](https://github.com/horizon-rust/horizon/issues/1496), [#1609](https://github.com/horizon-rust/horizon/issues/1609), [#1608](https://github.com/horizon-rust/horizon/issues/1608), [#1704](https://github.com/horizon-rust/horizon/issues/1704), [#1758](https://github.com/horizon-rust/horizon/issues/1758).
@@ -506,7 +506,7 @@ Villages and fights behaving as in vanilla: iron golems defending villages, vill
Technical -Villages: iron golem village goals, villager memories across saves, villager age, job-site claiming on dedicated servers, flower offers ([#1639](https://github.com/ludovic111/horizon/issues/1639) is one report). Combat: the mobs' `attack_knockback` attribute, mace smash logic, the hit knockback source on the host, the fire burnout biome tag. Each is checked against vanilla by a harness ([docs/rust-parity.md](docs/rust-parity.md)). +Villages: iron golem village goals, villager memories across saves, villager age, job-site claiming on dedicated servers, flower offers ([#1639](https://github.com/horizon-rust/horizon/issues/1639) is one report). Combat: the mobs' `attack_knockback` attribute, mace smash logic, the hit knockback source on the host, the fire burnout biome tag. Each is checked against vanilla by a harness ([docs/rust-parity.md](docs/rust-parity.md)).
@@ -516,7 +516,7 @@ Pick the speakers or headphones Horizon plays through, in Music & Sounds.
Technical -An output device list in Music & Sounds, falling back to the system default. [#1035](https://github.com/ludovic111/horizon/issues/1035) started it: a player on an older Windows computer had no sound at all, and a device choice is how such cases are found and fixed. +An output device list in Music & Sounds, falling back to the system default. [#1035](https://github.com/horizon-rust/horizon/issues/1035) started it: a player on an older Windows computer had no sound at all, and a device choice is how such cases are found and fixed.
@@ -544,7 +544,7 @@ Coming soon: sign in with your Microsoft account to play on online-mode servers. Device-code sign-in in the launcher and online-mode login in the client ([docs/microsoft-account.md](docs/microsoft-account.md)). It is turned on by setting the app's client id once Minecraft API access is approved; until then the launcher shows "Coming soon". -More: [#1270](https://github.com/ludovic111/horizon/issues/1270) +More: [#1270](https://github.com/horizon-rust/horizon/issues/1270)
@@ -566,7 +566,7 @@ Builds of the game and the launcher for Macs with an Intel processor.
Technical -x86_64 game and launcher builds, picked per processor ([#1171](https://github.com/ludovic111/horizon/issues/1171)). Before it ships it needs a run on a real Intel Mac: Rosetta on Apple Silicon only proves the CPU code. Requests: [#1161](https://github.com/ludovic111/horizon/issues/1161), [#1792](https://github.com/ludovic111/horizon/issues/1792). +x86_64 game and launcher builds, picked per processor ([#1171](https://github.com/horizon-rust/horizon/issues/1171)). Before it ships it needs a run on a real Intel Mac: Rosetta on Apple Silicon only proves the CPU code. Requests: [#1161](https://github.com/horizon-rust/horizon/issues/1161), [#1792](https://github.com/horizon-rust/horizon/issues/1792).
@@ -576,7 +576,7 @@ Fixes for Linux desktops that use Wayland and Hyprland: fullscreen, the clipboar
Technical -Open: the GUI Scale is clamped to 2 after a restart under Hyprland, while XWayland keeps it ([#1866](https://github.com/ludovic111/horizon/issues/1866)). Earlier reports covered fullscreen dropping on menu clicks, the clipboard and a white overlay ([#1007](https://github.com/ludovic111/horizon/issues/1007), closed). Checked on a real Wayland session. +Open: the GUI Scale is clamped to 2 after a restart under Hyprland, while XWayland keeps it ([#1866](https://github.com/horizon-rust/horizon/issues/1866)). Earlier reports covered fullscreen dropping on menu clicks, the clipboard and a white overlay ([#1007](https://github.com/horizon-rust/horizon/issues/1007), closed). Checked on a real Wayland session.
@@ -626,7 +626,7 @@ Safer releases: changes to the release machinery need the owner's review, and AI
Technical -`.github/CODEOWNERS` lists the workflows, the release and signing tools, the update-checking code and the installers ([#1015](https://github.com/ludovic111/horizon/issues/1015)); the branch protection that makes it count waits for the `horizon-agent` GitHub App, which reads and writes code, pull requests and issues but can't change settings, workflows, secrets or members, and whose tokens last an hour. It needs the owner to create the App and switch the protection on ([docs/security.md](docs/security.md)). +`.github/CODEOWNERS` lists the workflows, the release and signing tools, the update-checking code and the installers ([#1015](https://github.com/horizon-rust/horizon/issues/1015)); the branch protection that makes it count waits for the `horizon-agent` GitHub App, which reads and writes code, pull requests and issues but can't change settings, workflows, secrets or members, and whose tokens last an hour. It needs the owner to create the App and switch the protection on ([docs/security.md](docs/security.md)).
@@ -636,7 +636,7 @@ Every download Horizon makes is checked against the project's signature, includi
Technical -Releases carry signed checksums, and the launcher and `horizon-server update` refuse anything unsigned ([#1011](https://github.com/ludovic111/horizon/issues/1011), [#1014](https://github.com/ludovic111/horizon/issues/1014)). Left: the first install through `install.sh` and `install.ps1` still trusts only the checksum GitHub publishes, because verifying Ed25519 signatures needs OpenSSL 3, which macOS doesn't ship ([docs/security.md](docs/security.md)). +Releases carry signed checksums, and the launcher and `horizon-server update` refuse anything unsigned ([#1011](https://github.com/horizon-rust/horizon/issues/1011), [#1014](https://github.com/horizon-rust/horizon/issues/1014)). Left: the first install through `install.sh` and `install.ps1` still trusts only the checksum GitHub publishes, because verifying Ed25519 signatures needs OpenSSL 3, which macOS doesn't ship ([docs/security.md](docs/security.md)).
@@ -650,7 +650,7 @@ Far terrain drawn from the world you really built and explored, caves and builds
Technical -Keep a 3D mip store on disk built from real chunks, drawn by the GPU beside the seed preview for areas nobody has visited. Written from scratch and measured before it is kept. Builds on Far Detail and the far-terrain levels of detail already shipped; the open work on them is [#718](https://github.com/ludovic111/horizon/issues/718). +Keep a 3D mip store on disk built from real chunks, drawn by the GPU beside the seed preview for areas nobody has visited. Written from scratch and measured before it is kept. Builds on Far Detail and the far-terrain levels of detail already shipped; the open work on them is [#718](https://github.com/horizon-rust/horizon/issues/718).
@@ -692,7 +692,7 @@ Run Java mods that nobody has rewritten for Horizon yet, through a bridge or a c
Technical -Earlier research ([#527](https://github.com/ludovic111/horizon/issues/527), closed) found that Java mods can't simply run, because they call Minecraft's own classes. Options to look at again: a jar-to-WebAssembly backend, or a bridge for simple Fabric mods. Whatever is chosen has to run inside the same sandbox and capability checks as native mods. +Earlier research ([#527](https://github.com/horizon-rust/horizon/issues/527), closed) found that Java mods can't simply run, because they call Minecraft's own classes. Options to look at again: a jar-to-WebAssembly backend, or a bridge for simple Fabric mods. Whatever is chosen has to run inside the same sandbox and capability checks as native mods.
@@ -704,7 +704,7 @@ Sign in with other account providers, such as Ely.by or any Yggdrasil-compatible
Technical -Issue [#1270](https://github.com/ludovic111/horizon/issues/1270) asks for Ely.by and Yggdrasil-compatible servers with an account selector in the launcher. It builds on the Microsoft sign-in ([docs/microsoft-account.md](docs/microsoft-account.md)). +Issue [#1270](https://github.com/horizon-rust/horizon/issues/1270) asks for Ely.by and Yggdrasil-compatible servers with an account selector in the launcher. It builds on the Microsoft sign-in ([docs/microsoft-account.md](docs/microsoft-account.md)).
@@ -748,7 +748,7 @@ Contraptions and physics like the Create and Aeronautics mods, as a mod for Hori
Technical -Issue [#805](https://github.com/ludovic111/horizon/issues/805) (porting QOL mods) closed with this answer: it would come as a native Horizon mod on the mod API. It needs server mods, entities and rendering first. +Issue [#805](https://github.com/horizon-rust/horizon/issues/805) (porting QOL mods) closed with this answer: it would come as a native Horizon mod on the mod API. It needs server mods, entities and rendering first.
@@ -790,7 +790,7 @@ Vanilla's complete F3 screen: debug options, a profiler chart, ten-second captur
Technical -Today F3 shows position, chunk, light, biome and FPS ([docs/native-client.md](docs/native-client.md)). Vanilla also has F3+F6 debug options with profiles, F3+1 the profiler pie, F3+L a ten-second capture and F3+S the atlas dump ([#562](https://github.com/ludovic111/horizon/issues/562) asked for the F3 editor). +Today F3 shows position, chunk, light, biome and FPS ([docs/native-client.md](docs/native-client.md)). Vanilla also has F3+F6 debug options with profiles, F3+1 the profiler pie, F3+L a ten-second capture and F3+S the atlas dump ([#562](https://github.com/horizon-rust/horizon/issues/562) asked for the F3 editor).
@@ -814,7 +814,7 @@ An optional ray-tracing mode for graphics cards that support it (RTX and recent
Technical -A spike with ray-traced sun shadows, off by default, is a draft ([#1180](https://github.com/ludovic111/horizon/issues/1180)). Reflections, global illumination, Apple M3 and newer if it is cheap, and a performance report per card come after. +A spike with ray-traced sun shadows, off by default, is a draft ([#1180](https://github.com/horizon-rust/horizon/issues/1180)). Reflections, global illumination, Apple M3 and newer if it is cheap, and a performance report per card come after.
@@ -824,7 +824,7 @@ Output for HDR monitors: brighter highlights and richer colour where your screen
Technical -Issue [#1441](https://github.com/ludovic111/horizon/issues/1441). Needs a surface format and a tone-mapping path per backend, and tests on real HDR screens on Windows, macOS and Linux. +Issue [#1441](https://github.com/horizon-rust/horizon/issues/1441). Needs a surface format and a tone-mapping path per backend, and tests on real HDR screens on Windows, macOS and Linux.
@@ -858,7 +858,7 @@ Game and launcher builds for 64-bit ARM Linux computers.
Technical -Issue [#1709](https://github.com/ludovic111/horizon/issues/1709): aarch64 builds of the game and the launcher in the release workflow, tested on a real ARM machine with its Vulkan driver. The server build already drops audio and controllers (`--no-default-features`). +Issue [#1709](https://github.com/horizon-rust/horizon/issues/1709): aarch64 builds of the game and the launcher in the release workflow, tested on a real ARM machine with its Vulkan driver. The server build already drops audio and controllers (`--no-default-features`).
@@ -868,7 +868,7 @@ Versions of Horizon for Android, iOS and web browsers. Nothing official yet; con
Technical -No official build. Android was first closed as not planned, with touch controls, a mobile interface, packaging and loading the player's own assets all missing; the roadmap now includes it, iOS and a WebAssembly build for the browser as long-term goals. First pieces from contributors: `horizon-dualsense` compiling on iOS ([#1813](https://github.com/ludovic111/horizon/issues/1813)) and helper-thread limits on Android ([#1751](https://github.com/ludovic111/horizon/issues/1751)). Preparing without Java ([#1750](https://github.com/ludovic111/horizon/issues/1750)) matters here too. Horizon ships none of Mojang's files on any platform. +No official build. Android was first closed as not planned, with touch controls, a mobile interface, packaging and loading the player's own assets all missing; the roadmap now includes it, iOS and a WebAssembly build for the browser as long-term goals. First pieces from contributors: `horizon-dualsense` compiling on iOS ([#1813](https://github.com/horizon-rust/horizon/issues/1813)) and helper-thread limits on Android ([#1751](https://github.com/horizon-rust/horizon/issues/1751)). Preparing without Java ([#1750](https://github.com/horizon-rust/horizon/issues/1750)) matters here too. Horizon ships none of Mojang's files on any platform.
@@ -912,7 +912,7 @@ An optional AI teammate you can talk to by voice. It plays beside you, helps or
Technical -Draft pull requests: the companion ([#1068](https://github.com/ludovic111/horizon/issues/1068)), its safety modes and their evaluation ([#1069](https://github.com/ludovic111/horizon/issues/1069)) and a route that finishes the game ([#1070](https://github.com/ludovic111/horizon/issues/1070)). In the drafts: a companion that follows, fights, mines, crafts, sleeps and respawns; chat and push-to-talk voice, with speech recognition and a choice of voices; presets (very strong, helper, beat the game); a guard model with Clean, Kid and Salty modes; perception levels from Fair to All-knowing; hardware detection with a simple mode and an Advanced tab; local models first, cloud keys optional. The No AI switch is already in the game. Left: the speedrun route doesn't finish the game reliably yet, voices for more languages, and the safety evaluation, which must pass before it ships. +Draft pull requests: the companion ([#1068](https://github.com/horizon-rust/horizon/issues/1068)), its safety modes and their evaluation ([#1069](https://github.com/horizon-rust/horizon/issues/1069)) and a route that finishes the game ([#1070](https://github.com/horizon-rust/horizon/issues/1070)). In the drafts: a companion that follows, fights, mines, crafts, sleeps and respawns; chat and push-to-talk voice, with speech recognition and a choice of voices; presets (very strong, helper, beat the game); a guard model with Clean, Kid and Salty modes; perception levels from Fair to All-knowing; hardware detection with a simple mode and an Advanced tab; local models first, cloud keys optional. The No AI switch is already in the game. Left: the speedrun route doesn't finish the game reliably yet, voices for more languages, and the safety evaluation, which must pass before it ships.
@@ -938,7 +938,7 @@ Run Horizon's built-in benchmark and share the report: every new computer makes
Technical -`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/ludovic111/horizon/issues/1711). +`horizon-launcher play --arg=--benchmark --arg=standard` writes a JSON report; `horizon-launcher data benchmark ` shows what would be sent and uploads it (playhorizon.dev/docs/performance). Results from three installs with the same hardware appear on the Benchmarks page. Example: [#1711](https://github.com/horizon-rust/horizon/issues/1711). More: [https://playhorizon.dev/docs/performance](https://playhorizon.dev/docs/performance) @@ -952,7 +952,7 @@ Banners in End cities show as plain magenta instead of with their pattern.
Technical -Compare the banner block entities the End city templates place with vanilla's (`EndCityPieces`, the templates' block entity NBT, `BannerBlockEntity`'s patterns), in `crates/horizon-world/src/worldgen/structure/`. Issue [#1438](https://github.com/ludovic111/horizon/issues/1438); possibly related: [#526](https://github.com/ludovic111/horizon/issues/526). +Compare the banner block entities the End city templates place with vanilla's (`EndCityPieces`, the templates' block entity NBT, `BannerBlockEntity`'s patterns), in `crates/horizon-world/src/worldgen/structure/`. Issue [#1438](https://github.com/horizon-rust/horizon/issues/1438); possibly related: [#526](https://github.com/horizon-rust/horizon/issues/526).
@@ -962,19 +962,19 @@ Armour and tools in End city chests should come enchanted, as in vanilla.
Technical -`loot.rs` implements `enchant_with_levels`: find why the End city chest table's rolls come out bare, and compare them with vanilla's for a few seeds. Issues [#1437](https://github.com/ludovic111/horizon/issues/1437), [#1660](https://github.com/ludovic111/horizon/issues/1660). +`loot.rs` implements `enchant_with_levels`: find why the End city chest table's rolls come out bare, and compare them with vanilla's for a few seeds. Issues [#1437](https://github.com/horizon-rust/horizon/issues/1437), [#1660](https://github.com/horizon-rust/horizon/issues/1660).
## Recently shipped -- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936) -- **Server resource packs** (v0.2.48): Servers can send you their resource pack: Horizon asks, downloads it and applies it, like vanilla. [#1562](https://github.com/ludovic111/horizon/issues/1562) · [#1569](https://github.com/ludovic111/horizon/issues/1569) · [#1570](https://github.com/ludovic111/horizon/issues/1570) -- **Single player on its own server thread** (v0.2.39): Single player runs on a server thread, as vanilla does, so the world keeps ticking smoothly while the window draws. [#1514](https://github.com/ludovic111/horizon/issues/1514) · [docs/server-levels.md](docs/server-levels.md) -- **GPU occlusion culling on Macs** (v0.2.17): On Macs the GPU now skips terrain hidden behind hills and caves: 8 to 48% more frames per second at 32 chunks on an M4 Pro. [#1434](https://github.com/ludovic111/horizon/issues/1434) -- **Animated textures on the GPU** (v0.2.5): Water, lava and other animated blocks are now animated by the graphics card: 1.7 to 2.4 times better 1% lows on Intel graphics. [#1239](https://github.com/ludovic111/horizon/issues/1239) -- **Far Detail for integrated graphics** (v0.2.5): An optional Reduced setting for far terrain, suggested on integrated graphics, that saves 2 to 4 ms of GPU time per frame. [#1199](https://github.com/ludovic111/horizon/issues/1199) · [#1029](https://github.com/ludovic111/horizon/issues/1029) -- **The launcher's mod browser** (launcher@0.2.0): Search Modrinth for mods, modpacks and resource packs from the launcher; it says before installing what works in Horizon. [#1154](https://github.com/ludovic111/horizon/issues/1154) · [#1242](https://github.com/ludovic111/horizon/issues/1242) · [#1243](https://github.com/ludovic111/horizon/issues/1243) · [#1246](https://github.com/ludovic111/horizon/issues/1246) · [docs/mod-browser.md](docs/mod-browser.md) -- **A blocky, Minecraft-like launcher** (launcher@0.2.0): The launcher got a new blocky look in Horizon's purple, in dark and light. [#1269](https://github.com/ludovic111/horizon/issues/1269) · [docs/design-system.md](docs/design-system.md) -- **Dynamic lights** (v2026.10.22): An optional extra: torches you hold, drop or set on fire light up what is around them. [#1162](https://github.com/ludovic111/horizon/issues/1162) -- **Host a server from the launcher** (launcher-v0.15.0): The launcher's Servers page creates, starts, backs up and updates a Horizon server with buttons, and invites friends. [#1026](https://github.com/ludovic111/horizon/issues/1026) · [docs/hosting.md](docs/hosting.md) +- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/horizon-rust/horizon/issues/1917) · [#1920](https://github.com/horizon-rust/horizon/issues/1920) · [#1936](https://github.com/horizon-rust/horizon/issues/1936) +- **Server resource packs** (v0.2.48): Servers can send you their resource pack: Horizon asks, downloads it and applies it, like vanilla. [#1562](https://github.com/horizon-rust/horizon/issues/1562) · [#1569](https://github.com/horizon-rust/horizon/issues/1569) · [#1570](https://github.com/horizon-rust/horizon/issues/1570) +- **Single player on its own server thread** (v0.2.39): Single player runs on a server thread, as vanilla does, so the world keeps ticking smoothly while the window draws. [#1514](https://github.com/horizon-rust/horizon/issues/1514) · [docs/server-levels.md](docs/server-levels.md) +- **GPU occlusion culling on Macs** (v0.2.17): On Macs the GPU now skips terrain hidden behind hills and caves: 8 to 48% more frames per second at 32 chunks on an M4 Pro. [#1434](https://github.com/horizon-rust/horizon/issues/1434) +- **Animated textures on the GPU** (v0.2.5): Water, lava and other animated blocks are now animated by the graphics card: 1.7 to 2.4 times better 1% lows on Intel graphics. [#1239](https://github.com/horizon-rust/horizon/issues/1239) +- **Far Detail for integrated graphics** (v0.2.5): An optional Reduced setting for far terrain, suggested on integrated graphics, that saves 2 to 4 ms of GPU time per frame. [#1199](https://github.com/horizon-rust/horizon/issues/1199) · [#1029](https://github.com/horizon-rust/horizon/issues/1029) +- **The launcher's mod browser** (launcher@0.2.0): Search Modrinth for mods, modpacks and resource packs from the launcher; it says before installing what works in Horizon. [#1154](https://github.com/horizon-rust/horizon/issues/1154) · [#1242](https://github.com/horizon-rust/horizon/issues/1242) · [#1243](https://github.com/horizon-rust/horizon/issues/1243) · [#1246](https://github.com/horizon-rust/horizon/issues/1246) · [docs/mod-browser.md](docs/mod-browser.md) +- **A blocky, Minecraft-like launcher** (launcher@0.2.0): The launcher got a new blocky look in Horizon's purple, in dark and light. [#1269](https://github.com/horizon-rust/horizon/issues/1269) · [docs/design-system.md](docs/design-system.md) +- **Dynamic lights** (v2026.10.22): An optional extra: torches you hold, drop or set on fire light up what is around them. [#1162](https://github.com/horizon-rust/horizon/issues/1162) +- **Host a server from the launcher** (launcher-v0.15.0): The launcher's Servers page creates, starts, backs up and updates a Horizon server with buttons, and invites friends. [#1026](https://github.com/horizon-rust/horizon/issues/1026) · [docs/hosting.md](docs/hosting.md) diff --git a/benchmarks/server-equal-mixed-2026-10-18/README.md b/benchmarks/server-equal-mixed-2026-10-18/README.md index 5849e72ba..695f08c81 100644 --- a/benchmarks/server-equal-mixed-2026-10-18/README.md +++ b/benchmarks/server-equal-mixed-2026-10-18/README.md @@ -119,7 +119,7 @@ machines during the runs. ## Reproduce - curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + curl -fsSL https://raw.githubusercontent.com/horizon-rust/horizon/main/packaging/server/install.sh | sh horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy cargo build --release -p horizon-bots # on the machine that runs the bots # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): diff --git a/benchmarks/server-four-way-2026-10-19/README.md b/benchmarks/server-four-way-2026-10-19/README.md index 7048c2743..1c8b7b07e 100644 --- a/benchmarks/server-four-way-2026-10-19/README.md +++ b/benchmarks/server-four-way-2026-10-19/README.md @@ -148,7 +148,7 @@ early, wrote no report. Its lines come from its output. ## Reproduce - curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + curl -fsSL https://raw.githubusercontent.com/horizon-rust/horizon/main/packaging/server/install.sh | sh horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy cargo build --release -p horizon-bots # on the machine that runs the bots # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): diff --git a/benchmarks/server-mixed-2026-10-18/README.md b/benchmarks/server-mixed-2026-10-18/README.md index 3cbe3897f..a55f5999d 100644 --- a/benchmarks/server-mixed-2026-10-18/README.md +++ b/benchmarks/server-mixed-2026-10-18/README.md @@ -103,7 +103,7 @@ the Nix store, so the run set `LD_LIBRARY_PATH` to them (see #898). ## Reproduce - curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + curl -fsSL https://raw.githubusercontent.com/horizon-rust/horizon/main/packaging/server/install.sh | sh horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy cargo build --release -p horizon-bots # on the machine that runs the bots # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): diff --git a/crates/cargo-horizon-mod/src/main.rs b/crates/cargo-horizon-mod/src/main.rs index b82c6d07f..95d0a9eb3 100644 --- a/crates/cargo-horizon-mod/src/main.rs +++ b/crates/cargo-horizon-mod/src/main.rs @@ -25,7 +25,7 @@ use std::{ }; const TARGET: &str = "wasm32-unknown-unknown"; -const SDK_GIT: &str = "{ git = \"https://github.com/ludovic111/horizon\" }"; +const SDK_GIT: &str = "{ git = \"https://github.com/horizon-rust/horizon\" }"; fn main() -> ExitCode { // Cargo runs `cargo-horizon-mod horizon-mod `. diff --git a/crates/cargo-horizon-mod/src/registry.rs b/crates/cargo-horizon-mod/src/registry.rs index ac5e77ea4..4e78daf26 100644 --- a/crates/cargo-horizon-mod/src/registry.rs +++ b/crates/cargo-horizon-mod/src/registry.rs @@ -1,5 +1,5 @@ //! `cargo horizon-mod registry build|review|check|list`: the registry repository's CI -//! (`ludovic111/horizon-mods`, docs/api/mod-index.md). Network-free: the +//! (`horizon-rust/horizon-mods`, docs/api/mod-index.md). Network-free: the //! workflow downloads the files and publishes what this writes. use horizon_mods::index::{ FILE_HOST, @@ -8,7 +8,7 @@ use horizon_mods::index::{ use std::path::Path; /// Where the registry's site is published (its icons). -const SITE: &str = "https://ludovic111.github.io/horizon-mods/"; +const SITE: &str = "https://horizon-rust.github.io/horizon-mods/"; const USAGE: &str = "usage: cargo horizon-mod registry build --files --out [--release ] [--site ] [--generated