From 5903b5981df38d7c4834634664082d4f9647e8ca Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Tue, 13 Oct 2026 22:41:21 -0400 Subject: [PATCH 01/23] Fix item-use feedback, ranged poses, arrows and elytra rendering --- crates/horizon-client/src/first_person.rs | 240 ++++++++++++++++++ crates/horizon-client/src/game.rs | 239 ++++++++++------- .../horizon-client/src/game/armor_stands.rs | 5 +- crates/horizon-client/src/game/books.rs | 1 + crates/horizon-client/src/game/creatures.rs | 67 ++--- crates/horizon-client/src/game/crossbow.rs | 4 +- crates/horizon-client/src/game/dispenser.rs | 50 +--- crates/horizon-client/src/game/fireworks.rs | 1 + crates/horizon-client/src/game/item_draw.rs | 2 +- crates/horizon-client/src/game/perspective.rs | 69 +++++ crates/horizon-client/src/items.rs | 90 +++++++ crates/horizon-client/src/mobs.rs | 63 +++++ crates/horizon-client/src/mobs/anim.rs | 85 ++++++- crates/horizon-client/src/mobs/render.rs | 22 ++ crates/horizon-client/src/projectiles.rs | 85 +++++++ crates/horizon-client/src/sprites.rs | 46 +++- tests/test_item_action_animation.py | 93 +++++++ 17 files changed, 973 insertions(+), 189 deletions(-) create mode 100644 tests/test_item_action_animation.py diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 757a93873..d07e2e23a 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -8,6 +8,125 @@ //! //! What those read and do in the world is behind [`HandWorld`]. +/// The ranged item state read by the first-person hand renderer. +#[derive(Clone, Copy, Debug)] +pub enum ItemPose { + Swing, + Using, + Eat { + remaining: f32, + duration: f32, + partial: f32, + }, + Trident { + ticks_used: f32, + }, + Bow { + ticks_used: f32, + }, + Crossbow { + ticks_used: Option, + charge_duration: f32, + charged: bool, + }, +} + +/// `submitArmWithItem`: the main-hand item pose, before the model transform. +pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) -> glam::Mat4 { + use glam::{Mat4, Vec3}; + use horizon_core::geometry::trig::Mth; + let invert = if left { -1.0 } else { 1.0 }; + let pi = std::f32::consts::PI; + let mut m = Mat4::from_translation(Vec3::new( + invert * 0.56, + -0.52 - inverse_height * 0.6, + -0.72, + )); + if let ItemPose::Eat { + remaining, + duration, + partial, + } = pose + { + let time = remaining - partial + 1.0; + let fraction = time / duration; + let mut eat = Mat4::IDENTITY; + if fraction < 0.8 { + eat *= + Mat4::from_translation(Vec3::new(0.0, ((time / 4.0 * pi).mcos() * 0.1).abs(), 0.0)); + } + let jiggle = 1.0 - horizon_core::jmath::pow(f64::from(fraction), 27.0) as f32; + eat *= Mat4::from_translation(Vec3::new(jiggle * 0.6 * invert, jiggle * -0.5, 0.0)); + eat *= Mat4::from_rotation_y((invert * jiggle * 90.0).to_radians()); + eat *= Mat4::from_rotation_x((jiggle * 10.0).to_radians()); + eat *= Mat4::from_rotation_z((invert * jiggle * 30.0).to_radians()); + return eat * m; + } + if matches!(pose, ItemPose::Using) { + return m; + } + let charging = match pose { + ItemPose::Bow { ticks_used } => { + let power = ticks_used / 20.0; + Some(( + ticks_used, + ((power * power + power * 2.0) / 3.0).min(1.0), + false, + )) + } + ItemPose::Crossbow { + ticks_used: Some(ticks), + charge_duration, + charged: false, + } => Some((ticks, (ticks / charge_duration).min(1.0), true)), + ItemPose::Trident { ticks_used } => Some((ticks_used, (ticks_used / 10.0).min(1.0), false)), + _ => None, + }; + if let Some((ticks, power, crossbow)) = charging { + let trident = matches!(pose, ItemPose::Trident { .. }); + let (x, y, z, pitch, yaw) = if trident { + (-0.5, 0.7, 0.1, -55.0f32, 35.3f32) + } else if crossbow { + (-0.4785682, -0.094387, 0.05731531, -11.935f32, 65.3f32) + } else { + (-0.2785682, 0.18344387, 0.15731531, -13.935f32, 35.3f32) + }; + m *= Mat4::from_translation(Vec3::new(invert * x, y, z)); + m *= Mat4::from_rotation_x(pitch.to_radians()); + m *= Mat4::from_rotation_y((invert * yaw).to_radians()); + m *= Mat4::from_rotation_z((invert * -9.785f32).to_radians()); + if power > 0.1 { + let shake = ((ticks - 0.1) * 1.3).msin() * (power - 0.1); + m *= Mat4::from_translation(Vec3::new(0.0, shake * 0.004, 0.0)); + } + m *= Mat4::from_translation(Vec3::new( + 0.0, + 0.0, + power * if trident { 0.2 } else { 0.04 }, + )); + m *= Mat4::from_scale(Vec3::new(1.0, 1.0, 1.0 + power * 0.2)); + m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians()); + } else { + let root = attack.sqrt(); + m *= Mat4::from_translation(Vec3::new( + invert * -0.4 * (root * pi).msin(), + 0.2 * (root * std::f32::consts::TAU).msin(), + -0.2 * (attack * pi).msin(), + )); + m *= Mat4::from_rotation_y( + (invert * (45.0 - (attack * attack * pi).msin() * 20.0)).to_radians(), + ); + m *= Mat4::from_rotation_z((invert * (root * pi).msin() * -20.0).to_radians()); + m *= Mat4::from_rotation_x(((root * pi).msin() * -80.0).to_radians()); + m *= Mat4::from_rotation_y((invert * -45.0f32).to_radians()); + if matches!(pose, ItemPose::Crossbow { charged: true, .. }) && attack < 0.001 { + m *= Mat4::from_translation(Vec3::new(invert * -0.641864, 0.0, 0.0)); + m *= Mat4::from_rotation_y((invert * 10.0f32).to_radians()); + } + } + m +} + /// `InteractionHand`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Hand { @@ -599,3 +718,124 @@ mod tests { assert_eq!(swing_duration(d, None, Some(2)), 12); } } + +#[cfg(test)] +mod item_pose_tests { + use super::*; + #[test] + fn ranged_draw_uses_native_charge_curves_and_caps() { + for (ticks, stretch) in [ + (0.0, 1.0), + (10.0, 1.0 + 0.2 * 1.25 / 3.0), + (20.0, 1.2), + (40.0, 1.2), + ] { + let m = item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: ticks }); + assert!((m.determinant() - stretch).abs() < 0.000001); + } + for duration in [25.0, 20.0, 15.0, 10.0] { + let m = item_pose( + false, + 0.0, + 0.0, + ItemPose::Crossbow { + ticks_used: Some(duration), + charge_duration: duration, + charged: false, + }, + ); + assert!((m.determinant() - 1.2).abs() < 0.000001); + } + } + #[test] + fn left_handed_ranged_poses_mirror_the_right_hand() { + let reflect = glam::Mat4::from_scale(glam::Vec3::new(-1.0, 1.0, 1.0)); + for pose in [ + ItemPose::Swing, + ItemPose::Bow { ticks_used: 10.0 }, + ItemPose::Crossbow { + ticks_used: Some(10.0), + charge_duration: 25.0, + charged: false, + }, + ItemPose::Crossbow { + ticks_used: None, + charge_duration: 25.0, + charged: true, + }, + ] { + let left = item_pose(true, 0.2, 0.0, pose).to_cols_array(); + let right = (reflect * item_pose(false, 0.2, 0.0, pose) * reflect).to_cols_array(); + for (a, b) in left.into_iter().zip(right) { + assert!((a - b).abs() < 0.000001); + } + } + } + + #[test] + fn drawing_bow_has_its_own_pose() { + assert_ne!( + item_pose(false, 0.0, 0.0, ItemPose::Bow { ticks_used: 10.0 }), + item_pose(false, 0.0, 0.0, ItemPose::Swing) + ); + } + #[test] + fn charging_crossbow_has_its_own_pose() { + assert_ne!( + item_pose( + false, + 0.0, + 0.0, + ItemPose::Crossbow { + ticks_used: Some(10.0), + charge_duration: 25.0, + charged: false + } + ), + item_pose(false, 0.0, 0.0, ItemPose::Swing) + ); + } + #[test] + fn charged_crossbow_is_aimed_while_idle() { + assert_ne!( + item_pose( + false, + 0.0, + 0.0, + ItemPose::Crossbow { + ticks_used: None, + charge_duration: 25.0, + charged: true + } + ), + item_pose(false, 0.0, 0.0, ItemPose::Swing) + ); + } +} + +#[cfg(test)] +mod continuous_use_tests { + use super::*; + #[test] + fn eating_and_throwing_have_use_poses_not_attack_poses() { + let swing = item_pose(false, 0.0, 0.3, ItemPose::Swing); + assert_ne!( + swing, + item_pose( + false, + 0.0, + 0.3, + ItemPose::Eat { + remaining: 10.0, + duration: 32.0, + partial: 0.5 + } + ) + ); + assert_ne!( + swing, + item_pose(false, 0.0, 0.3, ItemPose::Trident { ticks_used: 5.0 }) + ); + assert_ne!(swing, item_pose(false, 0.0, 0.3, ItemPose::Using)); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..590ff07c0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -792,6 +792,7 @@ struct Game<'a> { rockets: Vec, creaking: creaking::CreakingState, trident_model: Option, + arrow_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, creative_screen: Creative, @@ -1225,6 +1226,7 @@ impl Game<'_> { self.inventory[self.selected] = None; } self.player_drop(thrown); + self.swing_arm(); } /// `Player.drop`: the statistics and a thrown item entity in front of the player. fn player_drop(&mut self, thrown: ItemStack) { @@ -2066,6 +2068,21 @@ impl Game<'_> { let Some(info) = self.res.items.get(&stack.item).cloned() else { return Ok(()); }; + if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { + return Ok(()); + } + use horizon_client::first_person::UseResult; + let swings = self.swings_started; + match self.use_tool(&stack)? { + UseResult::Success { swing } => { + if swing && self.swings_started == swings { + self.swing_arm(); + } + return Ok(()); + } + UseResult::Fail => return Ok(()), + UseResult::Pass => {} + } if self.use_potion_item(&stack)? || self.throw_item(&stack)? { return Ok(()); } @@ -2087,12 +2104,13 @@ impl Game<'_> { return Ok(()); } if &*stack.item == "minecraft:bow" { - if self.using.is_none() { + if self.using.is_none() && (self.creative || self.arrow_slot().is_some()) { self.using = Some((self.selected, 0)); } return Ok(()); } - if info.food.is_some() + if info.consumable + && info.food.is_some() && let Some(p) = self.player.as_ref() && (p.health.food.food < 20 || self.creative) { @@ -2102,12 +2120,6 @@ impl Game<'_> { } return Ok(()); } - if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { - return Ok(()); - } - if self.use_tool(&stack)? { - return Ok(()); - } if self.place_boat(&stack) { return Ok(()); } @@ -6129,8 +6141,9 @@ impl Game<'_> { } } } - /// Item use on blocks for tools, buckets and fire starters; returns true if handled. - fn use_tool(&mut self, stack: &ItemStack) -> Result { + /// Block tool use: distinguish success, failure and fall-through for hand feedback. + fn use_tool(&mut self, stack: &ItemStack) -> Result { + use horizon_client::first_person::UseResult; let item = stack.item.trim_start_matches("minecraft:").to_owned(); let at = |p: [i32; 3]| { [ @@ -6142,16 +6155,16 @@ impl Game<'_> { if let Some(hit) = self.pick() && self.use_on_cauldron(hit.pos)? { - return Ok(true); + return Ok(UseResult::Success { swing: true }); } if item == "bucket" { let Some(hit) = self.pick_fluid() else { - return Ok(false); + return Ok(UseResult::Pass); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let f = self.res.facts.get(state).clone(); if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling { - return Ok(false); + return Ok(UseResult::Pass); } let (filled, sound) = match f.fluid { Fluid::Water => ("minecraft:water_bucket", "minecraft:item.bucket.fill"), @@ -6177,13 +6190,16 @@ impl Game<'_> { self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); } } - return Ok(true); + return Ok(UseResult::Success { swing: true }); } let Some(hit) = self.pick() else { - return Ok(false); + return Ok(UseResult::Pass); }; let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if item == "water_bucket" || item == "lava_bucket" { + if let Some((content, sound, mob)) = horizon_client::items::bucket_contents(&stack.item) { + if !self.may_build() { + return Ok(UseResult::Fail); + } let target = if self.res.facts.get(clicked).replaceable { hit.pos } else { @@ -6193,34 +6209,32 @@ impl Game<'_> { hit.pos[2] + hit.face[2], ] }; - let existing = self.world.block(target[0], target[1], target[2]); - if !self.res.facts.get(existing).replaceable && !self.res.facts.is_air(existing) { - return Ok(true); + let pos = BlockPos::new(target[0], target[1], target[2]); + let emptied = self + .with_level(|b, level, ticks| b.bucket_empty(level, ticks, pos, content, sound)); + self.process_level_events()?; + if !emptied { + return Ok(UseResult::Fail); } - let fluid = if item == "water_bucket" { - "minecraft:water" - } else { - "minecraft:lava" - }; - self.set_state_named(target, fluid, &[])?; - let sound = if item == "water_bucket" { - "minecraft:item.bucket.empty" - } else { - "minecraft:item.bucket.empty_lava" - }; - self.audio.play(sound, Some(at(target)), 1.0, 1.0); + if let Some(kind) = mob { + if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) { + self.mob_placed(id)?; + } + self.post_block_game_event( + "minecraft:entity_place", + target, + self.sculk_actor(), + None, + ); + } + self.trigger_item("minecraft:placed_block", stack); if !self.creative { - self.inventory[self.selected] = Some(ItemStack { - item: Arc::from("minecraft:bucket"), - count: 1, - damage: 0, - extra: None, - }); + self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); } - return Ok(true); + return Ok(UseResult::Success { swing: true }); } if self.use_block_transformer(stack, hit.pos, hit.face)? { - return Ok(true); + return Ok(UseResult::Success { swing: true }); } if item == "honeycomb" { let registry = self.res.assets.registry; @@ -6238,22 +6252,47 @@ impl Game<'_> { if !self.creative { self.consume_held(); } - return Ok(true); + return Ok(UseResult::Success { swing: true }); } } if item == "flint_and_steel" || item == "fire_charge" { + if !self.may_build() { + return Ok(UseResult::Fail); + } + let name = self.res.facts.get(clicked).name.clone(); + if self.can_light(clicked, &name) { + let registry = self.res.assets.registry; + let mut state = registry + .state(clicked) + .cloned() + .ok_or("missing lit block state")?; + state.properties.insert("lit".into(), "true".into()); + self.level_set(hit.pos, registry.resolve(&state)?)?; + self.audio.play( + if item == "fire_charge" { + "minecraft:item.firecharge.use" + } else { + "minecraft:item.flintandsteel.use" + }, + Some(at(hit.pos)), + 1.0, + self.world.random.next_float() * 0.4 + 0.8, + ); + if item == "fire_charge" { + self.consume_held(); + } else { + self.damage_held(1); + } + return Ok(UseResult::Success { swing: true }); + } let target = [ hit.pos[0] + hit.face[0], hit.pos[1] + hit.face[1], hit.pos[2] + hit.face[2], ]; - if self - .res - .facts - .is_air(self.world.block(target[0], target[1], target[2])) - { + if self.can_place_used_fire(target) { if !self.try_light_portal(target)? { - self.set_state_named(target, "minecraft:fire", &[])?; + self.place_used_fire(target)?; } let sound = if item == "fire_charge" { "minecraft:item.firecharge.use" @@ -6271,36 +6310,11 @@ impl Game<'_> { } else { self.damage_held(1); } - return Ok(true); + return Ok(UseResult::Success { swing: true }); } + return Ok(UseResult::Fail); } - // Equippable items swap into their armor slot (Equippable.swapWithEquipmentSlot); - // block items aimed at a block are placed instead. - if let Some(slot) = self - .res - .items - .get(&stack.item) - .filter(|i| i.block.is_none()) - .and_then(|i| i.equip_slot.clone()) - { - let index = match slot.as_str() { - "head" => 0, - "chest" => 1, - "legs" => 2, - "feet" => 3, - _ => return Ok(false), - }; - let held = self.inventory[self.selected].take(); - self.inventory[self.selected] = self.armor[index].take(); - self.armor[index] = held; - if let Some(eye) = self.eye_position() { - self.audio - .play("minecraft:item.armor.equip_generic", Some(eye), 1.0, 1.0); - } - self.apply_equipment(); - return Ok(true); - } - Ok(false) + Ok(UseResult::Pass) } /// `ExperienceOrb.award`: orbs of the largest sizes; each draws the id /// `tryMergeToExisting` compares from the level random, then moves with @@ -6332,6 +6346,21 @@ impl Game<'_> { on_ground: false, }); } + fn can_place_used_fire(&mut self, target: [i32; 3]) -> bool { + let pos = BlockPos::new(target[0], target[1], target[2]); + let direction = match ((self.yaw / 90.0 + 0.5).floor() as i32).rem_euclid(4) { + 0 => Direction::South, + 1 => Direction::West, + 2 => Direction::North, + _ => Direction::East, + }; + self.with_level(|b, level, ticks| b.fire_can_be_placed_at(level, ticks, pos, direction)) + } + fn place_used_fire(&mut self, target: [i32; 3]) -> Result<()> { + let pos = BlockPos::new(target[0], target[1], target[2]); + let state = self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, pos)); + self.level_set(target, state) + } /// DropExperienceBlock / RedStoneOreBlock / SculkBlock experience ranges. fn block_experience(&mut self, name: &str) -> u32 { let (min, max) = match name.trim_start_matches("minecraft:") { @@ -6580,27 +6609,48 @@ impl Game<'_> { ); } Some(stack) => { - // applyItemArmTransform + swingArm (applyItemArmAttackTransform) - let x = -0.4 * (sqrt_attack * std::f32::consts::PI).sin(); - let y = 0.2 * (sqrt_attack * std::f32::consts::TAU).sin(); - let z = -0.2 * (attack * std::f32::consts::PI).sin(); - let y_swing_rot = (attack * attack * std::f32::consts::PI).sin(); - let xz_swing_rot = (sqrt_attack * std::f32::consts::PI).sin(); - let m = to_world - * glam::Mat4::from_translation(glam::Vec3::new( - 0.56, - -0.52 + inverse_height * -0.6, - -0.72, - )) - * glam::Mat4::from_translation(glam::Vec3::new(x, y, z)) - * glam::Mat4::from_rotation_y(deg(45.0 + y_swing_rot * -20.0)) - * glam::Mat4::from_rotation_z(deg(xz_swing_rot * -20.0)) - * glam::Mat4::from_rotation_x(deg(xz_swing_rot * -80.0)) - * glam::Mat4::from_rotation_y(deg(-45.0)); - // `ItemInHandRenderer.renderItem`: the player as owner, seeded by - // its id plus the display context ordinal. let owner = self.player_owner(Some(&stack)); - let context = horizon_assets::item_model::DisplayContext::FirstPersonRightHand; + let using = owner.using_this_item && owner.use_item_remaining_ticks > 0; + let ticks_used = + owner.use_duration as f32 - (owner.use_item_remaining_ticks as f32 - a + 1.0); + use horizon_client::first_person::ItemPose; + let pose = match &*stack.item { + "minecraft:bow" if using => ItemPose::Bow { ticks_used }, + "minecraft:crossbow" => { + let charged = stack.data().is_some_and(|d| !d.charged.is_empty()); + ItemPose::Crossbow { + ticks_used: (using && !charged).then_some(ticks_used), + charge_duration: owner.crossbow_charge_duration as f32, + charged, + } + } + "minecraft:trident" if using => ItemPose::Trident { ticks_used }, + _ if using => { + let components = self + .res + .item_renderer + .models + .components(&horizon_client::item_render::stack_view(&stack)); + if components.contains_key("minecraft:consumable") { + ItemPose::Eat { + remaining: owner.use_item_remaining_ticks as f32, + duration: owner.use_duration as f32, + partial: a, + } + } else { + ItemPose::Using + } + } + _ => ItemPose::Swing, + }; + let left = self.settings.main_hand_left; + let m = to_world + * horizon_client::first_person::item_pose(left, inverse_height, attack, pose); + let context = if left { + horizon_assets::item_model::DisplayContext::FirstPersonLeftHand + } else { + horizon_assets::item_model::DisplayContext::FirstPersonRightHand + }; let state = self.resolve_item(&stack, context, Some(&owner), 4); let light = self.world.light( eye[0].floor() as i32, @@ -8670,6 +8720,7 @@ pub fn run() -> Result<()> { rockets: Vec::new(), creaking: Default::default(), trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), + arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), tnts: Vec::new(), hoppers: HashMap::new(), creative_screen: Creative::load(&game_root)?, diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 23aeeb092..3faeccf07 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -41,6 +41,9 @@ impl ArmorStandAssets { } } } + if let Some(part) = load("minecraft:elytra#main") { + player.insert("elytra", part); + } let mut equipment = HashMap::new(); if let Ok(entries) = std::fs::read_dir(root.join("assets/minecraft/equipment")) { for e in entries.flatten() { @@ -55,7 +58,7 @@ impl ArmorStandAssets { }; let Ok(v) = v else { continue }; let mut kinds = HashMap::new(); - for kind in ["humanoid", "humanoid_leggings"] { + for kind in ["humanoid", "humanoid_leggings", "wings"] { if let Some(layer) = v["layers"][kind].get(0) { let tex = layer["texture"] .as_str() diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index f275da402..50c252746 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -77,6 +77,7 @@ impl Game<'_> { _ => return false, }; self.open_book(screen); + self.swing_arm(); true } fn open_book(&mut self, screen: BookScreen) { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 27b48a15f..fe71cf173 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1327,6 +1327,7 @@ impl Game<'_> { fn tick_projectiles(&mut self) -> Result<()> { let mut projectiles = std::mem::take(&mut self.creatures.projectiles); let mut hits = Vec::new(); + let mut trails = Vec::new(); let mut deflections: Vec<[f64; 3]> = Vec::new(); { let mut targets: Vec<(Who, Aabb)> = self @@ -1362,6 +1363,7 @@ impl Game<'_> { let w = self.mob_world_base(&[]); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { + trails.extend(p.arrow_trail(pw.in_water(p.position))); let (keep, hit) = p.tick(&pw); let wind = matches!( p.kind, @@ -1397,6 +1399,13 @@ impl Game<'_> { keep }); } + for (ty, at, velocity) in trails { + self.particles.add( + &horizon_client::particles::ParticleOptions::simple(ty), + at, + velocity, + ); + } for at in deflections { self.audio .play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0); @@ -2345,7 +2354,7 @@ impl Game<'_> { } } self.elder_apparition_geometry(alpha, out); - // Projectiles: arrows as crossed quads, the rest as item billboards. + // Projectiles: the baked vanilla arrow model, the rest as item billboards. let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians()); let forward = glam::Vec3::new( -yaw.sin() * pitch.cos(), @@ -2371,52 +2380,24 @@ impl Game<'_> { packed = (15 * 16) | ((15 * 16) << 8); } if a.is_arrow() { + let Some(model) = self.arrow_model.as_ref() else { + continue; + }; let Some(r) = atlas.sprites.get("entity/projectiles/arrow").copied() else { continue; }; - let dir = glam::Vec3::new( - a.velocity.x as f32, - a.velocity.y as f32, - a.velocity.z as f32, - ) - .normalize_or(glam::Vec3::X); - let dir = if a.stuck { - glam::Vec3::new( - -a.yaw.to_radians().sin() * a.pitch.to_radians().cos(), - a.pitch.to_radians().sin(), - a.yaw.to_radians().cos() * a.pitch.to_radians().cos(), - ) - .normalize_or(dir) - } else { - dir - }; - let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08; - let upv = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08; - let (u1, v1) = ( - r.u0 + (r.u1 - r.u0) * 0.5, - r.v0 + (r.v1 - r.v0) * (5.0 / 32.0), + let m = glam::Mat4::from_translation(c) + * glam::Mat4::from_rotation_y((a.yaw - 90.0).to_radians()) + * glam::Mat4::from_rotation_z(a.pitch.to_radians()); + horizon_client::mobs::render_model( + model, + m, + &|part| part.pose, + [r.u0, r.v0, r.u1, r.v1], + packed, + 0, + out, ); - for off in [side, upv] { - let q = [ - c - dir * 0.25 - off, - c + dir * 0.25 - off, - c + dir * 0.25 + off, - c - dir * 0.25 + off, - ]; - for (v, uv) in q - .iter() - .zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]]) - { - out.push(Vertex { - normal: [0; 4], - pos: v.to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: packed, - }); - } - } continue; } // WindChargeRenderer. diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index c51049da8..b2ae95387 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -13,7 +13,7 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; const CROSSBOW: &str = "minecraft:crossbow"; impl Game<'_> { - fn charge_ticks(stack: &ItemStack) -> u32 { + pub(super) fn charge_ticks(stack: &ItemStack) -> u32 { // crossbow_charge_time: 1.25 s, minus 0.25 s per Quick Charge level. let seconds = 1.25 - 0.25 * stack.enchantment_level("minecraft:quick_charge") as f32; (seconds.max(0.0) * 20.0).floor() as u32 @@ -42,7 +42,7 @@ impl Game<'_> { ], } } - fn arrow_slot(&self) -> Option { + pub(super) fn arrow_slot(&self) -> Option { self.inventory .iter() .position(|s| s.as_ref().is_some_and(|s| &*s.item == "minecraft:arrow")) diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index d86c41255..23488c3fa 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -741,7 +741,7 @@ impl Game<'_> { 1.0 + amount } /// `EntityType.spawn(.., pos, reason, tryMoveDown, false)` for a mob. - fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option { + pub(super) fn spawn_mob_at(&mut self, kind: &str, p: Pos, try_move_down: bool) -> Option { let name = if kind.contains(':') { kind.to_owned() } else { @@ -868,7 +868,7 @@ impl Game<'_> { self.handle_mob_events(events) } /// A mob a bucket emptied: `setFromBucket` keeps it, then it calls out. - fn mob_placed(&mut self, id: u32) -> Result<()> { + pub(super) fn mob_placed(&mut self, id: u32) -> Result<()> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.persistent = true; } @@ -1141,48 +1141,8 @@ impl Game<'_> { ) -> Result { let item = stack.item.to_string(); let target = offset(pos, facing); - let (content, sound, mob) = match item.as_str() { - "minecraft:lava_bucket" => ( - BucketContent::Fluid(FluidKind::Lava), - "minecraft:item.bucket.empty_lava", - None, - ), - "minecraft:water_bucket" => ( - BucketContent::Fluid(FluidKind::Water), - "minecraft:item.bucket.empty", - None, - ), - "minecraft:powder_snow_bucket" => ( - BucketContent::Powder, - "minecraft:item.bucket.empty_powder_snow", - None, - ), - "minecraft:axolotl_bucket" => ( - BucketContent::MobWater, - "minecraft:item.bucket.empty_axolotl", - Some("axolotl"), - ), - "minecraft:tadpole_bucket" => ( - BucketContent::MobWater, - "minecraft:item.bucket.empty_tadpole", - Some("tadpole"), - ), - "minecraft:sulfur_cube_bucket" => ( - BucketContent::Nothing, - "minecraft:item.bucket.empty_sulfur_cube", - Some("sulfur_cube"), - ), - other => ( - BucketContent::MobWater, - "minecraft:item.bucket.empty_fish", - Some(match other { - "minecraft:salmon_bucket" => "salmon", - "minecraft:cod_bucket" => "cod", - "minecraft:pufferfish_bucket" => "pufferfish", - _ => "tropical_fish", - }), - ), - }; + let (content, sound, mob) = + horizon_client::items::bucket_contents(&item).expect("filled bucket dispatcher"); let target_pos = Self::pos_of(target); let emptied = self .with_level(|b, level, ticks| b.bucket_empty(level, ticks, target_pos, content, sound)); @@ -1337,7 +1297,7 @@ impl Game<'_> { Ok((Some(stack), event)) } /// `CampfireBlock.canLight || CandleBlock.canLight || CandleCakeBlock.canLight`. - fn can_light(&self, state: BlockStateId, name: &str) -> bool { + pub(super) fn can_light(&self, state: BlockStateId, name: &str) -> bool { let lit = self.prop(state, "lit"); let waterlogged = self.prop(state, "waterlogged"); let dry_unlit = lit.as_deref() == Some("false") && waterlogged.as_deref() == Some("false"); diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 60fca288e..bbaeb1a99 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -102,6 +102,7 @@ impl Game<'_> { if !self.creative { self.consume_held(); } + self.swing_arm(); true } pub(super) fn tick_rockets(&mut self) { diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index d5a4db677..8e25eee84 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -222,7 +222,7 @@ impl Game<'_> { owner.using_this_item = true; owner.use_duration = duration; owner.use_item_remaining_ticks = duration - ticks as i32; - owner.crossbow_charge_duration = 25; + owner.crossbow_charge_duration = Self::charge_ticks(stack).max(1) as i32; } owner.is_selected = stack.is_some() && self.inventory.get(self.selected).and_then(Option::as_ref) == stack; diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 7da906515..826a3e1bb 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -297,6 +297,14 @@ impl Game<'_> { } let crouching = p.pose == Pose::Crouching; let (position, flying) = (p.position, p.flying || p.fall_flying); + let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); + let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); + let charged = self.inventory[self.selected] + .as_ref() + .is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty())); + let charge_duration = self.inventory[self.selected] + .as_ref() + .map_or(25, |s| Self::charge_ticks(s).max(1)) as i32; let attack = (self.swing.old_animation, self.swing.animation); let swinging = self.swing.swinging(); let (yaw, pitch) = (self.yaw, self.pitch); @@ -356,6 +364,14 @@ impl Game<'_> { m.extra.off_hand = off; m.extra.crouching = crouching; m.extra.passenger = riding; + m.velocity = velocity; + m.extra.fall_flying = fall_flying; + m.extra.fall_fly_ticks = fly_ticks; + m.extra.main_hand_left = self.settings.main_hand_left; + m.extra.using_item = using; + m.extra.charged = charged; + m.extra.ints[5] = charge_duration; + m.extra.elytra.tick(fall_flying, crouching, velocity); m.hurt_time = hurt; } /// Whether the player's own model shows in the world view. @@ -400,6 +416,7 @@ impl Game<'_> { &self.player_armor_layers(), out, ); + self.player_elytra_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box @@ -454,6 +471,7 @@ impl Game<'_> { &self.player_armor_layers(), &mut verts, ); + self.player_elytra_geometry(&m, 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); @@ -509,3 +527,54 @@ impl Game<'_> { } } } + +impl Game<'_> { + fn player_elytra_geometry( + &self, + m: &Mob, + 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)) + .and_then(|i| i.equip_asset.as_ref()) + else { + return; + }; + let assets = &self.armor_stand_assets; + let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else { + return; + }; + let (Some(model), Some(rect)) = ( + assets.player.get("elytra"), + self.res.atlas.sprites.get(texture), + ) else { + return; + }; + let base = horizon_client::mobs::render::base_transform(m, partial, camera) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.0, 0.125)); + let angles = m.extra.elytra.angles(partial); + horizon_client::mobs::render_model( + model, + base, + &|part| { + let mut p = part.pose; + if part.name == "left_wing" || part.name == "right_wing" { + let invert = if part.name == "left_wing" { 1.0 } else { -1.0 }; + p[1] = if m.extra.crouching { 3.0 } else { 0.0 }; + p[3] = angles[0]; + p[4] = invert * angles[1]; + p[5] = invert * angles[2]; + } + p + }, + [rect.u0, rect.v0, rect.u1, rect.v1], + light, + 0, + out, + ); + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index abba286f1..29385b53e 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -27,6 +27,7 @@ pub struct ItemInfo { pub tool: Vec, pub tool_default_speed: f32, pub food: Option<(u32, f32)>, + pub consumable: bool, pub model: String, /// Main-hand `attack_damage` / `attack_speed` modifier amounts. pub attack_damage: f32, @@ -378,6 +379,7 @@ impl Items { .as_f64() .unwrap_or(1.0) as f32, food, + consumable: c.get("minecraft:consumable").is_some(), model: c["minecraft:item_model"] .as_str() .unwrap_or(name) @@ -1169,6 +1171,94 @@ impl LootContext<'_> { } } +/// `DispensibleContainerItem`: shared contents for hand use and dispensers. +pub fn bucket_contents( + item: &str, +) -> Option<(horizon_world::level::BucketContent, &str, Option<&str>)> { + use horizon_world::{fluid::FluidKind, level::BucketContent as C}; + Some(match item { + "minecraft:water_bucket" => ( + C::Fluid(FluidKind::Water), + "minecraft:item.bucket.empty", + None, + ), + "minecraft:lava_bucket" => ( + C::Fluid(FluidKind::Lava), + "minecraft:item.bucket.empty_lava", + None, + ), + "minecraft:powder_snow_bucket" => { + (C::Powder, "minecraft:item.bucket.empty_powder_snow", None) + } + "minecraft:cod_bucket" => (C::MobWater, "minecraft:item.bucket.empty_fish", Some("cod")), + "minecraft:salmon_bucket" => ( + C::MobWater, + "minecraft:item.bucket.empty_fish", + Some("salmon"), + ), + "minecraft:pufferfish_bucket" => ( + C::MobWater, + "minecraft:item.bucket.empty_fish", + Some("pufferfish"), + ), + "minecraft:tropical_fish_bucket" => ( + C::MobWater, + "minecraft:item.bucket.empty_fish", + Some("tropical_fish"), + ), + "minecraft:axolotl_bucket" => ( + C::MobWater, + "minecraft:item.bucket.empty_axolotl", + Some("axolotl"), + ), + "minecraft:tadpole_bucket" => ( + C::MobWater, + "minecraft:item.bucket.empty_tadpole", + Some("tadpole"), + ), + "minecraft:sulfur_cube_bucket" => ( + C::Nothing, + "minecraft:item.bucket.empty_sulfur_cube", + Some("sulfur_cube"), + ), + _ => return None, + }) +} + +#[cfg(test)] +mod bucket_use_tests { + use super::*; + #[test] + fn every_filled_bucket_has_the_native_content_and_sound() { + use horizon_world::level::BucketContent as C; + assert_eq!( + bucket_contents("minecraft:powder_snow_bucket"), + Some((C::Powder, "minecraft:item.bucket.empty_powder_snow", None)) + ); + assert_eq!( + bucket_contents("minecraft:tadpole_bucket"), + Some(( + C::MobWater, + "minecraft:item.bucket.empty_tadpole", + Some("tadpole") + )) + ); + assert_eq!( + bucket_contents("minecraft:sulfur_cube_bucket"), + Some(( + C::Nothing, + "minecraft:item.bucket.empty_sulfur_cube", + Some("sulfur_cube") + )) + ); + for id in ["cod", "salmon", "pufferfish", "tropical_fish", "axolotl"] { + assert!(bucket_contents(&format!("minecraft:{id}_bucket")).is_some()); + } + assert!(bucket_contents("minecraft:bucket").is_none()); + assert!(bucket_contents("minecraft:milk_bucket").is_none()); + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f8ebca55c..96dcf9949 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -660,6 +660,10 @@ pub struct Extra { pub legs: Option>, pub feet: Option>, pub using_item: i32, + pub fall_flying: bool, + pub fall_fly_ticks: i32, + pub main_hand_left: bool, + pub elytra: ElytraAnimation, pub flag: bool, pub flag2: bool, /// Species scratch values (the wither's head targets and clocks). @@ -1885,3 +1889,62 @@ mod lighting_tests { ); } } + +/// `LivingEntity.elytraAnimationState`: eased wing angles and render interpolation. +#[derive(Clone, Copy, Debug, Default)] +pub struct ElytraAnimation { + pub old: [f32; 3], + pub angles: [f32; 3], +} +impl ElytraAnimation { + pub fn tick(&mut self, flying: bool, crouching: bool, velocity: horizon_core::geometry::Vec3) { + use std::f32::consts::PI; + self.old = self.angles; + let target = if flying { + let length = + (velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z) + .sqrt(); + let ratio = if velocity.y < 0.0 && length > 0.0 { + 1.0 - horizon_core::jmath::pow(-velocity.y / length, 1.5) as f32 + } else { + 1.0 + }; + [ + PI / 12.0 + (PI / 9.0 - PI / 12.0) * ratio, + 0.0, + -PI / 12.0 + (-PI / 2.0 + PI / 12.0) * ratio, + ] + } else if crouching { + [PI * 2.0 / 9.0, 0.08726646, -PI / 4.0] + } else { + [PI / 12.0, 0.0, -PI / 12.0] + }; + for (angle, target) in self.angles.iter_mut().zip(target) { + *angle += (target - *angle) * 0.3; + } + } + pub fn angles(&self, partial: f32) -> [f32; 3] { + std::array::from_fn(|i| self.old[i] + (self.angles[i] - self.old[i]) * partial) + } +} + +#[cfg(test)] +mod elytra_tests { + use super::*; + #[test] + fn wings_ease_between_ground_flight_and_crouch() { + let mut wings = ElytraAnimation::default(); + wings.tick(false, false, Vec3::ZERO); + assert!((wings.angles[0] - std::f32::consts::PI / 12.0 * 0.3).abs() < 0.000001); + assert_eq!(wings.angles(0.0), wings.old); + assert_eq!(wings.angles(1.0), wings.angles); + for _ in 0..40 { + wings.tick(true, false, Vec3::new(1.0, 0.0, 0.0)); + } + assert!((wings.angles[2] + std::f32::consts::FRAC_PI_2).abs() < 0.00001); + for _ in 0..40 { + wings.tick(false, true, Vec3::ZERO); + } + assert!((wings.angles[1] - 0.08726646).abs() < 0.00001); + } +} diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index ca340fbaa..161db24f9 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -266,6 +266,8 @@ pub struct Hum { pub left: ArmPose, pub crouching: bool, pub passenger: bool, + pub fall_flying: bool, + pub fly_speed_scale: f32, /// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`. pub zombie: Option, /// The main hand holds something (`getMainHandItemStack() != EMPTY`). @@ -282,6 +284,8 @@ impl Hum { left, crouching: false, passenger: false, + fall_flying: false, + fly_speed_scale: 1.0, zombie: None, holding: false, charge: (0.0, 0.0), @@ -353,7 +357,10 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { /// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`). pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { head(p, s); - let (pos, sp) = (s.pos, s.speed); + if h.fall_flying { + p.xrot("head", -std::f32::consts::FRAC_PI_4); + } + let (pos, sp) = (s.pos, s.speed / h.fly_speed_scale); p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5); p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5); p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp); @@ -539,7 +546,38 @@ pub fn setup( } else { ArmPose::Empty }; - let mut h = Hum::new(right, ArmPose::Empty); + let pose = if player { + match m.extra.main_hand.as_deref() { + Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow, + Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => { + ArmPose::CrossbowCharge + } + Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => { + ArmPose::CrossbowHold + } + Some(_) => ArmPose::Item, + None => ArmPose::Empty, + } + } else { + right + }; + let off = if player && m.extra.off_hand.is_some() && !pose.two_handed() { + ArmPose::Item + } else { + ArmPose::Empty + }; + let mut h = if m.extra.main_hand_left { + Hum::new(off, pose) + } else { + Hum::new(pose, off) + }; + h.charge = (m.extra.ints[5] as f32, m.extra.using_item as f32); + h.fall_flying = m.extra.fall_flying; + if h.fall_flying { + let v = m.velocity; + h.fly_speed_scale = + (((v.x * v.x + v.y * v.y + v.z * v.z) as f32 / 0.2).powi(3)).max(1.0); + } h.crouching = m.extra.crouching; h.passenger = m.extra.passenger; humanoid(p, s, &h); @@ -630,3 +668,46 @@ pub fn setup( } } } + +#[cfg(test)] +mod flight_pose_tests { + use super::*; + #[test] + fn flight_slows_limbs_and_sets_the_head_pose() { + let state = State { + pos: 0.0, + speed: 1.0, + age: 0.0, + y_rot: 0.0, + x_rot: 0.0, + swing: 0.0, + baby: false, + partial: 0.0, + }; + let make = || Poses { + map: [ + "head", + "right_arm", + "left_arm", + "right_leg", + "left_leg", + "body", + ] + .into_iter() + .map(|n| (n.to_string(), [0.0; 9])) + .collect(), + dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), + }; + let mut ground = make(); + let mut flight = make(); + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + humanoid(&mut ground, &state, &h); + h.fall_flying = true; + h.fly_speed_scale = 8.0; + humanoid(&mut flight, &state, &h); + assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4); + assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0); + } +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index ef45ffb46..2e722674e 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -738,6 +738,28 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 { .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation; + if m.extra.fall_flying { + let ticks = m.extra.fall_fly_ticks as f32 + alpha; + let scale = (ticks * ticks / 100.0).min(1.0); + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; + let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos()); + let v = m.velocity; + let view_scale = (pitch.to_radians()).mcos(); + let (look_x, look_z) = (look_x * view_scale, look_z * view_scale); + let view_length = f64::from(look_x * look_x + look_z * look_z); + let speed = v.x * v.x + v.z * v.z; + if speed > f64::from(1.0e-5f32) && view_length > f64::from(1.0e-5f32) { + let dot = + (v.x * f64::from(look_x) + v.z * f64::from(look_z)) / (speed * view_length).sqrt(); + let sign = (v.x * f64::from(look_z) - v.z * f64::from(look_x)).signum(); + base *= glam::Mat4::from_rotation_y( + (sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32, + ); + } + } + if m.death_time > 0 && !super::creaking::tearing_down(m) { let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) .sqrt() diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index 59d419a46..e66f41819 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -138,6 +138,41 @@ impl Projectile { bonus: Default::default(), } } + /// `AbstractArrow.tick`: critical streaks and submerged bubble trails. + pub fn arrow_trail( + &self, + water: bool, + ) -> Vec<(crate::particles::ParticleType, [f64; 3], [f64; 3])> { + use crate::particles::ParticleType; + let mut trail = Vec::new(); + if self.stuck || !self.is_arrow() { + return trail; + } + let (p, v) = (self.position, self.velocity); + if water { + let drag = f64::from(0.6f32); + let speed = [v.x * drag, v.y * drag, v.z * drag]; + let at = [ + p.x - speed[0] * 0.25, + p.y - speed[1] * 0.25, + p.z - speed[2] * 0.25, + ]; + for _ in 0..4 { + trail.push((ParticleType::Bubble, at, speed)); + } + } + if matches!(self.kind, ProjectileKind::Arrow { critical: true, .. }) { + for i in 0..4 { + let t = i as f64 / 4.0; + trail.push(( + ParticleType::Crit, + [p.x + v.x * t, p.y + v.y * t, p.z + v.z * t], + [-v.x, -v.y + 0.2, -v.z], + )); + } + } + trail + } pub fn is_arrow(&self) -> bool { matches!(self.kind, ProjectileKind::Arrow { .. }) } @@ -760,3 +795,53 @@ mod tests { assert!((p.velocity.x - 0.19).abs() < 1e-9); } } + +#[cfg(test)] +mod trail_tests { + use super::*; + use crate::particles::ParticleType; + fn arrow(critical: bool) -> Projectile { + let mut p = Projectile::new( + ProjectileKind::Arrow { + base_damage: 2.0, + critical, + effect: None, + }, + Vec3::new(1.0, 2.0, 3.0), + None, + ); + p.velocity = Vec3::new(4.0, 2.0, -1.0); + p + } + #[test] + fn critical_arrow_emits_four_native_streak_samples() { + let trail = arrow(true).arrow_trail(false); + assert_eq!(trail.len(), 4); + for (i, (ty, pos, speed)) in trail.iter().enumerate() { + assert_eq!(*ty, ParticleType::Crit); + assert_eq!( + *pos, + [1.0 + i as f64, 2.0 + i as f64 * 0.5, 3.0 - i as f64 * 0.25] + ); + assert_eq!(*speed, [-4.0, -1.8, 1.0]); + } + } + #[test] + fn submerged_arrow_emits_four_bubbles_after_water_inertia() { + let trail = arrow(false).arrow_trail(true); + assert_eq!(trail.len(), 4); + let drag = f64::from(0.6f32); + for (ty, pos, speed) in trail { + assert_eq!(ty, ParticleType::Bubble); + assert_eq!(speed, [4.0 * drag, 2.0 * drag, -drag]); + assert_eq!(pos, [1.0 - drag, 2.0 - drag * 0.5, 3.0 + drag * 0.25]); + } + } + #[test] + fn ordinary_and_stuck_arrows_do_not_emit_critical_trails() { + assert!(arrow(false).arrow_trail(false).is_empty()); + let mut p = arrow(true); + p.stuck = true; + assert!(p.arrow_trail(true).is_empty()); + } +} diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index 758e9e857..213f7c7ca 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -34,7 +34,9 @@ pub struct Sprites { pub translucent: Vec, } /// Edge length of every sprite array layer. -pub const SPRITE_SIZE: u32 = 16; +// Flow sprites are 32 square: each fluid face samples a 16-texel subregion. +// shortcut: HD frames above 32 are resampled; use variable-resolution storage for HD-pack parity. +pub const SPRITE_SIZE: u32 = 32; impl Sprites { pub fn insert(&mut self, root: &Path, name: &str) -> Result { if let Some(layer) = self.layers.get(name) { @@ -140,6 +142,48 @@ impl Sprites { #[cfg(test)] mod tests { use super::*; + #[test] + fn native_32_pixel_animation_frames_keep_every_texel() { + let root = std::env::temp_dir().join(format!( + "horizon-sprite-detail-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let directory = root.join("assets/test/textures"); + fs::create_dir_all(&directory).unwrap(); + let path = directory.join("flow.png"); + let mut pixels = Vec::new(); + for y in 0..64u8 { + for x in 0..32u8 { + pixels.extend([x, y, 0, 255]); + } + } + let mut encoder = png::Encoder::new(File::create(&path).unwrap(), 32, 64); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + fs::write(path.with_extension("png.mcmeta"), r#"{"animation":{}}"#).unwrap(); + let mut sprites = Sprites::default(); + sprites.insert(&root, "test:flow").unwrap(); + let size = sprites.size; + let initial = sprites.pixels.clone(); + let animation = sprites.animations[0].clone(); + fs::remove_dir_all(root).unwrap(); + assert_eq!( + size, 32, + "half a flowing-water frame must retain 16 texels, not 8" + ); + assert_eq!(initial, pixels[..32 * 32 * 4]); + assert_eq!(animation.pixels(animation.frame(1)), &pixels[32 * 32 * 4..]); + } + #[test] fn animation_boundaries_and_repeated_frames_do_not_depend_on_render_rate() { let animation = SpriteAnimation { diff --git a/tests/test_item_action_animation.py b/tests/test_item_action_animation.py new file mode 100644 index 000000000..145a21993 --- /dev/null +++ b/tests/test_item_action_animation.py @@ -0,0 +1,93 @@ +"""Compile the actual drop and ignition branches with world effects stubbed.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +def block(source, start): + opening = source.index("{", start) + depth, end = 1, opening + 1 + while depth: + depth += (source[end] == "{") - (source[end] == "}") + end += 1 + return source[start:end] + + +class ItemActionAnimationTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is required for action-policy tests") + def test_successful_drop_and_ignition_start_a_swing(self): + source = (ROOT / "crates/horizon-client/src/game.rs").read_text() + drop = block(source, source.index("fn drop_held(")) + ignition = block(source, source.index("if self.can_place_used_fire(target)")) + caller_start = source.index(" let swings = self.swings_started;", source.index("fn use_item_as_player(")) + caller = source[caller_start:source.index(" if self.use_potion_item", caller_start)] + program = """ +type Result = std::result::Result>; +enum UseResult { Pass, Fail, Success { swing: bool } } +#[derive(Clone)] struct ItemStack { count: u32, item: String } +struct Hit { pos: [i32; 3], face: [i32; 3] } +struct Facts; impl Facts { fn is_air(&self, state:u8)->bool { state == 0 } } +struct Res { facts:Facts } +struct Random; impl Random { fn next_float(&mut self)->f32 { 0.5 } } +struct World { air:bool, path:bool, random:Random } +impl World { fn block(&self,_:i32,_:i32,_:i32)->u8 { if self.air {0} else {1} } } +struct Audio { sounds:u32 } impl Audio { fn play(&mut self,_:&str,_:Option<[f64;3]>,_:f32,_:f32) {self.sounds+=1;} } +struct Game { selected:usize, inventory:[Option;1], alive:bool, swings:u32, drops:u32, res:Res, world:World, audio:Audio } +impl Game { + DROP + fn ignite(&mut self,item:&str)->Result<()> { + let stack=ItemStack {count:1,item:item.into()}; + CALLER + Ok(()) + } + fn use_tool(&mut self,stack:&ItemStack)->Result { + let item=stack.item.as_str(); + let hit = Hit { pos:[0;3], face:[0,1,0] }; + let at = |p:[i32;3]| p.map(f64::from); + let target = [0,1,0]; + IGNITION + Ok(UseResult::Fail) + } + fn eye_position(&self)->Option<[f64;3]> { self.alive.then_some([0.0;3]) } + fn player_drop(&mut self,stack:ItemStack) { self.drops += stack.count; } + fn swing_arm(&mut self) { self.swings += 1; } + fn try_light_portal(&mut self,_:[i32;3])->Result {Ok(false)} + fn may_build(&self)->bool {true} + fn can_place_used_fire(&self,_:[i32;3])->bool {self.world.air&&!self.world.path} + fn place_used_fire(&mut self,_:[i32;3])->Result<()> {Ok(())} + fn consume_held(&mut self) {} fn damage_held(&mut self,_:u32) {} +} +fn game()->Game { Game { selected:0, inventory:[Some(ItemStack { count:4,item:"minecraft:stone".into() })], alive:true, swings:0, drops:0, res:Res {facts:Facts}, world:World {air:true,path:false,random:Random}, audio:Audio {sounds:0} } } +#[test] fn dropping_one_and_all_swings_only_on_success() { + let mut g=game();g.drop_held(false);assert_eq!((g.drops,g.swings),(1,1)); + g.drop_held(true);assert_eq!((g.drops,g.swings),(4,2)); + g.drop_held(false);assert_eq!(g.swings,2); + let mut g=game();g.alive=false;g.drop_held(false);assert_eq!(g.swings,0); +} +#[test] fn successful_ignition_swings_but_blocked_ignition_does_not() { + for item in ["flint_and_steel","fire_charge"] { + let mut g=game();g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(1,1)); + let mut g=game();g.world.air=false;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0)); + let mut g=game();g.world.path=true;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0)); + } +} +""".replace("DROP", drop).replace("IGNITION", ignition).replace("CALLER", caller) + program = program.replace("self.swings_started", "self.swings") + with tempfile.TemporaryDirectory(prefix="horizon-item-action-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + compiled = subprocess.run( + ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")], + capture_output=True, text=True, check=False, + ) + self.assertEqual(compiled.returncode, 0, compiled.stderr) + tested = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False) + self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr) + + +if __name__ == "__main__": + unittest.main() From 726f88fcfca37181f7d4ed231ca022f241ff1486 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 02:20:13 -0400 Subject: [PATCH 02/23] Fix axolotl AI, fluid and fire integration, and world-local progress Bind resident environment kernels and real fire clocks, fix sprite uploads and flame material, restore swim speed, throttle item lava audio, and emit fire extinguish events. Reset world-entry progress state without deleting saved data. Exact axolotl replay parity remains deferred to issue #64. --- crates/horizon-client/src/advancements.rs | 19 + crates/horizon-client/src/effects.rs | 2 + crates/horizon-client/src/entities.rs | 198 +++++ crates/horizon-client/src/entity_nbt.rs | 43 +- crates/horizon-client/src/fire_render.rs | 106 +++ crates/horizon-client/src/game.rs | 185 ++++- .../horizon-client/src/game/armor_stands.rs | 19 +- crates/horizon-client/src/game/creatures.rs | 50 +- .../src/game/enchant_effects.rs | 29 +- crates/horizon-client/src/game/lightning.rs | 9 +- crates/horizon-client/src/game/potions.rs | 3 +- crates/horizon-client/src/game/remote.rs | 2 + crates/horizon-client/src/game/render_tick.rs | 4 +- crates/horizon-client/src/gfx.rs | 6 +- crates/horizon-client/src/hud.rs | 69 ++ crates/horizon-client/src/items.rs | 23 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 10 + crates/horizon-client/src/mobs/ai.rs | 31 +- .../horizon-client/src/mobs/animal_brain.rs | 693 +++++++++++++++++- crates/horizon-client/src/mobs/aquatic.rs | 20 + crates/horizon-client/src/mobs/axolotl.rs | 205 ++++++ crates/horizon-client/src/mobs/body_anim.rs | 22 +- crates/horizon-client/src/mobs/goals.rs | 16 +- .../horizon-client/src/mobs/monster_brain.rs | 4 +- crates/horizon-client/src/mobs/world.rs | 3 + crates/horizon-client/src/motion.rs | 221 +++++- .../horizon-client/src/motion/environment.rs | 320 ++++++++ crates/horizon-client/src/pose.rs | 5 +- crates/horizon-client/src/sprites.rs | 46 ++ crates/horizon-client/src/world.rs | 2 + crates/horizon-world/src/level/hooks.rs | 7 +- crates/horizon-world/src/level/tests.rs | 35 + tests/test_sprite_animation_upload.py | 71 ++ tests/test_world_runtime_reset.py | 39 + 35 files changed, 2397 insertions(+), 121 deletions(-) create mode 100644 crates/horizon-client/src/fire_render.rs create mode 100644 crates/horizon-client/src/mobs/axolotl.rs create mode 100644 crates/horizon-client/src/motion/environment.rs create mode 100644 tests/test_sprite_animation_upload.py create mode 100644 tests/test_world_runtime_reset.py diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 2d62c2b97..14754d3b7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -571,6 +571,7 @@ pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool { w, ) } + "minecraft:match_block" => ctx.block_pos.is_some_and(|b| block(v, b, w)), "minecraft:block_state_property" => ctx.block_pos.is_some_and(|b| { let mut pred = serde_json::Map::new(); pred.insert("blocks".into(), v["block"].clone()); @@ -929,6 +930,24 @@ mod tests { } } #[test] + fn bucket_axolotl_block_advancements_require_the_placed_block() { + let ctx = Entities { + this: None, + origin: [0.0; 3], + tool: None, + block_pos: Some([0; 3]), + }; + let stone = serde_json::json!({"type":"minecraft:match_block","blocks":"minecraft:stone"}); + let wheat = serde_json::json!({"type":"minecraft:match_block","blocks":"minecraft:wheat"}); + assert!(conditions(&stone, &ctx, &Flat)); + assert!(!conditions(&wheat, &ctx, &Flat)); + let absent = Entities { + block_pos: None, + ..ctx + }; + assert!(!conditions(&stone, &absent, &Flat)); + } + #[test] fn predicates_match_tags_ranges_and_locations() { let w = Flat; let stone = ItemView { diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 7c245987a..4dbc2268c 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -283,6 +283,7 @@ impl PlayerEffects { levitation: self.amplifier("levitation"), resistance: self.amplifier("resistance"), fire_resistance: self.get("fire_resistance").is_some(), + dolphins_grace: self.get("dolphins_grace").is_some(), water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), protection: Vec::new(), @@ -378,6 +379,7 @@ pub struct StatusFlags { pub levitation: Option, pub resistance: Option, pub fire_resistance: bool, + pub dolphins_grace: bool, pub water_breathing: bool, /// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`). pub protection: Vec<(String, f32)>, diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index c0295a688..2855f9679 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -12,6 +12,8 @@ use horizon_world::block_collision::BlockCollisionRegistry; #[derive(Clone, Debug)] pub struct ItemEntity { + pub health: i32, + pub fire_ticks: i32, pub id: u32, pub stack: ItemStack, pub position: Vec3, @@ -22,6 +24,17 @@ pub struct ItemEntity { pub pickup_delay: u32, pub bob_offset: f32, } +/// Environment results needed by the entity owner, including lethal lava damage. +#[derive(Debug)] +pub struct ItemEnvironmentTick { + pub alive: bool, + pub lava_hurt: bool, +} +impl ItemEnvironmentTick { + pub fn should_play_lava_hurt_sound(&self, tick: u32) -> bool { + self.lava_hurt && (!self.alive || tick.is_multiple_of(10)) + } +} impl ItemEntity { pub const WIDTH: f64 = 0.25; pub fn bounds(&self) -> Aabb { @@ -35,6 +48,50 @@ impl ItemEntity { ), ) } + pub fn environment_tick( + &mut self, + world: &World, + facts: &BlockFacts, + registry: &horizon_world::registry::BlockRegistry, + items: &crate::items::Items, + ) -> ItemEnvironmentTick { + let at = world.block( + self.position.x.floor() as i32, + (self.position.y + 0.1).floor() as i32, + self.position.z.floor() as i32, + ); + let fluid = facts.get(at).fluid; + if fluid == Fluid::Water { + self.fire_ticks = 0; + } + if self.fire_ticks > 0 { + if self.fire_ticks % 20 == 0 + && fluid != Fluid::Lava + && !items.resists_fire(&self.stack, "minecraft:on_fire") + { + self.health -= 1; + } + self.fire_ticks -= 1; + } + let mut lava_hurt = false; + if fluid == Fluid::Lava { + self.fire_ticks = self.fire_ticks.max(300); + if !items.resists_fire(&self.stack, "minecraft:lava") { + self.health -= 4; + lava_hurt = true; + } + } + if crate::motion::environment::fire_contact(world, registry, self.bounds()) > 0.0 { + self.fire_ticks = self.fire_ticks.max(160); + if !items.resists_fire(&self.stack, "minecraft:in_fire") { + self.health -= 1; + } + } + ItemEnvironmentTick { + alive: self.health > 0, + lava_hurt, + } + } /// Returns false when the item should be removed. pub fn tick( &mut self, @@ -59,6 +116,12 @@ impl ItemEntity { self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, self.velocity.z * 0.99, ); + } else if facts.get(eye).fluid == Fluid::Lava { + self.velocity = Vec3::new( + self.velocity.x * 0.95, + self.velocity.y + if self.velocity.y < 0.06 { 5.0e-4 } else { 0.0 }, + self.velocity.z * 0.95, + ); } else { self.velocity.y -= 0.04; } @@ -431,6 +494,8 @@ impl ItemFrame { /// An armor stand (`ArmorStand`). #[derive(Clone, Debug)] pub struct ArmorStand { + pub fire_ticks: i32, + pub health: f32, pub id: u32, pub position: Vec3, pub velocity: Vec3, @@ -450,6 +515,8 @@ impl ArmorStand { pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"]; pub fn new(id: u32, position: Vec3, yaw: f32) -> Self { Self { + fire_ticks: 0, + health: 20.0, id, position, velocity: Vec3::ZERO, @@ -464,6 +531,53 @@ impl ArmorStand { last_hit: i64::MIN / 2, } } + pub fn environment_tick( + &mut self, + world: &World, + facts: &BlockFacts, + registry: &horizon_world::registry::BlockRegistry, + ) -> bool { + let (lo, hi) = (self.bounds().min_position(), self.bounds().max_position()); + let mut water = false; + let mut lava = false; + for x in lo.x.floor() as i32..=hi.x.floor() as i32 { + for y in lo.y.floor() as i32..hi.y.ceil() as i32 { + for z in lo.z.floor() as i32..=hi.z.floor() as i32 { + match facts.get(world.block(x, y, z)).fluid { + Fluid::Water => water = true, + Fluid::Lava => lava = true, + _ => {} + } + } + } + } + if water { + self.fire_ticks = 0; + } + if self.fire_ticks > 0 { + if self.fire_ticks % 20 == 0 + && !lava + && !self.invisible + && !self.marker + && self.health > 0.5 + { + self.health -= 4.0; + } + self.fire_ticks -= 1; + } + if lava { + self.fire_ticks = self.fire_ticks.max(300); + } + let fire = crate::motion::environment::fire_contact(world, registry, self.bounds()) > 0.0; + if (fire || lava) && !self.invisible && !self.marker { + if self.fire_ticks > 0 { + self.health -= 0.15; + } else { + self.fire_ticks = 100; + } + } + self.health > 0.5 + } /// EntityType.ARMOR_STAND dimensions (0.5 x 1.975, half for small). pub fn bounds(&self) -> Aabb { let s = if self.small { 0.5 } else { 1.0 }; @@ -495,3 +609,87 @@ impl ArmorStand { self.velocity = v; } } + +#[cfg(test)] +mod fire_environment_tests { + use super::*; + #[test] + fn ordinary_items_burn_but_native_netherite_resists_lava() { + let root = std::path::Path::new(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 = BlockFacts::load(&root, assets.registry).unwrap(); + let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap(); + let mut world = World::test_scene(&assets, 3).unwrap(); + let at = Vec3::new(20.5, 4.0, 20.5); + world + .set( + 20, + 4, + 20, + assets.registry.default_state("minecraft:lava").unwrap(), + ) + .unwrap(); + let make = |id: &str| ItemEntity { + id: 1, + stack: ItemStack { + item: std::sync::Arc::from(id), + count: 1, + damage: 0, + extra: None, + }, + health: 5, + fire_ticks: 0, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: false, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + }; + let mut wood = make("minecraft:oak_planks"); + let mut metal = make("minecraft:netherite_ingot"); + let first = wood.environment_tick(&world, &facts, assets.registry, &items); + assert!(first.alive && first.lava_hurt); + assert!( + !first.should_play_lava_hurt_sound(1), + "ordinary entry damage must not repeat the burn sound" + ); + assert!(first.should_play_lava_hurt_sound(10)); + assert!( + wood.fire_ticks > 0, + "lava contact must ignite dropped items" + ); + let last = wood.environment_tick(&world, &facts, assets.registry, &items); + assert!( + !last.alive && last.lava_hurt, + "lethal lava damage still emits burn sound" + ); + assert!( + last.should_play_lava_hurt_sound(2), + "the lethal hit must always play the sound" + ); + for _ in 0..40 { + let result = metal.environment_tick(&world, &facts, assets.registry, &items); + assert!(result.alive && !result.lava_hurt); + assert!(!result.should_play_lava_hurt_sound(10)); + } + assert_eq!(metal.health, 5); + world + .set( + 20, + 4, + 20, + assets.registry.default_state("minecraft:fire").unwrap(), + ) + .unwrap(); + let mut burning = make("minecraft:oak_planks"); + let result = burning.environment_tick(&world, &facts, assets.registry, &items); + assert!(result.alive && !result.lava_hurt); + assert!(burning.fire_ticks > 0); + } +} diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 64cbe15ba..3972ce172 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -98,6 +98,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { }; let mut tag = base.tag(raw); for (key, value) in [ + ( + "Fire", + Tag::Short(m.fire_ticks.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16), + ), + ("Air", Tag::Short(m.air as i16)), ("Health", Tag::Float(m.health.max(0.0).to_bits())), ( "HurtTime", @@ -324,6 +329,20 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { crate::mobs::villager::write_nbt(m, map); } "minecraft:wandering_trader" => put_offers(map, m), + "minecraft:axolotl" => { + if let Some(ttl) = crate::mobs::animal_brain::hunting_cooldown(m) { + map.insert( + "Brain".into(), + Tag::compound([( + "memories", + Tag::compound([( + "minecraft:has_hunting_cooldown", + Tag::compound([("value", Tag::Byte(1)), ("ttl", Tag::Long(ttl))]), + )]), + )]), + ); + } + } "minecraft:allay" => { // InventoryCarrier: the fetched stack; the liked player memory. let mut inv = Vec::new(); @@ -710,6 +729,17 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } crate::mobs::zombie_villager::read_nbt(&mut m, tag); } + if m.species() == crate::mobs::Species::Axolotl + && let Some(memory) = tag + .get("Brain") + .and_then(|b| b.get("memories")) + .and_then(|b| b.get("minecraft:has_hunting_cooldown")) + && let Some(ttl) = number(memory.get("ttl")) + { + crate::mobs::animal_brain::set_hunting_cooldown(&mut m, ttl); + } + m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; + m.air = number(tag.get("Air")).unwrap_or(300) as i32; if m.species() == crate::mobs::Species::Allay { if let Some(Tag::List(inv)) = tag.get("Inventory") && let Some(first) = inv.first() @@ -853,6 +883,8 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option) -> } else if let Tag::Compound(map) = &mut tag { map.remove(&"Marker".into()); } - if let Tag::Compound(map) = &tag - && !map.contains_key(&horizon_world::nbt::JavaString::from("Health")) - { - put(&mut tag, "Health", Tag::Float(20f32.to_bits())); - } + put(&mut tag, "Health", Tag::Float(a.health.to_bits())); + put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16)); // LivingEntity.addAdditionalSaveData and ArmorStand's own fields. if let Tag::Compound(map) = &mut tag { for (key, value) in [ @@ -1170,6 +1199,8 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) -> pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option { let mut a = ArmorStand::new(id, position(tag)?, rotation(tag)[0]); a.velocity = motion(tag); + a.health = float(tag.get("Health")).unwrap_or(20.0) as f32; + a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; if let Some(eq) = tag.get("equipment") { for (i, slot) in ArmorStand::SLOTS.iter().enumerate() { a.equipment[i] = eq.get(slot).and_then(item_from_nbt); @@ -1421,6 +1452,8 @@ mod tests { #[test] fn item_entities_round_trip() { let e = ItemEntity { + health: 5, + fire_ticks: 0, id: 7, stack: ItemStack { item: Arc::from("minecraft:diamond_pickaxe"), diff --git a/crates/horizon-client/src/fire_render.rs b/crates/horizon-client/src/fire_render.rs new file mode 100644 index 000000000..c3a9f6a92 --- /dev/null +++ b/crates/horizon-client/src/fire_render.rs @@ -0,0 +1,106 @@ +//! Animated burning-entity flames; the first-person overlay uses screen_effects. +use crate::{hud::Rect, mesher::Vertex}; +use std::collections::HashMap; + +#[allow(clippy::too_many_arguments)] +pub fn flames( + position: [f64; 3], + width: f32, + height: f32, + camera: glam::DVec3, + yaw: f32, + sprites: &HashMap, + scene_light: u8, + out: &mut Vec, +) { + let (Some(a), Some(b)) = (sprites.get("block/fire_0"), sprites.get("block/fire_1")) else { + return; + }; + let scale = width * 1.4; + if scale <= 0.0 { + return; + } + let origin = glam::DVec3::from(position) - camera; + let rotation = glam::Mat3::from_rotation_y(std::f32::consts::PI - yaw.to_radians()); + let mut remaining = height / scale; + let mut half = 0.5f32; + let mut y = 0.0f32; + let mut z = 0.3 - (remaining as i32) as f32 * 0.02; + let mut index = 0; + while remaining > 0.0 { + let r = if index % 2 == 0 { a } else { b }; + let (u0, u1) = if (index / 2) % 2 == 0 { + (r.u0, r.u1) + } else { + (r.u1, r.u0) + }; + for (p, uv) in [ + ([-half, y, z], [u0, r.v1]), + ([half, y, z], [u1, r.v1]), + ([half, y + 1.4, z], [u1, r.v0]), + ([-half, y + 1.4, z], [u0, r.v0]), + ] { + let p = origin.as_vec3() + rotation * (glam::Vec3::from(p) * scale); + out.push(Vertex { + pos: p.to_array(), + uv, + layer: 0, + color: 0xffff_ffff, + light: 0xf000 | (u32::from(scene_light >> 4) * 16), + normal: [0; 4], + }); + } + remaining -= 0.45; + y += 0.45; + half *= 0.9; + z -= 0.03; + index += 1; + } +} + +#[cfg(test)] +mod tests { + #[test] + fn flames_cover_entity_height_and_alternate_animated_sprites() { + let rect = |u0| super::Rect { + u0, + v0: 0.0, + u1: u0 + 0.1, + v1: 0.1, + w: 16, + h: 16, + }; + let sprites = super::HashMap::from([ + ("block/fire_0".into(), rect(0.0)), + ("block/fire_1".into(), rect(0.5)), + ]); + let mut out = Vec::new(); + super::flames( + [0.0; 3], + 0.6, + 1.8, + glam::DVec3::ZERO, + 0.0, + &sprites, + 0, + &mut out, + ); + assert_eq!(out.len() % 4, 0); + assert!( + out[0].pos[2] < 0.0, + "billboard depth bias must face the camera" + ); + assert!( + out.iter().all(|v| v.light == 0xf000), + "fire forces block light to 15 but preserves scene sky light" + ); + assert!(out.len() >= 20); + assert!(out.iter().any(|v| v.pos[1] >= 1.8)); + assert!( + out.iter().all(|v| v.layer == 0), + "flames must not use the breaking-cracks UV-remap material" + ); + assert!(out[..4].iter().all(|v| v.uv[0] <= 0.1)); + assert!(out[4..8].iter().all(|v| v.uv[0] >= 0.5)); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 590ff07c0..f85540c6d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1162,6 +1162,8 @@ impl Game<'_> { // ItemEntity.bobOffs comes from the entity's own random, not the level's. let bob = self.particles.random().next_float() * std::f32::consts::PI * 2.0; self.dropped.push(ItemEntity { + health: 5, + fire_ticks: 0, id: self.next_entity, stack, position: p, @@ -1255,10 +1257,32 @@ impl Game<'_> { // ServerLevel.tick: only entities in entity-ticking chunks tick. let ticking = self.entity_ticking_area(); items.retain_mut(|item| { - !ticking( + if !ticking( item.position.x.floor() as i32, item.position.z.floor() as i32, - ) || item.tick(&self.world, &self.res.facts, self.collision) + ) { + return true; + } + if !item.tick(&self.world, &self.res.facts, self.collision) { + return false; + } + let environment = item.environment_tick( + &self.world, + &self.res.facts, + self.res.assets.registry, + &self.res.items, + ); + // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. + if environment.should_play_lava_hurt_sound(item.age) { + let pitch = 2.0 + self.world.random.next_float() * 0.4; + self.audio.play( + "minecraft:entity.generic.burn", + Some([item.position.x, item.position.y, item.position.z]), + 0.4, + pitch, + ); + } + environment.alive }); let Some(p) = self.player.as_ref() else { self.dropped = items; @@ -1569,7 +1593,13 @@ impl Game<'_> { _ => None, }; if let Some((name, volume)) = sound { - self.audio.play(name, c, volume, 1.0); + let pitch = if id == 1009 { + 2.6 + (self.world.random.next_float() - self.world.random.next_float()) + * 0.8 + } else { + 1.0 + }; + self.audio.play(name, c, volume, pitch); } } LevelEvent::Sound { @@ -2568,10 +2598,25 @@ impl Game<'_> { }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; + player.fire_ticks = self + .level + .player_extra + .as_ref() + .and_then(|t| horizon_client::save::number(t.get("Fire"))) + .unwrap_or(0) as i32; + player.air = self + .level + .player_extra + .as_ref() + .and_then(|t| horizon_client::save::number(t.get("Air"))) + .unwrap_or(300) as i32; let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; player.invulnerable = self.creative || spectator; player.spectator = spectator; + player.respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { @@ -2671,6 +2716,9 @@ impl Game<'_> { player.auto_jump_enabled = self.settings.auto_jump; player.invulnerable = self.creative || spectator; player.spectator = spectator; + player.respiration = self.armor[0] + .as_ref() + .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { @@ -2833,7 +2881,6 @@ impl Game<'_> { /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { horizon_client::spans::time("tick_effects", || self.tick_effects()); - horizon_client::spans::time("tick_burning", || self.tick_burning()); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); // The player's digging comes in with its packets, before the level @@ -3167,8 +3214,7 @@ impl Game<'_> { hunger: effects.get("hunger").is_some(), hardcore: self.level.hardcore, damage_cooldown: p.health.hurt.cooldown > 0, - // Horizon does not track the player's air supply yet. - air: 300, + air: p.air, max_air: 300, under_water, vehicle_hearts, @@ -4342,6 +4388,89 @@ impl Game<'_> { /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec { let mut out = Vec::new(); + let fire_yaw = if self.camera_type == perspective::CameraType::ThirdPersonFront { + self.yaw + 180.0 + } else { + self.yaw + }; + for m in &self.mobs { + if m.fire_ticks > 0 && !m.removed { + let at = m.previous.lerp(m.position, alpha); + horizon_client::fire_render::flames( + [at.x, at.y, at.z], + m.width(), + m.height(), + camera, + fire_yaw, + &self.res.atlas.sprites, + self.world.light( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ), + &mut out, + ); + } + } + if !self.camera_type.first_person() + && let Some(p) = &self.player + && p.fire_ticks > 0 + && !p.spectator + { + let feet = self.previous_position.lerp(p.position, alpha); + horizon_client::fire_render::flames( + [feet.x, feet.y, feet.z], + p.dimensions.width, + p.dimensions.height, + camera, + fire_yaw, + &self.res.atlas.sprites, + self.world.light( + feet.x.floor() as i32, + feet.y.floor() as i32, + feet.z.floor() as i32, + ), + &mut out, + ); + } + for item in &self.dropped { + if item.fire_ticks > 0 { + let at = item.previous.lerp(item.position, alpha); + horizon_client::fire_render::flames( + [at.x, at.y, at.z], + 0.25, + 0.25, + camera, + fire_yaw, + &self.res.atlas.sprites, + self.world.light( + at.x.floor() as i32, + at.y.floor() as i32, + at.z.floor() as i32, + ), + &mut out, + ); + } + } + for stand in &self.armor_stands { + if stand.fire_ticks > 0 && !stand.marker { + let scale = if stand.small { 0.5 } else { 1.0 }; + horizon_client::fire_render::flames( + [stand.position.x, stand.position.y, stand.position.z], + 0.5 * scale, + 1.975 * scale, + camera, + fire_yaw, + &self.res.atlas.sprites, + self.world.light( + stand.position.x.floor() as i32, + stand.position.y.floor() as i32, + stand.position.z.floor() as i32, + ), + &mut out, + ); + } + } // `ItemEntityRenderer`. self.dropped_item_geometry(camera, alpha, &mut out); // Mobs and their projectiles. @@ -5191,6 +5320,8 @@ impl Game<'_> { self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); + self.adv = Default::default(); + self.stats = Default::default(); // RandomSequences: the world's data/minecraft/random_sequences.dat. self.rand_sequences = horizon_client::save::read_dat(&save_root.join("data/minecraft/random_sequences.dat")) @@ -5223,6 +5354,7 @@ impl Game<'_> { let (mut streaming, save) = self.make_streaming(&save_root, dim, level.seed)?; streaming.radius = self.settings.render_distance; let mut world = World::new(self.res.facts.air, level.seed); + world.fast_lava = dim == Dim::Nether; world.game_time = level.time; world.day_time = self.options.time.unwrap_or(level.day_time); world.weather = level.weather; @@ -5452,6 +5584,7 @@ impl Game<'_> { let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; let mut world = World::new(self.res.facts.air, self.level.seed); + world.fast_lava = target == Dim::Nether; world.game_time = self.world.game_time; world.day_time = self.world.day_time; world.weather = self.world.weather; @@ -6218,6 +6351,19 @@ impl Game<'_> { } if let Some(kind) = mob { if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) { + if kind == "axolotl" + && let Some(data) = stack.data().and_then(|d| { + d.other + .iter() + .find(|(key, _)| key == "minecraft:bucket_entity_data") + .map(|(_, v)| v) + }) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) + && let Some(horizon_world::nbt::Tag::Long(ticks)) = + data.get("HuntingCooldown") + { + horizon_client::mobs::animal_brain::set_hunting_cooldown(m, *ticks); + } self.mob_placed(id)?; } self.post_block_game_event( @@ -6227,7 +6373,7 @@ impl Game<'_> { None, ); } - self.trigger_item("minecraft:placed_block", stack); + self.trigger_block("minecraft:placed_block", target, stack); if !self.creative { self.inventory[self.selected] = Some(ItemStack::new("minecraft:bucket", 1)); } @@ -7171,6 +7317,19 @@ impl Game<'_> { if let Some(p) = &self.player { level.position = Some([p.position.x, p.position.y, p.position.z]); level.health = p.health.health(); + let extra = level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + map.insert( + "Fire".into(), + horizon_world::nbt::Tag::Short( + p.fire_ticks.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16, + ), + ); + map.insert("Air".into(), horizon_world::nbt::Tag::Short(p.air as i16)); + } + level.food = p.health.food.food; level.saturation = p.health.food.saturation; } @@ -7827,7 +7986,16 @@ impl ApplicationHandler for Game<'_> { ), (&self.res.forcefield.2, self.res.forcefield.0), )) { - Ok(r) => self.renderer = Some(r), + Ok(mut r) => { + r.hud.fire_animations = self + .res + .atlas + .fire_animations + .iter() + .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .collect(); + self.renderer = Some(r); + } Err(e) => { self.error = Some(e.to_string()); event_loop.exit(); @@ -8352,6 +8520,7 @@ impl ApplicationHandler for Game<'_> { } _ => {} } + Ok(()) })(); if let Err(e) = result { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 3faeccf07..6bfb53956 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -366,8 +366,25 @@ impl Game<'_> { world: &self.world, binding: self.collision, }; - for a in &mut self.armor_stands { + let mut dead = Vec::new(); + for (i, a) in self.armor_stands.iter_mut().enumerate() { a.tick(&mut scene); + if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) { + dead.push(i); + } + } + for i in dead.into_iter().rev() { + let a = self.armor_stands.remove(i); + let at = [a.position.x, a.position.y, a.position.z]; + for stack in a.equipment.into_iter().flatten() { + self.spawn_item(stack, at, [0.0; 3], 10); + } + self.audio + .play("minecraft:entity.armor_stand.break", Some(at), 1.0, 1.0); + self.world.modified.insert(( + a.position.x.floor() as i32 >> 4, + a.position.z.floor() as i32 >> 4, + )); } } /// ArmorStandRenderer: the stand with its default pose, then armor layers. diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index fe71cf173..ec140faa5 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -28,7 +28,6 @@ use std::sync::Arc; pub(super) struct Creatures { pub projectiles: Vec, /// Player status effects applied by mobs: (effect, ticks left, amplifier). - pub player_fire: i32, pub pearl_cooldown: u32, /// The wind charge's use cooldown (ticks). pub wind_cooldown: u32, @@ -908,6 +907,26 @@ impl Game<'_> { } } MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount), + MobEvent::AxolotlSupportPlayer => { + let previous = self + .potions + .effects + .get("regeneration") + .map_or(0, |e| e.duration); + if (0..=2399).contains(&previous) { + self.potions + .effects + .add(horizon_client::effects::EffectInstance::new( + "regeneration", + (previous + 100).min(2400), + 0, + )); + } + self.potions + .effects + .list + .retain(|e| e.id != "mining_fatigue"); + } MobEvent::EffectPlayer { effect, ticks, @@ -917,9 +936,10 @@ impl Game<'_> { } MobEvent::Ignite { target, seconds } => match target { Who::Player => { - if !self.creative { - self.creatures.player_fire = - self.creatures.player_fire.max(seconds * 20); + if !self.creative + && let Some(p) = self.player.as_mut() + { + p.fire_ticks = p.fire_ticks.max(seconds * 20); } } Who::Mob(id) => { @@ -1291,24 +1311,6 @@ impl Game<'_> { } /// Burning applied to the player by mobs. fn tick_player_effects(&mut self) { - let in_water = self.player.as_ref().is_some_and(|p| { - let (x, y, z) = ( - p.position.x.floor() as i32, - p.position.y.floor() as i32, - p.position.z.floor() as i32, - ); - self.res.facts.get(self.world.block(x, y, z)).fluid == Fluid::Water - }); - if self.creatures.player_fire > 0 { - if in_water { - self.creatures.player_fire = 0; - } else { - if self.creatures.player_fire % 20 == 0 { - self.hurt_player_by("minecraft:on_fire", 1.0); - } - self.creatures.player_fire -= 1; - } - } self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1); if self.creatures.pearl_cooldown > 0 { self.creatures.pearl_cooldown -= 1; @@ -1583,7 +1585,9 @@ impl Game<'_> { Hit::Entity { who, .. } => match who { Who::Player => { if !self.creative { - self.creatures.player_fire = self.creatures.player_fire.max(100); + if let Some(p) = self.player.as_mut() { + p.fire_ticks = p.fire_ticks.max(100); + } self.mob_hits_player( 5.0, [p.previous.x, p.previous.y, p.previous.z], diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 88268379a..e4b8e2fe5 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -159,32 +159,13 @@ impl Game<'_> { } } } - if ignite > 0.0 { - // Entity.igniteForSeconds; mobs burn for 1 damage per second. - let id = self.mobs[mob].id; - self.potions.burning.retain(|(m, _)| *m != id); - self.potions.burning.push((id, (ignite * 20.0) as i32)); + if ignite > 0.0 + && let Some(m) = self.mobs.get_mut(mob) + && !m.kind.flags.fire_immune + { + m.fire_ticks = m.fire_ticks.max((ignite * 20.0) as i32); } } - /// Burning mobs (fire aspect): one damage every 20 ticks, flame particles. - pub(super) fn tick_burning(&mut self) { - let mut burning = std::mem::take(&mut self.potions.burning); - burning.retain_mut(|(id, ticks)| { - *ticks -= 1; - let Some(m) = self.mobs.iter_mut().find(|m| m.id == *id && m.alive()) else { - return false; - }; - if *ticks % 20 == 0 { - let at = [m.position.x, m.position.y, m.position.z]; - if m.hurt(1.0, None, &mut self.world.random) { - self.last_hurt_by_player.insert(*id); - let _ = at; - } - } - *ticks > 0 - }); - self.potions.burning = burning; - } /// Thorns on worn armor when a mob at `from` hits the player. pub(super) fn thorns(&mut self, from: [f64; 3]) { let attacker = self diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index f85bebd28..3c1075f5c 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -322,8 +322,13 @@ impl Game<'_> { if let Some(p) = self.player.as_ref().map(|p| p.position) && inside([p.x, p.y, p.z]) { - let fire = &mut self.creatures.player_fire; - *fire = if *fire + 1 == 0 { 160 } else { *fire + 1 }; + if let Some(p) = self.player.as_mut() { + p.fire_ticks = if p.fire_ticks + 1 == 0 { + 160 + } else { + p.fire_ticks + 1 + }; + } self.hurt_player_by("minecraft:lightning_bolt", 5.0); } // Dropped items burn up (ItemEntity health 5), save fire-resistant ones. diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 8dcd2baa9..e9e7bd95e 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -57,8 +57,7 @@ pub(super) struct PotionState { applied: Vec<(&'static str, &'static str, f64, &'static str)>, /// Armor the protection table was computed for. protection_for: Option>>, - /// Mobs set on fire by fire aspect: (mob id, ticks left). - pub(super) burning: Vec<(u32, i32)>, + /// Enchantment attribute modifiers on the player: (attribute, id, amount, operation). pub(super) enchant_modifiers: Vec<(String, String, f64, String)>, } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3fc55d0b3..d5cf21652 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1502,6 +1502,8 @@ impl Game<'_> { let at = Vec3::new(p[0], p[1], p[2]); let bob_offset = self.world.random.next_float() * std::f32::consts::PI * 2.0; self.dropped.push(ItemEntity { + health: 5, + fire_ticks: 0, id: id as u32, stack, position: at, diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index dd45ef053..18adda60a 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -176,7 +176,9 @@ impl Game<'_> { partial, block_overlay, water, - on_fire: false, + on_fire: self.camera_type.first_person() + && !self.spectator() + && self.player.as_ref().is_some_and(|p| p.fire_ticks > 0), gui_overlays: &gui_overlays, }) } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index cceedd4c5..2cdb2924b 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1697,16 +1697,17 @@ impl Renderer { ); } fn animate(&mut self, tick: u64) { + let sprite_size = self.sprite_texture.width(); for (animation, previous) in &mut self.animations { let frame = animation.frame(tick); if frame == *previous { continue; } *previous = frame; - let (mips, levels) = mip_chain(animation.pixels(frame), 16, 1); + let (mips, levels) = mip_chain(animation.pixels(frame), sprite_size, 1); let mut offset = 0; for level in 0..levels.min(self.mip_levels) { - let size = 16 >> level; + let size = sprite_size >> level; let bytes = (size * size * 4) as usize; self.queue.write_texture( wgpu::TexelCopyTextureInfo { @@ -1772,6 +1773,7 @@ impl Renderer { }; if self.animated_textures { self.animate(frame.ticks); + self.hud.animate_fire(&self.queue, frame.ticks); } self.update_lightmap( &frame.sky, diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 6161160dd..091acf822 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -23,6 +23,7 @@ pub struct HudAtlas { pub width: u32, pub height: u32, pub sprites: HashMap, + pub fire_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, @@ -247,6 +248,35 @@ 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 image = animation.resized_pixels(animation.frame(0), rect.w, rect.h); + let x = (rect.u0 * width as f32).round() as usize; + let y = (rect.v0 * height as f32).round() as usize; + for row in 0..rect.h as usize { + let dst = ((y + row) * width as usize + x) * 4; + let src = row * rect.w as usize * 4; + pixels[dst..dst + rect.w as usize * 4] + .copy_from_slice(&image[src..src + rect.w as usize * 4]); + } + fire_animations.push((rect, animation)); + } + } + } let white = sprites["horizon/white"]; let font = crate::font::Font::load( root, @@ -261,6 +291,7 @@ impl HudAtlas { width, height, sprites, + fire_animations, font, white, }) @@ -592,6 +623,7 @@ struct HudUniform { size: [f32; 4], } pub struct HudRenderer { + pub fire_animations: Vec<(Rect, crate::sprites::SpriteAnimation, usize)>, /// The shared atlas texture, for run-time glyph uploads. pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, @@ -713,6 +745,7 @@ impl HudRenderer { }); Ok(Self { atlas_texture: None, + fire_animations: Vec::new(), pipeline, group, uniform, @@ -720,6 +753,42 @@ impl HudRenderer { capacity, }) } + pub fn animate_fire(&mut self, queue: &wgpu::Queue, tick: u64) { + 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 { + continue; + } + let pixels = animation.resized_pixels(frame, rect.w, rect.h); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture, + mip_level: 0, + origin: wgpu::Origin3d { + x: (rect.u0 * texture.width() as f32).round() as u32, + y: (rect.v0 * texture.height() as f32).round() as u32, + z: 0, + }, + aspect: wgpu::TextureAspect::All, + }, + &pixels, + wgpu::TexelCopyBufferLayout { + offset: 0, + bytes_per_row: Some(rect.w * 4), + rows_per_image: Some(rect.h), + }, + wgpu::Extent3d { + width: rect.w, + height: rect.h, + depth_or_array_layers: 1, + }, + ); + *previous = frame; + } + } pub fn draw( &mut self, device: &wgpu::Device, diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 29385b53e..877869c88 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -20,6 +20,7 @@ pub struct ToolRule { } #[derive(Clone, Debug)] pub struct ItemInfo { + pub fire_resistant: bool, pub id: Arc, pub max_stack: u32, pub max_damage: u32, @@ -307,6 +308,26 @@ fn entity_spec(tags: &HashMap>, spec: &str) -> HashSet bool { + if let Some(data) = stack.data() + && let Some((_, v)) = data + .other + .iter() + .find(|(key, _)| key == "minecraft:damage_resistant") + { + return match v.get("types") { + Some(horizon_world::nbt::Tag::String(tag)) => { + tag.to_string().is_ok_and(|id|id=="#minecraft:is_fire" || id==source) + } + Some(horizon_world::nbt::Tag::List(tags)) => tags.iter().any( + |t| matches!(t,horizon_world::nbt::Tag::String(id) if id.to_string().is_ok_and(|id|id==source)), + ), + _ => false, + }; + } + self.get(&stack.item).is_some_and(|i| i.fire_resistant) + } + pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result { let mut block_for_item: HashMap<&str, BlockStateId> = HashMap::new(); for (i, s) in facts.states.iter().enumerate() { @@ -370,6 +391,8 @@ impl Items { items.insert( id.clone(), ItemInfo { + fire_resistant: c["minecraft:damage_resistant"]["types"].as_str() + == Some("#minecraft:is_fire"), id: id.clone(), max_stack: c["minecraft:max_stack_size"].as_u64().unwrap_or(64) as u32, max_damage: c["minecraft:max_damage"].as_u64().unwrap_or(0) as u32, diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5c753c09..7002170aa 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -44,6 +44,7 @@ pub mod entity_nbt; pub mod environment; pub mod fast_hash; pub mod fastutil_order; +pub mod fire_render; pub mod first_person; pub mod flatgen; pub mod fog; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 96dcf9949..1ef8e5de9 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -10,6 +10,7 @@ pub mod allay; pub mod anim; pub mod animal_brain; pub mod aquatic; +pub mod axolotl; pub mod body_anim; pub mod brain; pub mod breeze; @@ -701,6 +702,7 @@ pub struct Extra { pub villager: Option>, /// The sniffer's and the ghastling's brain. pub animal_brain: Option>, + pub axolotl: axolotl::Animation, /// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`). pub mount: Option, pub rider: Option, @@ -937,6 +939,7 @@ pub enum MobEvent { amount: u32, }, /// Apply an effect to the player (witch potions, bee stings, cave spider poison). + AxolotlSupportPlayer, EffectPlayer { effect: &'static str, ticks: i32, @@ -1093,6 +1096,9 @@ pub struct SpawnSetup { /// A snapshot of another entity mobs can see this tick. #[derive(Clone, Debug)] pub struct Seen { + pub in_water: bool, + pub playing_dead: bool, + pub last_damage: Option, pub id: u32, pub species: Species, pub position: Vec3, @@ -1151,6 +1157,9 @@ impl Mob { let m = self; let villager = m.species() == Species::Villager; Seen { + in_water: self.fluids.in_water, + playing_dead: axolotl::is_playing_dead(self), + last_damage: self.last_damage.map(|(d, _)| d), id: m.id, species: m.species(), position: m.position, @@ -1502,6 +1511,7 @@ impl Mob { .fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y)) } pub fn damage(&mut self, amount: f32, source: Damage) -> bool { + axolotl::before_damage(self, amount, &source); raider::note_hurt(self); if !self.alive() || self.removed || self.invulnerable_flag { return false; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0338c6b1..6f010338f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -126,7 +126,8 @@ pub fn family(s: Species) -> Family { | S::Salmon | S::TropicalFish | S::Pufferfish - | S::Dolphin => Family::Aquatic, + | S::Dolphin + | S::Axolotl => Family::Aquatic, S::Giant => Family::Inert, S::Witch => Family::Witch, S::Wolf | S::Cat => Family::Tame, @@ -369,6 +370,7 @@ pub fn tick( } events.append(&mut m.outbox); m.update_walk_animation(); + super::axolotl::tick_animation(m); m.anim.end_tick(m.ai.swinging); tick_swing(m); if m.species() == Species::CopperGolem { @@ -397,6 +399,12 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.fluids.in_water { m.fall_distance = 0.0; } + let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds()); + if fire > 0.0 && !m.kind.flags.fire_immune { + m.fire_ticks = + crate::motion::environment::ignite_contact(m.fire_ticks, false, &mut m.random); + m.damage(fire, Damage::of(DamageKind::InFire)); + } // Fire: water extinguishes, lava ignites, burning hurts every second. if m.fluids.in_water && m.fire_ticks > 0 { m.fire_ticks = 0; @@ -413,7 +421,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } if m.fire_ticks > 0 { if m.kind.flags.fire_immune { - m.fire_ticks = (m.fire_ticks - 4).max(0); + m.fire_ticks = 0; } else { if m.fire_ticks % 20 == 0 && !m.fluids.in_lava { m.damage(1.0, Damage::of(DamageKind::OnFire)); @@ -496,6 +504,9 @@ pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec) { play_ambient(m, w, events); } fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { + if super::axolotl::is_playing_dead(m) { + return; + } let sound = match m.species() { // Warden.getAmbientSound: by anger, silent while roaring or digging. Species::Warden => match super::warden::ambient_sound(m) { @@ -813,6 +824,7 @@ fn server_ai_step( if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() || m.species() == Species::CopperGolem + || m.species() == Species::Axolotl { super::animal_brain::tick(m, w, level_random, events); } @@ -824,8 +836,10 @@ fn server_ai_step( m.ai.jumping = false; return; } - m.move_control_tick(w, events); - m.look_control_tick(); + if !super::axolotl::is_playing_dead(m) { + m.move_control_tick(w, events); + m.look_control_tick(); + } m.jump_control_tick(); } fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { @@ -1352,3 +1366,12 @@ pub fn swim_sound(m: &Mob) -> &'static str { _ => "entity.generic.swim", } } + +#[cfg(test)] +mod bucket_axolotl_tests { + use super::*; + #[test] + fn bucket_axolotl_uses_aquatic_not_generic_land_ai() { + assert_eq!(family(Species::Axolotl), Family::Aquatic); + } +} diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 00650fcf3..e0bc6c0a8 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -194,11 +194,21 @@ pub struct Memories { pub sniff_cooldown: Slot<()>, pub gaze_cooldown_ticks: Slot, pub transport_items_cooldown_ticks: Slot, + pub nearest_attackable: Slot, + pub attack_target: Slot, + pub attack_cooling_down: Slot, + pub hunting_cooldown: Slot, + pub play_dead_ticks: Slot, pub visited_block_positions: Slot>, pub unreachable_transport_block_positions: Slot>, } impl Memories { fn tick(&mut self) { + self.nearest_attackable.tick(); + self.attack_target.tick(); + self.attack_cooling_down.tick(); + self.hunting_cooldown.tick(); + self.play_dead_ticks.tick(); self.mobs.tick(); self.visible_mobs.tick(); self.nearest_players.tick(); @@ -231,6 +241,8 @@ impl Memories { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Act { Core, + Fight, + PlayDead, Idle, Sniff, Dig, @@ -240,6 +252,8 @@ impl Act { pub fn name(self) -> &'static str { match self { Act::Core => "core", + Act::Fight => "fight", + Act::PlayDead => "play_dead", Act::Idle => "idle", Act::Sniff => "sniff", Act::Dig => "dig", @@ -251,6 +265,7 @@ impl Act { /// Which brain. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Kind { + Axolotl, Sniffer, /// A happy ghast (the brain ticks while it is a ghastling). Ghastling, @@ -261,6 +276,8 @@ pub enum Kind { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Sensor { Living, + AxolotlAttackables, + AdultSameType, HurtBy, Players, Tempting, @@ -270,6 +287,13 @@ impl Kind { /// `BRAIN_PROVIDER`'s sensors, in order (all scan every 20 ticks). fn sensors(self) -> &'static [Sensor] { match self { + Kind::Axolotl => &[ + Sensor::Living, + Sensor::AdultSameType, + Sensor::HurtBy, + Sensor::AxolotlAttackables, + Sensor::Tempting, + ], Kind::Sniffer => &[ Sensor::Living, Sensor::HurtBy, @@ -322,7 +346,11 @@ pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { /// The brain kind a mob has, if any. pub fn kind_of(m: &Mob) -> Option { - match m.species() { + kind_for_species(m.species()) +} +fn kind_for_species(species: Species) -> Option { + match species { + Species::Axolotl => Some(Kind::Axolotl), Species::Sniffer => Some(Kind::Sniffer), // Every happy ghast has the brain; only the ghastling's ticks. Species::HappyGhast => Some(Kind::Ghastling), @@ -353,6 +381,7 @@ pub fn init(m: &mut Mob, shuffle_seed: i64) { list: Vec::new(), }; b.list = match kind { + Kind::Axolotl => axolotl_package(shuffle_seed), Kind::Sniffer => sniffer_package(shuffle_seed), Kind::Ghastling => ghastling_package(shuffle_seed), Kind::CopperGolem => copper_golem_package(shuffle_seed), @@ -399,7 +428,16 @@ pub fn set_breed_partner(m: &mut Mob, partner: u32) { } let who = Who::Mob(partner); mem(m).breed_target.set(who); - lock_gaze_and_walk(m, who, 1.0, 2); + lock_gaze_and_walk( + m, + who, + if m.species() == Species::Axolotl { + 0.2 + } else { + 1.0 + }, + 2, + ); } /// `AnimalMakeLove.tick` after the birth: the partner forgets this mob. @@ -413,7 +451,16 @@ pub fn lock_gaze(m: &mut Mob, partner: u32) { if m.extra.animal_brain.is_none() { return; } - lock_gaze_and_walk(m, Who::Mob(partner), 1.0, 2); + lock_gaze_and_walk( + m, + Who::Mob(partner), + if m.species() == Species::Axolotl { + 0.2 + } else { + 1.0 + }, + 2, + ); } /// What behaviours read and emit during a brain tick. @@ -457,6 +504,13 @@ pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec 0); + m.ai.target = mem(m).attack_target.value(); + } } /// `SnifferAi.updateActivity` / `HappyGhastAi.updateActivity`: @@ -464,10 +518,15 @@ pub fn tick(m: &mut Mob, w: &MobWorld, lr: &mut LegacyRandom, events: &mut Vec &[Act::Dig, Act::Sniff, Act::Idle], Kind::Ghastling => &[Act::Panic, Act::Idle], Kind::CopperGolem => &[Act::Idle], + Kind::Axolotl => unreachable!(), }; for &a in order { let ok = match a { @@ -484,6 +543,7 @@ fn update_activity(m: &mut Mob) { Act::Idle => b.kind != Kind::Sniffer || !mm.sniffer_digging.present(), Act::Panic => mm.is_panicking.present(), Act::Core => true, + Act::Fight | Act::PlayDead => false, }; if ok { b.activity = a; @@ -523,6 +583,16 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { } match sensor { Sensor::Living => sense_living(m, w), + Sensor::AxolotlAttackables => sense_axolotl_attackables(m, w), + Sensor::AdultSameType => { + let found = find_closest(m, w, |m, who| match who { + Who::Mob(id) => w + .seen(id) + .is_some_and(|s| !s.baby && s.species == m.species()), + _ => false, + }); + mem(m).nearest_visible_adult.set_opt(found); + } Sensor::HurtBy => sense_hurt(m, w), Sensor::Players => sense_players(m, w), Sensor::Tempting => sense_tempting(m, w), @@ -571,7 +641,10 @@ fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { } Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; - s.alive && m.distance_sqr(s.position) <= range * range && m.sees(w, who) + s.alive + && !s.playing_dead + && m.distance_sqr(s.position) <= range * range + && m.sees(w, who) } } } @@ -759,6 +832,8 @@ impl Timed { #[derive(Clone, Debug)] struct Gate { running: bool, + shuffle: bool, + try_all: bool, random: LegacyRandom, kids: Vec<(B, i32, f64)>, /// The gate's memory requirements. @@ -768,6 +843,8 @@ impl Gate { fn run_one(seed: i64, kids: Vec<(B, i32)>) -> Self { Self { running: false, + shuffle: true, + try_all: false, random: LegacyRandom::new(seed), kids: kids.into_iter().map(|(b, w)| (b, w, 0.0)).collect(), when: None, @@ -786,13 +863,15 @@ impl Gate { self.running = true; // ShufflingList.shuffle: a fresh weight for each entry in the // current order, then a stable sort. - for k in &mut self.kids { - let r = self.random.next_float(); - k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); + if self.shuffle { + for k in &mut self.kids { + let r = self.random.next_float(); + k.2 = -horizon_core::jmath::pow(f64::from(r), f64::from(1.0_f32 / k.1 as f32)); + } + self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); } - self.kids.sort_by(|a, b| a.2.total_cmp(&b.2)); for k in &mut self.kids { - if !k.0.running() && k.0.try_start(m, cx) { + if !k.0.running() && k.0.try_start(m, cx) && !self.try_all { break; } } @@ -820,6 +899,12 @@ impl Gate { #[derive(Clone, Debug)] enum B { + AxolotlAction { + action: AxolotlAction, + running: bool, + until: i64, + }, + PlayDead(Timed), Swim(Timed), /// `AnimalPanic`: flying (`AirAndWaterRandomPos`) or on land, and /// whether the sniffer's override resets its sniffing first. @@ -890,7 +975,8 @@ enum B { impl B { fn running(&self) -> bool { match self { - B::Swim(t) + B::PlayDead(t) + | B::Swim(t) | B::AnimalPanic { t, .. } | B::MoveToTargetSink { t, .. } | B::CountDownTemptation(t) @@ -908,7 +994,8 @@ impl B { | B::CountDownTransport(t) => t.running, B::Transport(x) => x.running, B::LookAtPlayerSometimes(running, _) => *running, - B::WalkToLookTarget { running, .. } + B::AxolotlAction { running, .. } + | B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) | B::Stroll { running, .. } | B::FollowAdult { running, .. } => *running, @@ -919,7 +1006,8 @@ impl B { /// cleared with the rest). fn reset(&mut self) { match self { - B::Swim(t) + B::PlayDead(t) + | B::Swim(t) | B::AnimalPanic { t, .. } | B::CountDownTemptation(t) | B::MakeLove { t, .. } @@ -952,7 +1040,8 @@ impl B { fn one_shot(&self) -> bool { matches!( self, - B::WalkToLookTarget { .. } + B::AxolotlAction { .. } + | B::WalkToLookTarget { .. } | B::LookAtPlayer(_) | B::LookAtPlayerSometimes(..) | B::Stroll { .. } @@ -961,7 +1050,8 @@ impl B { } fn set_one_shot(&mut self, on: bool) { match self { - B::WalkToLookTarget { running, .. } + B::AxolotlAction { running, .. } + | B::WalkToLookTarget { running, .. } | B::LookAtPlayer(running) | B::LookAtPlayerSometimes(running, _) | B::Stroll { running, .. } @@ -982,6 +1072,19 @@ impl B { let now = cx.now; match self { B::Gate(g) => g.try_start(m, cx), + B::PlayDead(t) => { + if !m.fluids.in_water + || !mem(m).play_dead_ticks.present() + || !mem(m).hurt_by_entity.present() + { + return false; + } + t.begin(cx); + mem(m).walk_target.clear(); + mem(m).look_target.clear(); + m.add_effect("minecraft:regeneration", 200, 0); + true + } B::Swim(t) => { if !swim_condition(m) { return false; @@ -1082,7 +1185,12 @@ impl B { partner: m.id, }); } - lock_gaze_and_walk(m, partner, 1.0, 2); + let speed = if m.species() == Species::Axolotl { + 0.2 + } else { + 1.0 + }; + lock_gaze_and_walk(m, partner, speed, 2); *spawn_at = now + 60 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); true } @@ -1196,7 +1304,8 @@ impl B { t.begin(cx); true } - B::WalkToLookTarget { .. } + B::AxolotlAction { .. } + | B::WalkToLookTarget { .. } | B::LookAtPlayer(_) | B::LookAtPlayerSometimes(..) | B::Stroll { .. } @@ -1207,6 +1316,11 @@ impl B { /// A one-shot's trigger. fn trigger(&mut self, m: &mut Mob, cx: &mut Bx) -> bool { match *self { + B::AxolotlAction { + action, + ref mut until, + .. + } => axolotl_action(m, cx, action, until), B::WalkToLookTarget { speed, close, .. } => { let mm = mem(m); if mm.walk_target.present() { @@ -1252,7 +1366,11 @@ impl B { let Some(t) = found else { return false }; // Ticker.tickDownAndCheck (UniformInt 40..80 on the level random). if *ticks == 0 { - *ticks = 40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1; + *ticks = if m.species() == Species::Axolotl { + 30 + cx.lr.next_int_bound(31).unwrap_or(0) - 1 + } else { + 40 + cx.lr.next_int_bound(41).unwrap_or(0) - 1 + }; return false; } *ticks -= 1; @@ -1265,6 +1383,9 @@ impl B { B::Stroll { fly, speed, range, .. } => { + if m.species() == Species::Axolotl && m.fluids.in_water { + return false; + } if mem(m).walk_target.present() { return false; } @@ -1295,9 +1416,24 @@ impl B { }; // closerThan(adult, 17) && !closerThan(adult, 3) let d = m.distance_sqr(at.position); - if !(3.0 * 3.0..17.0 * 17.0).contains(&d) { + let min = if m.species() == Species::Axolotl { + 5.0 + } else { + 3.0 + }; + if !(min * min..17.0 * 17.0).contains(&d) { return false; } + let speed = if m.species() == Species::Axolotl { + axolotl_speed(m, true) + } else { + 1.1 + }; + let close = if m.species() == Species::Axolotl { + 4 + cx.lr.next_int_bound(12).unwrap_or(0) + } else { + 2 + }; let mm = mem(m); mm.walk_target.set(WalkTarget { target: Tracker::Entity { @@ -1305,8 +1441,8 @@ impl B { eye: true, block_eye: true, }, - speed: 1.1, - close: 2, + speed, + close, }); mm.look_target.set(Tracker::Entity { who: adult, @@ -1327,6 +1463,12 @@ impl B { } let now = cx.now; match self { + B::AxolotlAction { .. } => {} + B::PlayDead(t) => { + if t.timed_out(now) || !m.fluids.in_water || !mem(m).play_dead_ticks.present() { + self.do_stop(m, cx); + } + } B::Gate(g) => g.tick_or_stop(m, cx), B::Swim(t) => { if t.timed_out(now) || !swim_condition(m) { @@ -1419,7 +1561,16 @@ impl B { self.do_stop(m, cx); return; } - lock_gaze_and_walk(m, partner, 1.0, 2); + lock_gaze_and_walk( + m, + partner, + if m.species() == Species::Axolotl { + 0.2 + } else { + 1.0 + }, + 2, + ); if let Who::Mob(id) = partner { cx.events.push(MobEvent::LockGaze { mob: id, @@ -1476,7 +1627,11 @@ impl B { let near = cx.w.target_info(player) .is_some_and(|t| m.distance_sqr(t.position) < close * close); - let speed = 1.25; + let speed = if m.species() == Species::Axolotl { + axolotl_speed(m, false) + } else { + 1.25 + }; let mm = mem(m); if near { mm.walk_target.clear(); @@ -1560,6 +1715,8 @@ impl B { } let now = cx.now; match self { + B::AxolotlAction { .. } => {} + B::PlayDead(t) => t.running = false, B::Gate(g) => g.do_stop(m, cx), B::Swim(t) | B::DoNothing(t) => t.running = false, B::AnimalPanic { t, .. } => { @@ -1788,6 +1945,7 @@ fn follow_temptation_close(m: &mut Mob) -> f64 { 3.5 } } + Kind::Axolotl => 2.5, Kind::Ghastling | Kind::CopperGolem => 3.0, } } @@ -1797,8 +1955,8 @@ fn can_mate_with(m: &Mob, w: &MobWorld, partner: Who) -> bool { s.species == m.species() && s.in_love && m.extra.in_love > 0 - && sniffer::can_mate_state(sniffer::state(m)) - && sniffer::can_mate_state(s.variant) + && (m.species() != Species::Sniffer + || sniffer::can_mate_state(sniffer::state(m)) && sniffer::can_mate_state(s.variant)) } fn partner_panicking(_w: &MobWorld, _partner: Who) -> bool { false @@ -2093,6 +2251,431 @@ fn move_to_target_sink(min: i32, max: i32) -> B { } } +// ---- AxolotlAi ----------------------------------------------------------- + +#[derive(Clone, Copy, Debug)] +enum AxolotlAction { + ValidateDead, + StartAttack, + StopAttack, + Chase, + Bite, + EraseAttackBreeding, + EraseDeadBreeding, + FindLiquid, + SwimStroll, + WalkFromLook, + StayWater, + StayGround, +} +fn axolotl_speed(m: &Mob, chase: bool) -> f32 { + if m.fluids.in_water { + if chase { 0.6 } else { 0.5 } + } else { + 0.15 + } +} +pub fn set_play_dead(m: &mut Mob) { + if m.extra.animal_brain.is_none() { + init(m, i64::from(m.id)); + } + mem(m).play_dead_ticks.set(super::axolotl::PLAY_DEAD_TICKS); +} +pub fn hunting_cooldown(m: &Mob) -> Option { + mem_ref(m).and_then(|mm| mm.hunting_cooldown.get().map(|_| mm.hunting_cooldown.ttl)) +} +pub fn set_hunting_cooldown(m: &mut Mob, ticks: i64) { + if m.extra.animal_brain.is_none() { + init(m, i64::from(m.id)); + } + mem(m).hunting_cooldown.set_ttl(true, ticks); +} +fn validate_play_dead(b: &mut Brain) -> bool { + let Some(ticks) = b.mem.play_dead_ticks.value() else { + return false; + }; + if ticks <= 0 { + b.mem.play_dead_ticks.clear(); + b.mem.hurt_by_entity.clear(); + b.activity = Act::Idle; + } else { + b.mem.play_dead_ticks.set(ticks - 1); + } + true +} +fn update_axolotl_activity(b: &mut Brain) { + let old = b.activity; + // PLAY_DEAD remains active until ValidatePlayDead resets to default IDLE. + if old == Act::PlayDead { + return; + } + b.activity = if b.mem.play_dead_ticks.present() { + Act::PlayDead + } else if b.mem.attack_target.present() { + Act::Fight + } else { + Act::Idle + }; + if old != b.activity && old == Act::Fight { + b.mem + .hunting_cooldown + .set_ttl(true, super::axolotl::HUNTING_COOLDOWN); + b.mem.attack_target.clear(); + } +} +fn sense_axolotl_attackables(m: &mut Mob, w: &MobWorld) { + let cooldown = mem(m).hunting_cooldown.present(); + let target = find_closest(m, w, |m, who| { + let Who::Mob(id) = who else { return false }; + let Some(s) = w.seen(id) else { return false }; + let id = format!("minecraft:{}", super::species::def(s.species).name); + super::axolotl::prey_eligible( + m.distance_sqr(s.position), + s.in_water, + w.data.entity_has("minecraft:axolotl_always_hostiles", &id), + w.data.entity_has("minecraft:axolotl_hunt_targets", &id), + cooldown, + s.alive && !s.playing_dead, + ) + }); + mem(m).nearest_attackable.set_opt(target); +} +fn axolotl_action(m: &mut Mob, cx: &mut Bx, action: AxolotlAction, until: &mut i64) -> bool { + use AxolotlAction::*; + match action { + ValidateDead => validate_play_dead(brain_mut(m)), + StartAttack => { + let mm = mem(m); + if mm.attack_target.present() || mm.breed_target.present() { + return false; + } + let Some(target) = mm.nearest_attackable.value() else { + return false; + }; + if !cx + .w + .target_info(target) + .is_some_and(|t| t.alive && !t.creative) + { + return false; + } + mem(m).attack_target.set(target); + mem(m).cant_reach_walk_target_since.clear(); + m.ai.target = Some(target); + true + } + StopAttack => { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let tired = mem(m) + .cant_reach_walk_target_since + .value() + .is_some_and(|t| cx.now - t > 200); + let valid = + cx.w.target_info(target) + .is_some_and(|t| t.alive && !t.creative) + && match target { + Who::Mob(id) => cx.w.seen(id).is_some_and(|s| !s.playing_dead), + Who::Player => true, + }; + if tired || !valid { + super::axolotl::on_stop_attacking(m, cx.w, target, cx.events); + mem(m).attack_target.clear(); + m.ai.target = None; + } + true + } + Chase => { + let Some(target) = mem(m).attack_target.value() else { + return false; + }; + let speed = axolotl_speed(m, true); + if cx + .w + .target_info(target) + .is_some_and(|t| m.within_melee_range(&t)) + && visible_test(m, cx.w, target) + { + mem(m).walk_target.clear(); + } else { + let tracker = Tracker::entity(target, true); + mem(m).look_target.set(tracker); + mem(m).walk_target.set(WalkTarget { + target: Tracker::entity(target, false), + speed, + close: 0, + }); + } + true + } + Bite => { + let mm = mem(m); + if mm.attack_cooling_down.present() { + return false; + } + let Some(target) = mm.attack_target.value() else { + return false; + }; + if !visible_test(m, cx.w, target) + || !cx + .w + .target_info(target) + .is_some_and(|t| m.within_melee_range(&t)) + { + return false; + } + mem(m).look_target.set(Tracker::entity(target, true)); + m.swing(); + super::ai::do_hurt_target( + m, + target, + &mut super::goals::Cx { + w: cx.w, + events: cx.events, + }, + ); + m.sound("entity.axolotl.attack", cx.events); + mem(m).attack_cooling_down.set_ttl(true, 20); + true + } + EraseAttackBreeding | EraseDeadBreeding => { + if !mem(m).breed_target.present() { + return false; + } + if matches!(action, EraseAttackBreeding) { + mem(m).attack_target.clear(); + } else { + mem(m).play_dead_ticks.clear(); + } + true + } + FindLiquid => { + if mem(m).walk_target.present() || mem(m).attack_target.present() { + return false; + } + let p = [ + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ]; + if cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water { + return false; + } + if cx.now < *until { + *until = cx.now + 22; + return true; + } + let mut positions = Vec::new(); + // BlockPos.withinManhattan: distance, x, y, then positive/negative z. + for distance in 0..=18i32 { + for x in -6..=6i32 { + for y in -6..=6i32 { + let z = distance - x.abs() - y.abs(); + if !(0..=6).contains(&z) { + continue; + } + positions.push([p[0] + x, p[1] + y, p[2] + z]); + if z != 0 { + positions.push([p[0] + x, p[1] + y, p[2] - z]); + } + } + } + } + let mut found = None; + for q in positions { + if (q[0] == p[0] && q[2] == p[2]) + || cx.w.fluid(q[0], q[1], q[2]) != crate::blocks::Fluid::Water + { + continue; + } + let name = cx.w.block_name(q[0], q[1], q[2]); + if name != "minecraft:water" { + continue; + } + if cx.w.block_name(q[0], q[1] + 1, q[2]).ends_with("air") { + found = Some(q); + break; + } + let v = Vec3::new( + f64::from(q[0]) + 0.5, + f64::from(q[1]) + 0.5, + f64::from(q[2]) + 0.5, + ); + if found.is_none() && m.distance_sqr(v) >= 2.25 { + found = Some(q); + } + } + if let Some(q) = found { + mem(m).look_target.set(Tracker::Block(q)); + mem(m).walk_target.set(WalkTarget { + target: Tracker::Block(q), + speed: 0.15, + close: 0, + }); + } + *until = cx.now + 40; + true + } + SwimStroll => { + if mem(m).walk_target.present() || !m.fluids.in_water { + return false; + } + let mut fallback: Option = None; + for (h, v) in [(1, 1), (3, 3), (5, 5), (6, 5), (7, 7), (10, 7)] { + let point = if let Some(p) = fallback { + let delta = + Vec3::new(p.x - m.position.x, p.y - m.position.y, p.z - m.position.z); + let length = (delta.x * delta.x + delta.y * delta.y + delta.z * delta.z).sqrt(); + let n = if length < 1.0e-5 { + Vec3::ZERO + } else { + Vec3::new(delta.x / length, delta.y / length, delta.z / length) + }; + Some(Vec3::new( + m.position.x + n.x * f64::from(h), + m.position.y + n.y * f64::from(v), + m.position.z + n.z * f64::from(h), + )) + } else { + let mut p = m.default_random_pos(cx.w, h, v); + let mut count = 0; + while let Some(q) = p { + let state = cx.w.world.block( + q[0].floor() as i32, + q[1].floor() as i32, + q[2].floor() as i32, + ); + if cx.w.data.state(state).flags & super::data::WATER != 0 || count >= 10 { + break; + } + count += 1; + p = m.default_random_pos(cx.w, h, v); + } + p.map(|q| Vec3::new(q[0], q[1], q[2])) + }; + let Some(point) = point else { break }; + let q = [ + point.x.floor() as i32, + point.y.floor() as i32, + point.z.floor() as i32, + ]; + let restricted = m.restricted(f64::from(h), q); + if cx.w.fluid(q[0], q[1], q[2]) == crate::blocks::Fluid::None || restricted { + break; + } + fallback = Some(point); + } + mem(m) + .walk_target + .set_opt(fallback.map(|p| WalkTarget::point([p.x, p.y, p.z], 0.5, 0))); + true + } + WalkFromLook => { + if mem(m).walk_target.present() { + return false; + } + let Some(t) = mem(m).look_target.value() else { + return false; + }; + let Some(p) = t.block(cx.w) else { return false }; + if (cx.w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water) != m.fluids.in_water { + return false; + } + let speed = axolotl_speed(m, false); + mem(m).walk_target.set(WalkTarget { + target: t, + speed, + close: 3, + }); + true + } + StayWater => m.fluids.in_water, + StayGround => m.on_ground, + } +} +fn axolotl_package(seed: i64) -> Vec { + use Act::*; + use AxolotlAction::*; + let e = |act, b| Entry { act, b }; + let action = |action| B::AxolotlAction { + action, + running: false, + until: 0, + }; + vec![ + // Native activity slots, merged by behavior priority. + e(Core, B::LookAtTargetSink(Timed::new(45, 90))), + e(Idle, B::LookAtPlayerSometimes(false, 0)), + e(Fight, action(StopAttack)), + e(PlayDead, B::PlayDead(Timed::new(200, 200))), + e(Core, move_to_target_sink(150, 250)), + e( + Idle, + B::MakeLove { + t: Timed::new(325, 325), + spawn_at: 0, + }, + ), + e(Fight, action(Chase)), + e(PlayDead, action(EraseDeadBreeding)), + e(Core, action(ValidateDead)), + e( + Idle, + B::Gate(Box::new(Gate::run_one( + seed, + vec![ + ( + B::FollowTemptation { + t: Timed::new(60, 60), + look_in_the_eyes: false, + }, + 1, + ), + ( + B::FollowAdult { + running: false, + player: false, + }, + 1, + ), + ], + ))), + ), + e(Fight, action(Bite)), + e(Core, B::CountDownTemptation(Timed::new(60, 60))), + e(Idle, action(StartAttack)), + e(Idle, action(FindLiquid)), + e(Fight, action(EraseAttackBreeding)), + e( + Idle, + B::Gate(Box::new(Gate { + running: false, + shuffle: false, + try_all: true, + random: horizon_core::random::LegacyRandom::new(seed), + kids: vec![ + (action(SwimStroll), 2, 0.0), + ( + B::Stroll { + running: false, + fly: false, + speed: 0.15, + range: (10, 7), + }, + 2, + 0.0, + ), + (action(WalkFromLook), 3, 0.0), + (action(StayWater), 5, 0.0), + (action(StayGround), 5, 0.0), + ], + when: Some(|mm| !mm.walk_target.present()), + })), + ), + ] +} + // ---- Debug output (the mob AI harness) ------------------------------------ fn pos(p: [i32; 3]) -> String { @@ -2134,6 +2717,16 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { }; } let n = |l: &Vec| format!("n{}", l.len()); + slot!("nearest_attackable", mm.nearest_attackable, |v: &Who| who( + *v + )); + slot!("attack_target", mm.attack_target, |v: &Who| who(*v)); + slot!("attack_cooling_down", mm.attack_cooling_down, |v: &bool| v + .to_string()); + slot!("has_hunting_cooldown", mm.hunting_cooldown, |v: &bool| v + .to_string()); + slot!("play_dead_ticks", mm.play_dead_ticks, |v: &i32| v + .to_string()); slot!("mobs", mm.mobs, n); slot!("visible_mobs", mm.visible_mobs, |_: &Visible| { "NearestVisibleLivingEntities".to_string() @@ -2219,3 +2812,55 @@ pub fn describe(m: &Mob) -> Option<(String, String)> { out.sort(); Some((acts.join("|"), out.join(" "))) } + +#[cfg(test)] +mod axolotl_parity_tests { + use super::*; + fn empty_brain() -> Brain { + Brain { + kind: Kind::Axolotl, + mem: Memories::default(), + sensors: Vec::new(), + activity: Act::Idle, + list: Vec::new(), + } + } + #[test] + fn fight_exit_sets_hunting_cooldown_and_play_dead_has_priority() { + let mut b = empty_brain(); + b.mem.attack_target.set(Who::Mob(1)); + update_axolotl_activity(&mut b); + assert_eq!(b.activity, Act::Fight); + b.mem.play_dead_ticks.set(200); + update_axolotl_activity(&mut b); + assert_eq!(b.activity, Act::PlayDead); + assert_eq!(b.mem.hunting_cooldown.ttl, 2400); + assert!(!b.mem.attack_target.present()); + for _ in 0..2400 { + b.mem.hunting_cooldown.tick(); + } + assert!(b.mem.hunting_cooldown.present()); + b.mem.hunting_cooldown.tick(); + assert!(!b.mem.hunting_cooldown.present()); + } + #[test] + fn play_dead_flag_ends_at_zero_before_memory_is_erased() { + let mut b = empty_brain(); + b.activity = Act::PlayDead; + b.mem.play_dead_ticks.set(200); + b.mem.hurt_by_entity.set(Who::Mob(7)); + for _ in 0..200 { + assert!(validate_play_dead(&mut b)); + } + assert_eq!(b.mem.play_dead_ticks.value(), Some(0)); + assert_eq!(b.activity, Act::PlayDead); + assert!(validate_play_dead(&mut b)); + assert!(!b.mem.play_dead_ticks.present()); + assert!(!b.mem.hurt_by_entity.present()); + assert_eq!(b.activity, Act::Idle); + } + #[test] + fn axolotl_has_native_activity_brain_not_fallback_goals() { + assert!(kind_for_species(Species::Axolotl).is_some()); + } +} diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 8cb1f7873..702e3740d 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -35,6 +35,19 @@ pub fn register(m: &mut Mob) { let speed = 1.0 / (m.random.next_float() + 1.0) * 0.2; m.anim.v[TENTACLE_SPEED] = speed; } + S::Axolotl => { + // Native controller scaling is essential: the base speed attribute is 1.0. + m.ai.mov.kind = MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.1, + outside: 0.5, + gravity: false, + }; + m.ai.look.kind = super::control::LookKind::SmoothSwimming(20.0); + m.ai.nav.kind = NavKind::Amphibious; + super::animal_brain::init(m, i64::from(m.id)); + } S::Tadpole => { // TadpoleAi: panic, swim around and look about. let g = &mut m.ai.goals; @@ -267,6 +280,13 @@ pub fn travel(m: &mut Mob, w: &MobWorld, input: Vec3, events: &mut Vec m.do_move(w, events); true } + // Axolotl.travelInWater: no fish sinking or generic water gravity. + S::Axolotl if m.fluids.in_water => { + m.move_relative(m.ai.speed, input); + m.do_move(w, events); + m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9); + true + } // AbstractFish.travelInWater / Dolphin.travelInWater. S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin if m.fluids.in_water => { let speed = if m.species() == S::Dolphin { diff --git a/crates/horizon-client/src/mobs/axolotl.rs b/crates/horizon-client/src/mobs/axolotl.rs new file mode 100644 index 000000000..55f15717c --- /dev/null +++ b/crates/horizon-client/src/mobs/axolotl.rs @@ -0,0 +1,205 @@ +//! Axolotl-specific damage, animation and prey rules; activities live in animal_brain. +use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::AnimationState}; +use horizon_core::random::RandomSource; +pub const PLAY_DEAD_TICKS: i32 = 200; +pub const HUNTING_COOLDOWN: i64 = 2400; + +/// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown. +pub fn prey_eligible( + distance: f64, + water: bool, + hostile: bool, + hunt: bool, + cooldown: bool, + attackable: bool, +) -> bool { + distance <= 64.0 && water && (hostile || hunt && !cooldown) && attackable +} +/// Preserve the ordered random draws in Axolotl.hurtServer, even out of water. +fn roll_play_dead( + random: &mut impl RandomSource, + no_ai: bool, + health: f32, + max: f32, + damage: f32, + water: bool, + entity_source: bool, + already: bool, +) -> bool { + !no_ai + && random.next_int_bound(3).unwrap_or(0) == 0 + && ((random.next_int_bound(3).unwrap_or(0) as f32) < damage || health / max < 0.5) + && damage < health + && water + && entity_source + && !already +} +pub fn before_damage(m: &mut Mob, damage: f32, source: &super::Damage) { + if m.species() != Species::Axolotl { + return; + } + let playing = m.extra.axolotl.playing_dead; + if roll_play_dead( + &mut m.random, + m.no_ai, + m.health, + m.attrs.max_health, + damage, + m.fluids.in_water, + source.attacker.is_some() || source.is_projectile(), + playing, + ) { + animal_brain::set_play_dead(m); + } +} +pub fn is_playing_dead(m: &Mob) -> bool { + m.species() == Species::Axolotl && m.extra.axolotl.playing_dead +} +/// Axolotl.onStopAttacking: help the player whose last damage killed the target. +pub fn on_stop_attacking(m: &Mob, w: &MobWorld, target: Who, events: &mut Vec) { + if let Who::Mob(id) = target + && let Some(s) = w.seen(id) + && !s.alive + && s.last_damage + .is_some_and(|d| d.attacker == Some(Who::Player)) + && w.player.as_ref().is_some_and(|p| { + m.bounds() + .inflate(horizon_core::geometry::Vec3::new(20.0, 20.0, 20.0)) + .intersects(p.bounds) + }) + { + events.push(MobEvent::AxolotlSupportPlayer); + } +} +/// BinaryAnimator(10, IN_OUT_SINE), plus the seven exclusive baby animation states. +#[derive(Clone, Debug, Default)] +pub struct Animation { + pub playing_dead: bool, + old: [u8; 4], + value: [u8; 4], + pub states: [AnimationState; 7], +} +impl Animation { + pub fn tick(&mut self, baby: bool, water: bool, ground: bool, moving: bool, age: f32) { + self.old = self.value; + let flags = [ + self.playing_dead, + !self.playing_dead && water, + !self.playing_dead && !water && ground, + moving, + ]; + for (v, on) in self.value.iter_mut().zip(flags) { + *v = if on { + (*v + 1).min(10) + } else { + v.saturating_sub(1) + }; + } + if baby { + let selected = if self.playing_dead { + 6 + } else if moving { + if water && !ground { + 1 + } else if !water && ground { + 0 + } else { + 2 + } + } else if water && !ground { + 4 + } else if water && ground { + 5 + } else { + 3 + }; + for (i, state) in self.states.iter_mut().enumerate() { + if i == selected { + state.start_if_stopped(age); + } else { + state.stop(); + } + } + } + } + pub fn factor(&self, i: usize, partial: f32) -> f32 { + let x = (f32::from(self.old[i]) + + (f32::from(self.value[i]) - f32::from(self.old[i])) * partial) + / 10.0; + ((1.0 - horizon_core::jmath::cos(f64::from(x) * std::f64::consts::PI)) / 2.0) as f32 + } +} +pub fn tick_animation(m: &mut Mob) { + if m.species() != Species::Axolotl { + return; + } + let moving = + m.limb_speed > 1.0e-5 || m.yaw != m.previous_yaw || m.head_pitch != m.previous_head_pitch; + let baby = m.is_baby(); + m.extra + .axolotl + .tick(baby, m.fluids.in_water, m.on_ground, moving, m.age as f32); +} +#[cfg(test)] +mod axolotl_parity_tests { + use super::*; + use horizon_core::random::LegacyRandom; + #[test] + fn prey_water_range_and_cooldown_match_native() { + assert!(prey_eligible(64.0, true, false, true, false, true)); + assert!(!prey_eligible(64.01, true, false, true, false, true)); + assert!(!prey_eligible(4.0, false, true, true, false, true)); + assert!(!prey_eligible(4.0, true, false, true, true, true)); + assert!(prey_eligible(4.0, true, true, false, true, true)); + assert!(!prey_eligible(4.0, true, false, false, false, true)); + assert!(!prey_eligible(4.0, true, true, true, false, false)); + } + #[test] + fn damage_roll_matches_native_draw_order_and_gates() { + for seed in 0..100 { + for (water, entity, already, no_ai) in [ + (true, true, false, false), + (false, true, false, false), + (true, false, false, false), + (true, true, true, false), + (true, true, false, true), + ] { + let mut expected = LegacyRandom::new(seed); + let mut actual = LegacyRandom::new(seed); + let result = !no_ai + && expected.next_int_bound(3).unwrap() == 0 + && ((expected.next_int_bound(3).unwrap() as f32) < 2.0 || 4.0f32 / 14.0 < 0.5) + && 2.0 < 4.0 + && water + && entity + && !already; + assert_eq!( + roll_play_dead(&mut actual, no_ai, 4.0, 14.0, 2.0, water, entity, already), + result + ); + assert_eq!(actual.next_int(), expected.next_int()); + } + } + } + #[test] + fn playing_dead_eases_and_selects_exclusive_baby_pose() { + let mut x = Animation { + playing_dead: true, + ..Animation::default() + }; + for _ in 0..10 { + x.tick(true, true, true, true, 20.0); + } + assert_eq!(x.factor(0, 1.0), 1.0); + assert_eq!(x.factor(1, 1.0), 0.0); + assert_eq!(x.states.iter().filter(|s| s.started.is_some()).count(), 1); + assert!(x.states[6].started.is_some()); + x.playing_dead = false; + for _ in 0..10 { + x.tick(true, true, false, true, 30.0); + } + assert_eq!(x.factor(0, 1.0), 0.0); + assert_eq!(x.factor(1, 1.0), 1.0); + assert!(x.states[1].started.is_some()); + } +} diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index b6b232b8b..20bcded10 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -1011,7 +1011,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { }, a, ), - Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m), a), + Species::Axolotl => axolotl(p, s, &Axolotl::from_mob(m, s.partial), a), Species::Frog => frog( p, s, @@ -1031,14 +1031,20 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { true } impl Axolotl { - pub fn from_mob(m: &Mob) -> Self { - let in_water = m.fluids.in_water; + pub fn from_mob(m: &Mob, partial: f32) -> Self { + let x = &m.extra.axolotl; Self { - in_water: if in_water { 1.0 } else { 0.0 }, - on_ground: if m.on_ground { 1.0 } else { 0.0 }, - walk: m.anim.states[0], - swim: m.anim.states[1], - ..Self::default() + playing_dead: x.factor(0, partial), + in_water: x.factor(1, partial), + on_ground: x.factor(2, partial), + moving: x.factor(3, partial), + // Native baby model deliberately reads walkAnimationState, not its underwater counterpart. + walk: x.states[0], + swim: x.states[1], + idle_on_ground: x.states[3], + idle_underwater: x.states[4], + idle_underwater_on_ground: x.states[5], + play_dead: x.states[6], } } } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c440f6817..6b0996b5b 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1000,7 +1000,7 @@ impl Goal for MeleeAttack { let Some(t) = m.target_info(cx.w) else { return false; }; - if !t.alive { + if !t.alive || !t.can_be_seen_as_enemy { return false; } let path = m.create_path_to_entity(cx.w, [t.position.x, t.position.y, t.position.z], 0); @@ -1012,7 +1012,7 @@ impl Goal for MeleeAttack { let Some(t) = m.target_info(cx.w) else { return false; }; - if !t.alive { + if !t.alive || !t.can_be_seen_as_enemy { return false; } if !self.follow_unseen { @@ -1229,7 +1229,7 @@ pub fn target_continue(st: &mut TargetState, must_see: bool, m: &mut Mob, cx: &m let Some(t) = cx.w.target_info(who) else { return false; }; - if !t.alive || t.is_player && t.creative { + if !t.alive || !t.can_be_seen_as_enemy || t.is_player && t.creative { return false; } let follow = m.attrs.follow_range * st.follow_scale; @@ -1287,6 +1287,7 @@ impl Goal for NearestTarget { let candidates: Vec<(u32, Vec3)> = cx.w.nearby(pos, range, move |s| { s.id != id + && !s.playing_dead && match prey { Prey::Species(list) => list.contains(&s.species), Prey::Filter(f) => f(s), @@ -1381,7 +1382,7 @@ impl Goal for HurtByTarget { let Some(t) = cx.w.target_info(by) else { return false; }; - t.alive && !(t.is_player && t.creative) + t.alive && t.can_be_seen_as_enemy && !(t.is_player && t.creative) } fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { target_continue(&mut self.st, true, m, cx) @@ -2060,7 +2061,12 @@ impl Goal for TryFindWater { !m.ai.nav.is_done() } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - m.nav_move_to(cx.w, self.wanted, 1.0); + let speed = if m.species() == Species::Axolotl { + 0.15 + } else { + 1.0 + }; + m.nav_move_to(cx.w, self.wanted, speed); } } /// `MoveToBlockGoal`'s shared state: search, walk to and stay at a block. diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index bc2cfe705..238653dad 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -364,7 +364,9 @@ fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { .is_some_and(|p| p.alive && !p.creative && !p.spectator), Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; - s.alive && (m.species() != Species::Breeze || s.species == Species::IronGolem) + s.alive + && !s.playing_dead + && (m.species() != Species::Breeze || s.species == Species::IronGolem) } } } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 40931fcff..9910e1e65 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -15,6 +15,7 @@ pub struct TargetInfo { pub eye_y: f64, pub bounds: Aabb, pub alive: bool, + pub can_be_seen_as_enemy: bool, pub is_player: bool, pub creative: bool, } @@ -200,6 +201,7 @@ impl MobWorld<'_> { eye_y: p.eye[1], bounds: p.bounds, alive: p.alive, + can_be_seen_as_enemy: true, is_player: true, creative: p.creative, }), @@ -208,6 +210,7 @@ impl MobWorld<'_> { eye_y: s.eye_y, bounds: s.bounds, alive: s.alive, + can_be_seen_as_enemy: !s.playing_dead, is_player: false, creative: false, }), diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 9d9a5aa1e..1e940a981 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -41,7 +41,10 @@ use std::{ sync::Arc, }; +pub(crate) mod environment; + pub struct MotionResources { + pub facts: crate::blocks::BlockFacts, pub attributes: Arc, pub blocks: BoundMovementProperties, pub climbable: BTreeSet, @@ -82,6 +85,7 @@ impl MotionResources { .collect()) }; Ok(Self { + facts: crate::blocks::BlockFacts::load(root, assets.registry)?, landing: crate::landing::load(root, &properties)?, health: crate::health::HealthResources::load(root)?, attributes, @@ -128,6 +132,16 @@ pub enum MotionEvent { }, } pub struct PlayerMotion { + pub fluids: horizon_world::entity_fluid::EntityFluidInteraction, + pub in_water: bool, + pub eye_in_water: bool, + pub in_lava: bool, + pub swimming: bool, + pub fire_ticks: i32, + pub air: i32, + pub respiration: i32, + pub(crate) first_tick: bool, + pub position: Vec3, pub velocity: Vec3, pub ground: GroundState, @@ -257,6 +271,18 @@ impl PlayerMotion { local_crouching: false, pose: crate::pose::Pose::Standing, dimensions: crate::pose::Pose::Standing.dimensions(1.0), + fluids: horizon_world::entity_fluid::EntityFluidInteraction::new([ + environment::WATER, + environment::LAVA, + ]), + in_water: false, + eye_in_water: false, + in_lava: false, + swimming: false, + fire_ticks: 0, + air: 300, + respiration: 0, + first_tick: true, speed: 0.0, item_use_speed: None, last_climbable: None, @@ -358,6 +384,9 @@ impl PlayerMotion { horizontal_collision: self.collision.horizontal, minor_horizontal_collision: self.collision.minor, moving_slowly: self.moving_slowly(), + in_water: self.in_water, + under_water: self.eye_in_water, + swimming: self.swimming, ..Default::default() }; // The sprint setter edits attributes and flags, independent of local @@ -506,14 +535,20 @@ impl MotionWorld<'_, '_, '_> { } let toggled = flying_before != self.player.flying; // Player.tryToStartFallFlying (canGlide: airborne, not flying, a glider). - let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying; + let can_glide = self.player.glider + && !self.player.ground.on_ground + && !self.player.flying + && !self.player.in_water; if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide { self.player.fall_flying = true; } // LivingEntity.tick fallFlyTicks, then updateFallFlying. if self.player.fall_flying { self.player.fall_fly_ticks += 1; - let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying; + let still = self.player.glider + && !self.player.ground.on_ground + && !self.player.flying + && !self.player.in_water; if !still { self.player.fall_flying = false; } else if (self.player.fall_fly_ticks + 1) % 10 == 0 @@ -553,8 +588,16 @@ impl MotionWorld<'_, '_, '_> { /// services are still incomplete; this composes clocks, movement and hunger. pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> { self.player.health.advance_clock(); + self.update_fluid_environment()?; + self.tick_environment_damage()?; let previous = self.player.position; + self.player.swimming = self.player.sprinting + && self.player.in_water + && (self.player.swimming || self.player.eye_in_water) + && !self.player.flying + && !self.player.spectator; self.player_movement_tick(direction, jumping)?; + self.apply_fire_contact()?; self.player.refresh_attributes()?; self.update_player_pose()?; // The resident scene accepts the resolved local movement directly. @@ -573,6 +616,7 @@ impl MotionWorld<'_, '_, '_> { self.player.auto_jump_time -= 1; keys.jump = true; } + self.sample_fluid_environment(false)?; self.player.sprint_input_tick(keys)?; self.player.shift_key_down = keys.shift; let direction = keys.direction(); @@ -621,8 +665,27 @@ impl MotionWorld<'_, '_, '_> { input.x = 0.0; input.z = 0.0; } + if self.player.shift_key_down + && !self.player.flying + && (self.player.in_water || self.player.in_lava) + { + self.player.velocity.y -= 0.04; + } if self.player.jumping { - if self.player.ground.on_ground && self.player.no_jump_delay == 0 { + let height = self.player.fluids.fluid_height( + self, + if self.player.in_water { + environment::WATER + } else { + environment::LAVA + }, + ); + if !self.player.flying + && (self.player.in_water || self.player.in_lava) + && (!self.player.ground.on_ground || height > 0.4) + { + self.player.velocity.y += 0.04; + } else if self.player.ground.on_ground && self.player.no_jump_delay == 0 { self.jump_from_ground()?; self.player.no_jump_delay = 10; } @@ -636,6 +699,8 @@ impl MotionWorld<'_, '_, '_> { let y = self.player.velocity.y; self.travel_in_air(input)?; self.player.velocity.y = y * 0.6; + } else if !self.player.flying && (self.player.in_water || self.player.in_lava) { + horizon_world::living_fluid::travel_in_fluid(self, input)?; } else { self.travel_in_air(input)?; } @@ -771,13 +836,13 @@ impl MovementStatisticsWorld for MotionWorld<'_, '_, '_> { Ok(false) } fn swimming(&mut self) -> Result { - Ok(false) + Ok(self.player.swimming) } fn eyes_in_water(&mut self) -> Result { - Ok(false) + Ok(self.player.eye_in_water) } fn in_water(&mut self) -> Result { - Ok(false) + Ok(self.player.in_water) } fn on_climbable(&mut self) -> Result { self.climbable() @@ -900,7 +965,7 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { self.player.fall_distance } fn fall_reset_clip(&mut self, from: Vec3, to: Vec3) -> Result { - // Every fluid in this controlled scene is empty. Tagged reset blocks use + // Fluid immersion is handled before travel. Tagged reset blocks use // a full block in ClipContext.FALLDAMAGE_RESETTING, not their collider. let hit = traverse_blocks(from, to, 1_000_000, |p| { let name = &self.assets.registry.state(self.block(p)).unwrap().name; @@ -1086,10 +1151,10 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { Ok(false) } fn swimming(&mut self) -> Result { - Ok(false) + Ok(self.player.swimming) } fn in_water(&mut self) -> Result { - Ok(false) + Ok(self.player.in_water) } fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> { self.player @@ -1367,6 +1432,144 @@ mod tests { /// Footsteps on the prepared vanilla resources, when they are present: /// none while standing (gravity still moves the player every tick), one /// per `nextStep` metre while walking. + #[test] + fn resident_water_and_lava_are_not_treated_as_air() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + for x in 19..=21 { + for y in 3..=7 { + for z in 19..=21 { + scene.set(x, y, z, water).unwrap(); + } + } + } + let mut w = MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.controlled_simulation_tick(Default::default()).unwrap(); + assert!( + MovementStatisticsWorld::in_water(&mut w).unwrap(), + "resident water must reach the player movement adapter" + ); + assert!(MovementStatisticsWorld::eyes_in_water(&mut w).unwrap()); + assert!( + (w.player.velocity.y + 0.005).abs() < 1e-5, + "water drag/gravity must replace air travel: {:?}", + w.player.velocity + ); + let lava = assets.registry.default_state("minecraft:lava").unwrap(); + for x in 19..=21 { + for y in 3..=7 { + for z in 19..=21 { + w.scene.set(x, y, z, lava).unwrap(); + } + } + } + w.controlled_simulation_tick(Default::default()).unwrap(); + assert!( + w.player.health.health() < 20.0, + "lava must damage a survival player" + ); + // Water extinguishes, swimming is a real pose, and deep water consumes air. + for x in 19..=21 { + for y in 3..=7 { + for z in 19..=21 { + w.scene.set(x, y, z, water).unwrap(); + } + } + } + w.player.fire_ticks = 160; + w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!(w.player.fire_ticks, 0); + w.player.air = -19; + w.player.health.hurt.cooldown = 0; + let hp = w.player.health.health(); + w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!(w.player.air, 0); + assert!(w.player.health.health() < hp, "drowning must hurt"); + w.player.invulnerable = true; + let hp = w.player.health.health(); + w.player.air = -19; + w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!(w.player.health.health(), hp); + w.player.invulnerable = false; + w.player.air = 300; + w.controlled_simulation_tick(crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }) + .unwrap(); + assert!(w.player.swimming); + assert_eq!(w.player.pose, crate::pose::Pose::Swimming); + // Direct fire contact ignites; resistance prevents damage but does not hide flames. + let fire = assets.registry.default_state("minecraft:fire").unwrap(); + for x in 19..=21 { + for y in 3..=7 { + for z in 19..=21 { + w.scene.set(x, y, z, fire).unwrap(); + } + } + } + w.player.position = Vec3::new(20.5, 4.0, 20.5); + w.player.velocity = Vec3::ZERO; + w.player.health.hurt.cooldown = 0; + let hp = w.player.health.health(); + w.controlled_simulation_tick(Default::default()).unwrap(); + assert!(w.player.fire_ticks > 0); + assert!(w.player.health.health() < hp); + w.player.status.fire_resistance = true; + w.player.health.hurt.cooldown = 0; + let hp = w.player.health.health(); + w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!(w.player.health.health(), hp); + // Sprint swimming must keep full input, not the dry crawl/sneak multiplier. + for x in 19..=21 { + for y in 2..=7 { + for z in 19..=30 { + w.scene.set(x, y, z, water).unwrap(); + } + } + } + w.player.position = Vec3::new(20.5, 4.0, 20.5); + w.player.velocity = Vec3::ZERO; + w.player.local_crouching = false; + w.player.swimming = true; + w.player.sprinting = true; + w.player.set_pose(crate::pose::Pose::Swimming).unwrap(); + for _ in 0..30 { + w.controlled_simulation_tick(crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }) + .unwrap(); + } + assert!( + w.player.velocity.z > 0.165, + "native sprint swim speed must not receive crawl slowdown: {:?}", + w.player.velocity + ); + assert!(!w.player.moving_slowly()); + w.player.in_water = false; + assert!( + w.player.moving_slowly(), + "dry crawling must still slow input" + ); + } + #[test] fn footsteps_follow_the_walked_distance_not_the_tick() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs new file mode 100644 index 000000000..1ddd79047 --- /dev/null +++ b/crates/horizon-client/src/motion/environment.rs @@ -0,0 +1,320 @@ +//! Resident bindings for the existing native immersion, current and liquid-travel kernels. +use super::*; +use horizon_core::{geometry::Direction, random::RandomSource}; +use horizon_world::{ + entity_fluid::{ + CurrentTarget, FluidInteractionWorld, FluidMembership, FluidSections, FluidTagId, + }, + fluid::{FluidHeightWorld, FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + living_fluid::{LivingFluidWorld, TravelFluidTag}, +}; +pub(super) const WATER: FluidTagId = FluidTagId(0); +pub(super) const LAVA: FluidTagId = FluidTagId(1); +impl MotionWorld<'_, '_, '_> { + fn fluid_at(&self, p: BlockPos) -> Result { + Ok(FluidState::from_block( + self.assets + .registry + .state(self.block(p)) + .ok_or("missing fluid state")?, + )?) + } + pub(super) fn update_fluid_environment(&mut self) -> Result<()> { + self.sample_fluid_environment(true) + } + pub(super) fn sample_fluid_environment(&mut self, push: bool) -> Result<()> { + let mut fluids = std::mem::take(&mut self.player.fluids); + let result = fluids + .update(self, false, 4096) + .map_err(|e| io::Error::other(e.to_string())); + if let Err(e) = result { + self.player.fluids = fluids; + return Err(e.into()); + } + self.player.in_water = fluids.is_in_fluid(self, WATER); + self.player.in_lava = fluids.is_in_fluid(self, LAVA); + self.player.eye_in_water = fluids.is_eye_in_fluid(self, WATER); + if self.player.in_water { + self.player.fall_distance = 0.0; + } + if push && !self.player.flying && !self.player.spectator { + fluids.apply_current(self, WATER, 0.014)?; + fluids.apply_current( + self, + LAVA, + if self.scene.fast_lava { + 0.007 + } else { + 0.0023333333333333335 + }, + )?; + } + self.player.fluids = fluids; + self.player.first_tick = false; + Ok(()) + } + fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { + if self.player.invulnerable || self.player.spectator { + return Ok(()); + } + let id = self + .resources + .health + .damage + .id(source) + .ok_or("missing environment damage type")?; + self.player + .hurt(&self.resources.health, self.scene.health_rules, id, damage)?; + Ok(()) + } + pub(super) fn tick_environment_damage(&mut self) -> Result<()> { + if self.player.in_water || self.player.invulnerable || self.player.spectator { + self.player.fire_ticks = 0; + } + if self.player.fire_ticks > 0 { + if self.player.fire_ticks % 20 == 0 && !self.player.in_lava { + self.environment_hurt("minecraft:on_fire", 1.0)?; + } + self.player.fire_ticks -= 1; + } + if self.player.eye_in_water + && !self.player.status.water_breathing + && !self.player.invulnerable + && !self.player.spectator + { + let oxygen = self + .player + .attribute("minecraft:oxygen_bonus")? + .max(f64::from(self.player.respiration)); + if oxygen <= 0.0 || self.scene.random.next_double() < 1.0 / (oxygen + 1.0) { + self.player.air -= 1; + } + if self.player.air <= -20 { + self.player.air = 0; + self.environment_hurt("minecraft:drown", 2.0)?; + } + } else { + self.player.air = (self.player.air + 4).min(300); + } + if self.player.in_lava { + self.player.fire_ticks = self.player.fire_ticks.max(300); + self.environment_hurt("minecraft:lava", 4.0)?; + self.player.fall_distance *= 0.5; + } + Ok(()) + } + pub(super) fn apply_fire_contact(&mut self) -> Result<()> { + if self.player.spectator || self.player.invulnerable { + self.player.fire_ticks = 0; + return Ok(()); + } + let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds()); + if damage > 0.0 { + if !self.player.in_water { + self.player.fire_ticks = + ignite_contact(self.player.fire_ticks, true, &mut self.scene.random); + } + self.environment_hurt("minecraft:in_fire", damage)?; + } + Ok(()) + } +} +pub(crate) fn fire_contact( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + bounds: Aabb, +) -> f32 { + let b = bounds.deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + let mut damage = 0.0f32; + 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 { + damage = damage.max( + match registry + .state(world.block(x, y, z)) + .map(|s| s.name.as_str()) + { + Some("minecraft:fire") => 1.0, + Some("minecraft:soul_fire") => 2.0, + _ => 0.0, + }, + ); + } + } + } + damage +} +impl FluidMembership for MotionWorld<'_, '_, '_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + if tag == WATER { + matches!(kind, FluidKind::Water | FluidKind::FlowingWater) + } else { + matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) + } + } +} +impl CurrentTarget for MotionWorld<'_, '_, '_> { + type Error = Box; + fn is_player_class(&self) -> bool { + true + } + fn velocity(&mut self) -> Result { + Ok(self.player.velocity) + } + fn add_delta_movement(&mut self, v: Vec3) -> Result<()> { + let old = self.player.velocity; + self.player.velocity = Vec3::new(old.x + v.x, old.y + v.y, old.z + v.z); + Ok(()) + } +} +impl FluidInteractionWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + type Chunk = (i32, i32); + fn interaction_box(&mut self) -> Result> { + Ok(Some( + self.player.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> Result> { + Ok(self.scene.chunks.contains_key(&(x, z)).then_some((x, z))) + } + fn chunk_sections(&mut self, _: Self::Chunk) -> Result> { + // Resident sections have no fluid-count cache; scan the small interaction box rather than skipping sections. + static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: crate::chunk::MIN_Y >> 4, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.player.bounds().min_position().y + } + fn block_x(&self) -> i32 { + self.player.position.x.floor() as i32 + } + fn block_z(&self) -> i32 { + self.player.position.z.floor() as i32 + } + fn eye_y(&mut self) -> Result { + Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height)) + } + fn fluid_state(&mut self, p: BlockPos) -> Result { + self.fluid_at(p) + } + fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, f: FluidState, p: BlockPos) -> Result { + flow_at(self, f, p) + } +} +impl FluidHeightWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + fn fluid(&mut self, p: [i32; 3]) -> Result { + self.fluid_at(BlockPos::new(p[0], p[1], p[2])) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> Result { + Ok(self + .resources + .facts + .get(MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2]))) + .sturdy_full + & 1 + != 0) + } +} +impl FluidFlowWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + self.fluid_at(p) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(MotionWorld::block(self, p)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.assets + .blocks_fluid_flow + .contains(&self.assets.registry.state(s).unwrap().name) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.resources + .facts + .get(s) + .classes + .iter() + .any(|c| c.as_ref() == "IceBlock") + } + fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result { + Ok(self.resources.facts.get(s).sturdy_full & (1 << d as u8) != 0) + } +} +impl LivingFluidWorld for MotionWorld<'_, '_, '_> { + fn in_water(&mut self) -> Result { + Ok(self.player.in_water) + } + fn sprinting(&mut self) -> Result { + Ok(self.player.sprinting) + } + fn water_slow_down(&mut self) -> Result { + Ok(0.8) + } + fn water_movement_efficiency(&mut self) -> Result { + self.player.attribute("minecraft:water_movement_efficiency") + } + fn dolphins_grace(&mut self) -> Result { + Ok(self.player.status.dolphins_grace) + } + fn fluid_height(&mut self, tag: TravelFluidTag) -> Result { + Ok(self.player.fluids.fluid_height( + self, + if tag == TravelFluidTag::Lava { + LAVA + } else { + WATER + }, + )) + } + fn fluid_jump_threshold(&mut self) -> Result { + Ok(0.4) + } + fn is_free(&mut self, v: Vec3) -> Result { + let b = self.player.bounds().move_by(v); + Ok(self.no_player_collision(b)? && !self.has_liquid(b)?) + } + fn is_vehicle(&mut self) -> Result { + Ok(false) + } + fn can_float_while_ridden(&mut self) -> Result { + Ok(false) + } +} +impl MotionWorld<'_, '_, '_> { + fn has_liquid(&self, b: Aabb) -> Result { + 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 { + if self.fluid_at(BlockPos::new(x, y, z))?.kind() != FluidKind::Empty { + return Ok(true); + } + } + } + } + Ok(false) + } +} + +pub(crate) fn ignite_contact(ticks: i32, player: bool, random: &mut impl RandomSource) -> i32 { + let ticks = if ticks < 0 { + ticks + 1 + } else if player { + ticks + 1 + random.next_int_bound(2).unwrap_or(0) + } else { + ticks + }; + if ticks >= 0 { ticks.max(160) } else { ticks } +} diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index 477b9463a..fb912ed87 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -72,7 +72,7 @@ impl PlayerMotion { Ok(()) } pub fn moving_slowly(&self) -> bool { - self.local_crouching || self.pose == Pose::Swimming // dry scene: not in water + self.local_crouching || (self.pose == Pose::Swimming && !self.in_water) } } impl MotionWorld<'_, '_, '_> { @@ -87,6 +87,7 @@ impl MotionWorld<'_, '_, '_> { /// the old shift input. This is distinct from Entity's current pose. pub fn update_local_crouching(&mut self) -> Result<()> { self.player.local_crouching = !self.player.flying + && !self.player.swimming && self.can_fit_pose(Pose::Crouching)? && (self.player.shift_key_down || !self.can_fit_pose(Pose::Standing)?); Ok(()) @@ -99,6 +100,8 @@ impl MotionWorld<'_, '_, '_> { } let desired = if self.player.fall_flying { Pose::FallFlying + } else if self.player.swimming { + Pose::Swimming } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index 213f7c7ca..cc93757ef 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -19,6 +19,18 @@ impl SpriteAnimation { pub fn frame(&self, tick: u64) -> usize { self.clip.sample(tick).frame as usize } + pub fn resized_pixels(&self, frame: usize, width: u32, height: u32) -> Vec { + let source = self.pixels(frame); + let mut out = Vec::with_capacity((width * height * 4) as usize); + for y in 0..height { + for x in 0..width { + let offset = ((y * SPRITE_SIZE / height * SPRITE_SIZE + x * SPRITE_SIZE / width) + * 4) as usize; + out.extend_from_slice(&source[offset..offset + 4]); + } + } + out + } pub fn pixels(&self, frame: usize) -> &[u8] { &self.frames[frame] } @@ -142,6 +154,40 @@ impl Sprites { #[cfg(test)] mod tests { use super::*; + #[test] + fn native_fire_sprites_register_full_animation_sequences() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root + .join("assets/minecraft/textures/block/fire_0.png") + .exists() + { + return; + } + let mut sprites = Sprites::default(); + for name in ["fire_0", "fire_1", "soul_fire_0", "soul_fire_1"] { + let layer = sprites + .insert(&root, &format!("minecraft:block/{name}")) + .unwrap(); + let animation = sprites + .animations + .iter() + .find(|a| a.layer == layer) + .expect("fire must be animated"); + assert_ne!( + animation.pixels(animation.frame(0)), + animation.pixels(animation.frame(1)) + ); + assert_ne!( + animation.resized_pixels(animation.frame(0), 16, 16), + animation.resized_pixels(animation.frame(1), 16, 16) + ); + assert_eq!( + animation.pixels(animation.frame(0)).len(), + (SPRITE_SIZE * SPRITE_SIZE * 4) as usize + ); + } + } + #[test] fn native_32_pixel_animation_frames_keep_every_texel() { let root = std::env::temp_dir().join(format!( diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index ec3fea46c..1b589041d 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -9,6 +9,7 @@ use std::{ }; pub struct World { + pub fast_lava: bool, pub chunks: crate::fast_hash::FxHashMap<(i32, i32), Arc>, pub random: LegacyRandom, pub revision: u64, @@ -113,6 +114,7 @@ impl World { revision: 0, health_rules: crate::health::HealthRules::default(), air, + fast_lava: false, dirty_sections: Default::default(), dirty_light: Default::default(), light_edits: Vec::new(), diff --git a/crates/horizon-world/src/level/hooks.rs b/crates/horizon-world/src/level/hooks.rs index ee1e3cdd9..0695a92b3 100644 --- a/crates/horizon-world/src/level/hooks.rs +++ b/crates/horizon-world/src/level/hooks.rs @@ -424,7 +424,12 @@ impl Sim<'_, L> { if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) { self.prime_tnt(pos); } - self.level_event(2001, pos, state.0 as i32); + // BaseFireBlock emits extinguish and suppresses generic destroy particles/sound. + if data.is(Class::BaseFire) { + self.level_event(1009, pos, 0); + } else { + self.level_event(2001, pos, state.0 as i32); + } self.game_event(pos, "minecraft:block_destroy"); self.remove_block(pos, false) } diff --git a/crates/horizon-world/src/level/tests.rs b/crates/horizon-world/src/level/tests.rs index 5ffd31031..8d23e6058 100644 --- a/crates/horizon-world/src/level/tests.rs +++ b/crates/horizon-world/src/level/tests.rs @@ -1192,3 +1192,38 @@ fn creaking_heart_follows_its_logs_and_the_night() { } assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted"); } + +#[test] +fn player_breaks_fire_with_extinguish_not_generic_break_event() { + for name in ["fire", "soul_fire", "white_wool"] { + let mut w = world!(); + let pos = BlockPos::new(0, 1, 0); + let support = w.id("soul_soil", &[]); + w.put(BlockPos::new(0, 0, 0), support); + let state = w.id(name, &[]); + w.put(pos, state); + w.level.events.clear(); + assert!( + w.f.behaviours + .player_destroy_block(&mut w.level, &mut w.ticks, pos, false) + ); + let is_fire = name != "white_wool"; + assert_eq!( + w.level + .events + .iter() + .any(|e| matches!(e,LevelEvent::LevelEvent {id:1009,pos:p,..} if *p==pos)), + is_fire, + "extinguish for {name}" + ); + assert_eq!( + w.level + .events + .iter() + .any(|e| matches!(e,LevelEvent::LevelEvent {id:2001,pos:p,..} if *p==pos)), + !is_fire, + "generic break for {name}" + ); + assert_eq!(w.get(pos), w.b().air()); + } +} diff --git a/tests/test_sprite_animation_upload.py b/tests/test_sprite_animation_upload.py new file mode 100644 index 000000000..5a7d14395 --- /dev/null +++ b/tests/test_sprite_animation_upload.py @@ -0,0 +1,71 @@ +"""Exercise the actual animation uploader with a recording queue, without a GPU/window.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from test_item_action_animation import block + +ROOT = Path(__file__).resolve().parents[1] + + +class SpriteAnimationUploadTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is required") + def test_animation_updates_entire_layer_and_every_mip(self): + source = (ROOT / "crates/horizon-client/src/gfx.rs").read_text() + animate = block(source, source.index("fn animate(&mut self, tick: u64)")) + mips = block(source, source.index("fn mip_chain(")) + program = r""" +use std::cell::RefCell; +mod wgpu { + pub struct Texture(pub u32); + impl Texture {pub fn width(&self)->u32 {self.0}} + pub struct Origin3d {pub x:u32,pub y:u32,pub z:u32} + pub enum TextureAspect {All} + pub struct TexelCopyTextureInfo { + pub texture:&LIFETIME Texture,pub mip_level:u32,pub origin:Origin3d,pub aspect:TextureAspect, + } + pub struct TexelCopyBufferLayout {pub offset:u64,pub bytes_per_row:Option,pub rows_per_image:Option} + pub struct Extent3d {pub width:u32,pub height:u32,pub depth_or_array_layers:u32} +} +struct Queue {writes:RefCell>>} +impl Queue { + fn write_texture(&self, info:wgpu::TexelCopyTextureInfo, pixels:&[u8], layout:wgpu::TexelCopyBufferLayout, extent:wgpu::Extent3d) { + let size=info.texture.width() >> info.mip_level; + assert_eq!((extent.width,extent.height,extent.depth_or_array_layers),(size,size,1),"animation must update the entire mip, not a quarter"); + assert_eq!((layout.bytes_per_row,layout.rows_per_image,layout.offset),(Some(size*4),Some(size),0)); + assert_eq!((info.origin.x,info.origin.y,info.origin.z),(0,0,7)); + assert_eq!(pixels.len(),(size*size*4) as usize); + self.writes.borrow_mut().push(pixels.to_vec()); + } +} +struct Animation {layer:u32,pixels:Vec} +impl Animation {fn frame(&self,tick:u64)->usize {if tick==0 {0} else {1}} fn pixels(&self,_:usize)->&[u8] {&self.pixels}} +struct Gfx {animations:Vec<(Animation,usize)>,mip_levels:u32,sprite_texture:wgpu::Texture,queue:Queue} +MIPS +impl Gfx {ANIMATE} +fn main() { + for size in [16u32,32] { + let pixels:Vec=(0..size*size).flat_map(|i|[(i%size) as u8,(i/size) as u8,99,255]).collect(); + let (expected,levels)=mip_chain(&pixels,size,1); + let mut gfx=Gfx {animations:vec![(Animation {layer:7,pixels:pixels.clone()},0)],mip_levels:levels,sprite_texture:wgpu::Texture(size),queue:Queue {writes:RefCell::default()}}; + gfx.animate(0);assert!(gfx.queue.writes.borrow().is_empty()); + gfx.animate(1); + assert_eq!(gfx.queue.writes.borrow().len(),levels as usize); + assert_eq!(gfx.queue.writes.borrow()[0],pixels,"the bottom-right texel must animate too"); + assert_eq!(gfx.queue.writes.borrow().concat(),expected); + gfx.animate(1);assert_eq!(gfx.queue.writes.borrow().len(),levels as usize); + } +} +""".replace("LIFETIME", chr(39)+"a").replace("MIPS", mips).replace("ANIMATE", animate) + with tempfile.TemporaryDirectory(prefix="horizon-animation-upload-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + subprocess.run(["rustc", "--edition=2024", "-Awarnings", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True) + result = subprocess.run([str(path / "probe")], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_world_runtime_reset.py b/tests/test_world_runtime_reset.py new file mode 100644 index 000000000..e42827203 --- /dev/null +++ b/tests/test_world_runtime_reset.py @@ -0,0 +1,39 @@ +"""The actual world-entry reset must invalidate previously loaded player progress.""" +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[1] + + +def run_reset(source): + start = source.index(" self.persist = Default::default();", source.index(" fn open_world(")) + reset = source[start:source.index(" // RandomSequences", start)] + program = """ +#[derive(Default)] struct Game {persist:bool,score:bool,fns:bool,bosses:bool,adv:bool,stats:bool} +impl Game {fn enter_world(&mut self) {RESET}} +fn main() { + let mut game=Game {persist:true,score:true,fns:true,bosses:true,adv:true,stats:true}; + game.enter_world(); + assert!(!game.adv,"loaded advancement progress must not survive world entry"); + assert!(!game.stats,"loaded statistics must not survive world entry"); +} +""".replace("RESET", reset) + with tempfile.TemporaryDirectory(prefix="horizon-world-reset-") as directory: + path = Path(directory) + (path / "probe.rs").write_text(program) + subprocess.run(["rustc", "--edition=2024", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True) + return subprocess.run([str(path / "probe")], capture_output=True, text=True) + + +class WorldRuntimeResetTests(unittest.TestCase): + @unittest.skipUnless(shutil.which("rustc"), "rustc is required") + def test_world_entry_invalidates_loaded_progress(self): + result = run_reset((ROOT / "crates/horizon-client/src/game.rs").read_text()) + self.assertEqual(result.returncode, 0, result.stderr) + + +if __name__ == "__main__": + unittest.main() From f3dda9c412fe702aa49e2a7635fb7e17b3b52b0a Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:05:41 -0400 Subject: [PATCH 03/23] Address PR59 review: axolotl timers, fluid and fire parity, persistence and Rust tests --- crates/horizon-client/src/entities.rs | 40 +++- crates/horizon-client/src/entity_nbt.rs | 208 +++++++++++++++--- crates/horizon-client/src/first_person.rs | 49 +++++ crates/horizon-client/src/game.rs | 101 +++++---- .../horizon-client/src/game/advancements.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 54 ++++- crates/horizon-client/src/game/dispenser.rs | 3 + crates/horizon-client/src/game/lightning.rs | 21 +- crates/horizon-client/src/game/stats.rs | 2 +- crates/horizon-client/src/gfx.rs | 91 ++++++-- crates/horizon-client/src/items.rs | 30 +++ crates/horizon-client/src/mobs.rs | 17 +- crates/horizon-client/src/mobs/ai.rs | 13 +- .../horizon-client/src/mobs/animal_brain.rs | 46 +++- crates/horizon-client/src/mobs/finalize.rs | 10 +- crates/horizon-client/src/mobs/goals.rs | 11 +- crates/horizon-client/src/motion.rs | 115 ++++++++-- .../horizon-client/src/motion/environment.rs | 64 ++++-- crates/horizon-client/src/sprites.rs | 15 ++ tests/test_item_action_animation.py | 93 -------- tests/test_sprite_animation_upload.py | 71 ------ tests/test_world_runtime_reset.py | 39 ---- 22 files changed, 730 insertions(+), 365 deletions(-) delete mode 100644 tests/test_item_action_animation.py delete mode 100644 tests/test_sprite_animation_upload.py delete mode 100644 tests/test_world_runtime_reset.py diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 2855f9679..0ee3a8d8d 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -61,7 +61,8 @@ impl ItemEntity { self.position.z.floor() as i32, ); let fluid = facts.get(at).fluid; - if fluid == Fluid::Water { + let fire_immune = items.resists_fire(&self.stack, "minecraft:in_fire"); + if fluid == Fluid::Water || fire_immune { self.fire_ticks = 0; } if self.fire_ticks > 0 { @@ -74,17 +75,18 @@ impl ItemEntity { self.fire_ticks -= 1; } let mut lava_hurt = false; - if fluid == Fluid::Lava { + if fluid == Fluid::Lava && !fire_immune { self.fire_ticks = self.fire_ticks.max(300); if !items.resists_fire(&self.stack, "minecraft:lava") { self.health -= 4; lava_hurt = true; } } - if crate::motion::environment::fire_contact(world, registry, self.bounds()) > 0.0 { + let fire_damage = crate::motion::environment::fire_contact(world, registry, self.bounds()); + if fire_damage > 0.0 && !fire_immune { self.fire_ticks = self.fire_ticks.max(160); if !items.resists_fire(&self.stack, "minecraft:in_fire") { - self.health -= 1; + self.health -= fire_damage as i32; } } ItemEnvironmentTick { @@ -569,7 +571,7 @@ impl ArmorStand { self.fire_ticks = self.fire_ticks.max(300); } let fire = crate::motion::environment::fire_contact(world, registry, self.bounds()) > 0.0; - if (fire || lava) && !self.invisible && !self.marker { + if fire && !self.invisible && !self.marker { if self.fire_ticks > 0 { self.health -= 0.15; } else { @@ -679,6 +681,7 @@ mod fire_environment_tests { assert!(!result.should_play_lava_hurt_sound(10)); } assert_eq!(metal.health, 5); + assert_eq!(metal.fire_ticks, 0, "fire-resistant items must not ignite"); world .set( 20, @@ -691,5 +694,32 @@ mod fire_environment_tests { let result = burning.environment_tick(&world, &facts, assets.registry, &items); assert!(result.alive && !result.lava_hurt); assert!(burning.fire_ticks > 0); + world + .set( + 20, + 4, + 20, + assets + .registry + .default_state("minecraft:soul_fire") + .unwrap(), + ) + .unwrap(); + let mut soul = make("minecraft:oak_planks"); + soul.environment_tick(&world, &facts, assets.registry, &items); + assert_eq!(soul.health, 3); + let mut stand = ArmorStand::new(2, at, 0.0); + world + .set( + 20, + 4, + 20, + assets.registry.default_state("minecraft:lava").unwrap(), + ) + .unwrap(); + for _ in 0..150 { + assert!(stand.environment_tick(&world, &facts, assets.registry)); + } + assert_eq!(stand.health, 20.0, "lava does not hurt armor stands"); } } diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 3972ce172..386507c45 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -329,20 +329,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { crate::mobs::villager::write_nbt(m, map); } "minecraft:wandering_trader" => put_offers(map, m), - "minecraft:axolotl" => { - if let Some(ttl) = crate::mobs::animal_brain::hunting_cooldown(m) { - map.insert( - "Brain".into(), - Tag::compound([( - "memories", - Tag::compound([( - "minecraft:has_hunting_cooldown", - Tag::compound([("value", Tag::Byte(1)), ("ttl", Tag::Long(ttl))]), - )]), - )]), - ); - } - } + "minecraft:axolotl" => write_axolotl_memories(m, map), "minecraft:allay" => { // InventoryCarrier: the fetched stack; the liked player memory. let mut inv = Vec::new(); @@ -729,14 +716,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - } crate::mobs::zombie_villager::read_nbt(&mut m, tag); } - if m.species() == crate::mobs::Species::Axolotl - && let Some(memory) = tag - .get("Brain") - .and_then(|b| b.get("memories")) - .and_then(|b| b.get("minecraft:has_hunting_cooldown")) - && let Some(ttl) = number(memory.get("ttl")) - { - crate::mobs::animal_brain::set_hunting_cooldown(&mut m, ttl); + if m.species() == crate::mobs::Species::Axolotl { + restore_axolotl_memories(&mut m, tag); } m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; m.air = number(tag.get("Air")).unwrap_or(300) as i32; @@ -866,6 +847,8 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> let mut tag = base.tag(raw); for (key, value) in [ ("Item", item_to_nbt(&e.stack)), + ("Health", Tag::Short(e.health as i16)), + ("Fire", Tag::Short(e.fire_ticks as i16)), ("Age", Tag::Short(e.age.min(i16::MAX as u32) as i16)), ( "PickupDelay", @@ -874,9 +857,6 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> ] { put(&mut tag, key, value); } - if let Tag::Compound(map) = &mut tag { - map.entry("Health".into()).or_insert(Tag::Short(5)); - } tag } pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { @@ -1452,8 +1432,8 @@ mod tests { #[test] fn item_entities_round_trip() { let e = ItemEntity { - health: 5, - fire_ticks: 0, + health: 2, + fire_ticks: 73, id: 7, stack: ItemStack { item: Arc::from("minecraft:diamond_pickaxe"), @@ -1474,6 +1454,7 @@ mod tests { assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); let back = item_entity_from_nbt(&tag, 9, 0.0).unwrap(); assert_eq!(back.stack.damage, 5); + assert_eq!((back.health, back.fire_ticks), (2, 73)); assert_eq!( (back.age, back.pickup_delay, back.on_ground), (120, 10, true) @@ -1513,3 +1494,176 @@ mod tests { assert_eq!(back[0].value, 7); } } + +fn write_axolotl_memories(m: &Mob, map: &mut Compound) { + let brain = map + .entry("Brain".into()) + .or_insert_with(|| Tag::Compound(Compound::new())); + if !matches!(brain, Tag::Compound(_)) { + *brain = Tag::Compound(Compound::new()); + } + let Tag::Compound(brain) = brain else { return }; + let memories = brain + .entry("memories".into()) + .or_insert_with(|| Tag::Compound(Compound::new())); + if !matches!(memories, Tag::Compound(_)) { + *memories = Tag::Compound(Compound::new()); + } + let Tag::Compound(memories) = memories else { + return; + }; + let mm = m.extra.animal_brain.as_deref().map(|b| &b.mem); + let hunting = crate::mobs::animal_brain::hunting_cooldown(m) + .map(|ttl| Tag::compound([("value", Tag::Byte(1)), ("ttl", Tag::Long(ttl))])); + let play_dead = mm + .and_then(|m| m.play_dead_ticks.value()) + .map(|v| Tag::compound([("value", Tag::Int(v))])); + let temptation = mm + .and_then(|m| m.temptation_cooldown_ticks.value()) + .map(|v| Tag::compound([("value", Tag::Int(v))])); + for (key, value) in [ + ("minecraft:has_hunting_cooldown", hunting), + ("minecraft:play_dead_ticks", play_dead), + ("minecraft:temptation_cooldown_ticks", temptation), + ] { + if let Some(value) = value { + memories.insert(key.into(), value); + } else { + memories.remove(&key.into()); + } + } +} +fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) { + let memories = tag.get("Brain").and_then(|b| b.get("memories")); + let ttl = memories + .and_then(|b| b.get("minecraft:has_hunting_cooldown")) + .and_then(|v| number(v.get("ttl"))) + .unwrap_or(0); + crate::mobs::animal_brain::set_hunting_cooldown(m, ttl); + if let Some(b) = m.extra.animal_brain.as_mut() { + if let Some(v) = memories + .and_then(|b| b.get("minecraft:play_dead_ticks")) + .and_then(|v| number(v.get("value"))) + { + b.mem.play_dead_ticks.set(v as i32); + } + if let Some(v) = memories + .and_then(|b| b.get("minecraft:temptation_cooldown_ticks")) + .and_then(|v| number(v.get("value"))) + { + b.mem.temptation_cooldown_ticks.set(v as i32); + } + } +} +pub fn bucket_data(m: &Mob) -> Tag { + let mut data = Tag::compound([ + ("Age", Tag::Int(m.extra.age)), + ("Variant", Tag::Int(i32::from(m.extra.variant))), + ("Health", Tag::Float(m.health.to_bits())), + ]); + if let Some(ttl) = crate::mobs::animal_brain::hunting_cooldown(m) { + put(&mut data, "HuntingCooldown", Tag::Long(ttl)); + } + data +} +pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { + let data = stack.data().and_then(|d| { + d.other + .iter() + .find(|(key, _)| key == "minecraft:bucket_entity_data") + .map(|(_, v)| v) + }); + let Some(data) = data else { return }; + if let Some(v) = number(data.get("Age")) { + m.extra.age = v as i32; + } + if let Some(v) = number(data.get("Variant")) { + m.extra.variant = v as u8; + } + if let Some(v) = float(data.get("Health")) { + m.health = v as f32; + } + if m.species() == crate::mobs::Species::Axolotl { + crate::mobs::animal_brain::set_hunting_cooldown( + m, + number(data.get("HuntingCooldown")).unwrap_or(0), + ); + } +} + +#[cfg(test)] +mod axolotl_nbt_tests { + use super::*; + #[test] + fn bucket_cooldown_and_brain_memories_survive_and_expired_cooldown_is_removed() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let kind = Arc::new(data.types.get("minecraft:axolotl").unwrap().clone()); + let mut m = Mob::new(1, kind.clone(), Vec3::new(0.0, 4.0, 0.0), 0.0); + crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 123); + { + let mm = &mut m.extra.animal_brain.as_mut().unwrap().mem; + mm.play_dead_ticks.set(78); + mm.temptation_cooldown_ticks.set(42); + } + let raw = Tag::compound([( + "Brain", + Tag::compound([( + "memories", + Tag::compound([("test:unrelated", Tag::compound([("value", Tag::Int(9))]))]), + )]), + )]); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], Some(&raw)); + let memories = tag.get("Brain").unwrap().get("memories").unwrap(); + assert!(memories.get("test:unrelated").is_some()); + assert_eq!( + number( + memories + .get("minecraft:play_dead_ticks") + .unwrap() + .get("value") + ), + Some(78) + ); + assert_eq!( + number( + memories + .get("minecraft:temptation_cooldown_ticks") + .unwrap() + .get("value") + ), + Some(42) + ); + let mut stack = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1); + stack.extra = Some(Box::new(crate::item_data::StackData { + other: vec![("minecraft:bucket_entity_data".into(), bucket_data(&m))], + ..Default::default() + })); + let mut restored = Mob::new(2, kind, Vec3::new(0.0, 4.0, 0.0), 0.0); + load_bucket_data(&mut restored, &stack); + assert_eq!( + crate::mobs::animal_brain::hunting_cooldown(&restored), + Some(123) + ); + crate::mobs::animal_brain::set_hunting_cooldown(&mut m, 0); + assert!(bucket_data(&m).get("HuntingCooldown").is_none()); + let saved = mob_to_nbt(&m, [1, 2, 3, 4], Some(&tag)); + assert!( + saved + .get("Brain") + .unwrap() + .get("memories") + .unwrap() + .get("minecraft:has_hunting_cooldown") + .is_none() + ); + restore_axolotl_memories(&mut restored, &saved); + let mm = &restored.extra.animal_brain.as_ref().unwrap().mem; + assert_eq!(mm.play_dead_ticks.value(), Some(78)); + assert_eq!(mm.temptation_cooldown_ticks.value(), Some(42)); + } +} diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index d07e2e23a..19f55a9e8 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -330,6 +330,23 @@ pub enum UseResult { Fail, } +impl UseResult { + pub fn should_swing(self, before: u32, after: u32) -> bool { + 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, + } +} /// What the click handling reads and does in the world. pub trait HandWorld { fn hit(&mut self) -> Hit; @@ -839,3 +856,35 @@ mod continuous_use_tests { assert_ne!(swing, item_pose(false, 0.0, 0.3, ItemPose::Using)); } } + +#[cfg(test)] +mod action_result_tests { + use super::*; + #[test] + fn only_successful_actions_swing_once() { + assert!(UseResult::Success { swing: true }.should_swing(2, 2)); + for result in [ + UseResult::Fail, + UseResult::Pass, + UseResult::Success { swing: false }, + ] { + assert!(!result.should_swing(2, 2)); + } + assert!(!UseResult::Success { swing: true }.should_swing(2, 3)); + } + #[test] + fn consumption_pose_requires_eat_or_drink_animation() { + use horizon_world::consumable::UseAnimation::*; + assert_eq!(consumable_animation(&serde_json::json!({})), Eat); + assert_eq!( + consumable_animation(&serde_json::json!({"animation":"drink"})), + Drink + ); + for animation in ["none", "block", "bow", "brush"] { + assert_eq!( + consumable_animation(&serde_json::json!({"animation":animation})), + None + ); + } + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f85540c6d..dcccc4e0b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -847,6 +847,7 @@ struct Game<'a> { tab_list: horizon_client::tab_list::TabList, subtitles: subtitle_hud::SubtitleState, adv: advancements::AdvState, + restore_player_environment: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, camera_type: perspective::CameraType, @@ -1215,18 +1216,11 @@ impl Game<'_> { if self.eye_position().is_none() { return; } - let Some(stack) = self.inventory[self.selected].as_mut() else { + let Some(thrown) = + horizon_client::items::take_held_drop(&mut self.inventory[self.selected], all) + else { return; }; - let count = if all { stack.count } else { 1 }; - let thrown = ItemStack { - count, - ..stack.clone() - }; - stack.count -= count; - if stack.count == 0 { - self.inventory[self.selected] = None; - } self.player_drop(thrown); self.swing_arm(); } @@ -2105,7 +2099,7 @@ impl Game<'_> { let swings = self.swings_started; match self.use_tool(&stack)? { UseResult::Success { swing } => { - if swing && self.swings_started == swings { + if (UseResult::Success { swing }).should_swing(swings, self.swings_started) { self.swing_arm(); } return Ok(()); @@ -2598,18 +2592,10 @@ impl Game<'_> { }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; - player.fire_ticks = self - .level - .player_extra - .as_ref() - .and_then(|t| horizon_client::save::number(t.get("Fire"))) - .unwrap_or(0) as i32; - player.air = self - .level - .player_extra - .as_ref() - .and_then(|t| horizon_client::save::number(t.get("Air"))) - .unwrap_or(300) as i32; + player.load_environment_once( + &mut self.restore_player_environment, + self.level.player_extra.as_ref(), + ); let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; player.invulnerable = self.creative || spectator; @@ -4434,7 +4420,12 @@ impl Game<'_> { ); } for item in &self.dropped { - if item.fire_ticks > 0 { + if item.fire_ticks > 0 + && !self + .res + .items + .resists_fire(&item.stack, "minecraft:in_fire") + { let at = item.previous.lerp(item.position, alpha); horizon_client::fire_render::flames( [at.x, at.y, at.z], @@ -5320,8 +5311,8 @@ impl Game<'_> { self.score = Default::default(); self.fns = Default::default(); self.bosses = Default::default(); - self.adv = Default::default(); - self.stats = Default::default(); + reset_world_progress(&mut self.adv, &mut self.stats); + self.restore_player_environment = true; // RandomSequences: the world's data/minecraft/random_sequences.dat. self.rand_sequences = horizon_client::save::read_dat(&save_root.join("data/minecraft/random_sequences.dat")) @@ -6351,18 +6342,8 @@ impl Game<'_> { } if let Some(kind) = mob { if let Some(id) = self.spawn_mob_at(kind, (target[0], target[1], target[2]), true) { - if kind == "axolotl" - && let Some(data) = stack.data().and_then(|d| { - d.other - .iter() - .find(|(key, _)| key == "minecraft:bucket_entity_data") - .map(|(_, v)| v) - }) - && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) - && let Some(horizon_world::nbt::Tag::Long(ticks)) = - data.get("HuntingCooldown") - { - horizon_client::mobs::animal_brain::set_hunting_cooldown(m, *ticks); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + horizon_client::entity_nbt::load_bucket_data(m, stack); } self.mob_placed(id)?; } @@ -6422,7 +6403,12 @@ impl Game<'_> { }, Some(at(hit.pos)), 1.0, - self.world.random.next_float() * 0.4 + 0.8, + if item == "fire_charge" { + (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + + 1.0 + } else { + self.world.random.next_float() * 0.4 + 0.8 + }, ); if item == "fire_charge" { self.consume_held(); @@ -6777,7 +6763,16 @@ impl Game<'_> { .item_renderer .models .components(&horizon_client::item_render::stack_view(&stack)); - if components.contains_key("minecraft:consumable") { + let animation = components + .get("minecraft:consumable") + .map(horizon_client::first_person::consumable_animation); + if matches!( + animation, + Some( + horizon_world::consumable::UseAnimation::Eat + | horizon_world::consumable::UseAnimation::Drink + ) + ) { ItemPose::Eat { remaining: owner.use_item_remaining_ticks as f32, duration: owner.use_duration as f32, @@ -8928,6 +8923,7 @@ pub fn run() -> Result<()> { tab_list: Default::default(), subtitles: Default::default(), adv: Default::default(), + restore_player_environment: true, stats_ui: Default::default(), adv_ui: Default::default(), camera_type: Default::default(), @@ -9003,3 +8999,28 @@ pub fn run() -> Result<()> { } Ok(()) } + +fn reset_world_progress(adv: &mut advancements::AdvState, stats: &mut stats::Stats) { + *adv = Default::default(); + *stats = Default::default(); +} + +#[cfg(test)] +mod runtime_reset_tests { + use super::*; + #[test] + fn world_entry_invalidates_loaded_progress() { + let mut adv = advancements::AdvState::default(); + let mut stats = stats::Stats::default(); + adv.loaded = true; + stats.loaded = true; + adv.progress + .criteria + .insert("minecraft:story/root".into(), Default::default()); + stats.add("mined", "minecraft:stone", 4); + reset_world_progress(&mut adv, &mut stats); + assert!(!adv.loaded && !stats.loaded); + assert!(adv.progress.criteria.is_empty()); + assert!(stats.values.is_empty()); + } +} diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 428d7da97..ef615cc68 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -45,7 +45,7 @@ impl Toast { pub(super) struct AdvState { pub(super) tree: Arc, pub(super) progress: Progress, - loaded: bool, + pub(super) loaded: bool, pub(super) toasts: VecDeque, /// Awards skip the toast (`/advancement grant ... everything`). pub(super) quiet: bool, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index ec140faa5..89891670c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -751,8 +751,10 @@ impl Game<'_> { 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. @@ -769,6 +771,20 @@ impl Game<'_> { } } } + 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.eye_y(), m.position.z]), + 1.0, + 1.0, + ); + } if killed && let Some(Who::Mob(killer)) = source.attacker { self.zombie_killed(killer, target); } @@ -939,12 +955,12 @@ impl Game<'_> { if !self.creative && let Some(p) = self.player.as_mut() { - p.fire_ticks = p.fire_ticks.max(seconds * 20); + p.ignite_for_ticks(seconds * 20)?; } } Who::Mob(id) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { - m.fire_ticks = m.fire_ticks.max(seconds * 20); + m.ignite_for_ticks(seconds * 20); } } }, @@ -1586,7 +1602,7 @@ impl Game<'_> { Who::Player => { if !self.creative { if let Some(p) = self.player.as_mut() { - p.fire_ticks = p.fire_ticks.max(100); + p.ignite_for_ticks(100)?; } self.mob_hits_player( 5.0, @@ -1598,7 +1614,7 @@ impl Game<'_> { Who::Mob(id) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { if !m.kind.flags.fire_immune { - m.fire_ticks = m.fire_ticks.max(100); + m.ignite_for_ticks(100); } m.damage(5.0, source); } @@ -1811,6 +1827,36 @@ impl Game<'_> { .as_ref() .map(|h| h.item.to_string()) .unwrap_or_default(); + if item == "minecraft:water_bucket" + && self.mobs[index].species() == Species::Axolotl + && self.mobs[index].alive() + { + let mut filled = ItemStack::new("minecraft:axolotl_bucket", 1); + filled.extra = Some(Box::new(horizon_client::item_data::StackData { + other: vec![( + "minecraft:bucket_entity_data".into(), + horizon_client::entity_nbt::bucket_data(&self.mobs[index]), + )], + ..Default::default() + })); + self.audio.play( + "minecraft:item.bucket.fill_axolotl", + Some(self.mobs[index].center()), + 1.0, + 1.0, + ); + self.trigger_item("minecraft:filled_bucket", &filled); + self.mobs[index].removed = true; + if self.creative { + if let Some(rest) = self.give(filled) { + self.spawn_item(rest, self.eye_position().unwrap_or([0.0; 3]), [0.0; 3], 40); + } + } else { + self.inventory[self.selected] = Some(filled); + } + self.swing_arm(); + return Ok(true); + } let creative = self.creative; let selected = self.selected; if self.interact_zombie_villager(index, &item) { diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 23488c3fa..7a94c5696 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1177,6 +1177,9 @@ impl Game<'_> { // MobBucketItem.checkExtraContent: the mob (from the bucket, so // persistent) calls out, then ENTITY_PLACE. if let Some(id) = self.spawn_mob_at(kind, target, true) { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + horizon_client::entity_nbt::load_bucket_data(m, &stack); + } self.mob_placed(id)?; } self.post_block_game_event( diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 3c1075f5c..1dcd8c0e7 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -309,11 +309,11 @@ impl Game<'_> { _ => {} } // Entity.thunderHit: burning (8 seconds) and 5 lightning damage. - m.fire_ticks = if m.fire_ticks + 1 == 0 { - 160 - } else { - m.fire_ticks + 1 - }; + m.fire_ticks += 1; + if m.fire_ticks == 0 { + m.ignite_for_ticks(160); + } + m.damage(5.0, damage); } if !events.is_empty() { @@ -323,11 +323,12 @@ impl Game<'_> { && inside([p.x, p.y, p.z]) { if let Some(p) = self.player.as_mut() { - p.fire_ticks = if p.fire_ticks + 1 == 0 { - 160 - } else { - p.fire_ticks + 1 - }; + p.fire_ticks += 1; + if p.fire_ticks == 0 + && let Err(error) = p.ignite_for_ticks(160) + { + self.error = Some(error.to_string()); + } } self.hurt_player_by("minecraft:lightning_bolt", 5.0); } diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index bd8901ff0..e66e68355 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -10,7 +10,7 @@ use std::collections::BTreeMap; #[derive(Default)] pub(super) struct Stats { pub(super) values: BTreeMap>, - loaded: bool, + pub(super) loaded: bool, /// Ticks until the phantom spawner runs again. phantom_tick: i32, /// Statistic changes (type, key, amount; `None` = reset) for the diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 2cdb2924b..9000092eb 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1569,7 +1569,7 @@ impl Renderer { /// The Mipmap Levels option: block textures sample at most `levels` /// reduced copies (0: none). pub fn set_mipmap_levels(&mut self, levels: u32) { - let levels = levels.min(self.mip_levels - 1); + let levels = sprite_mipmap_limit(levels, self.sprite_texture.width(), self.mip_levels); if levels == self.mipmaps { return; } @@ -1697,18 +1697,12 @@ impl Renderer { ); } fn animate(&mut self, tick: u64) { - let sprite_size = self.sprite_texture.width(); - for (animation, previous) in &mut self.animations { - let frame = animation.frame(tick); - if frame == *previous { - continue; - } - *previous = frame; - let (mips, levels) = mip_chain(animation.pixels(frame), sprite_size, 1); - let mut offset = 0; - for level in 0..levels.min(self.mip_levels) { - let size = sprite_size >> level; - let bytes = (size * size * 4) as usize; + animate_sprites( + &mut self.animations, + tick, + self.sprite_texture.width(), + self.mip_levels, + |layer, level, size, pixels| { self.queue.write_texture( wgpu::TexelCopyTextureInfo { texture: &self.sprite_texture, @@ -1716,11 +1710,11 @@ impl Renderer { origin: wgpu::Origin3d { x: 0, y: 0, - z: animation.layer, + z: layer, }, aspect: wgpu::TextureAspect::All, }, - &mips[offset..offset + bytes], + pixels, wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 4), @@ -1732,9 +1726,8 @@ impl Renderer { depth_or_array_layers: 1, }, ); - offset += bytes; - } - } + }, + ); } pub fn render(&mut self, frame: &Frame) -> Result { if self.suspended { @@ -2540,3 +2533,65 @@ mod tests { assert!(super::outline_vertices(&[], glam::DVec3::ZERO).is_empty()); } } + +fn sprite_mipmap_limit(requested: u32, size: u32, available: u32) -> u32 { + // 16px textures are doubled in this atlas; mip1 retains their original texels. + let upscale = (size / 16).max(1).ilog2(); + requested.saturating_add(upscale).min(available - 1) +} +fn animate_sprites( + animations: &mut [(crate::sprites::SpriteAnimation, usize)], + tick: u64, + size: u32, + max_levels: u32, + mut write: impl FnMut(u32, u32, u32, &[u8]), +) { + for (animation, previous) in animations { + let frame = animation.frame(tick); + if frame == *previous { + continue; + } + *previous = frame; + let (mips, levels) = mip_chain(animation.pixels(frame), size, 1); + let mut offset = 0; + for level in 0..levels.min(max_levels) { + let edge = size >> level; + let bytes = (edge * edge * 4) as usize; + write(animation.layer, level, edge, &mips[offset..offset + bytes]); + offset += bytes; + } + } +} +#[cfg(test)] +mod sprite_upload_tests { + use super::*; + #[test] + fn mipmap_option_keeps_real_16px_reductions() { + for levels in 0..=4 { + assert_eq!(sprite_mipmap_limit(levels, 32, 6), levels + 1); + assert_eq!(sprite_mipmap_limit(levels, 16, 5), levels); + } + } + #[test] + fn animation_updates_entire_layer_every_mip_once() { + for size in [16, 32] { + let animation = crate::sprites::test_animation(size, 7); + let pixels = animation.pixels(animation.frame(1)).to_vec(); + let (expected, levels) = mip_chain(&pixels, size, 1); + let mut animations = vec![(animation, 0)]; + let mut writes = Vec::new(); + let mut record = |layer, level, edge, data: &[u8]| { + assert_eq!(layer, 7); + assert_eq!(edge, size >> level); + assert_eq!(data.len(), (edge * edge * 4) as usize); + writes.push(data.to_vec()); + }; + animate_sprites(&mut animations, 0, size, levels, &mut record); + animate_sprites(&mut animations, 1, size, levels, &mut record); + animate_sprites(&mut animations, 1, size, levels, &mut record); + assert_eq!(writes.len(), levels as usize); + assert_eq!(writes[0], pixels); + assert_eq!(writes.concat(), expected); + } + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 877869c88..93b720564 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1375,3 +1375,33 @@ mod tests { ); } } + +pub fn take_held_drop(slot: &mut Option, all: bool) -> Option { + let stack = slot.as_mut()?; + if stack.count == 0 { + return None; + } + let count = if all { stack.count } else { 1 }; + let thrown = ItemStack { + count, + ..stack.clone() + }; + stack.count -= count; + if stack.count == 0 { + *slot = None; + } + Some(thrown) +} +#[cfg(test)] +mod held_drop_tests { + use super::*; + #[test] + fn one_all_and_empty_drop() { + let mut slot = Some(ItemStack::new("minecraft:stone", 4)); + assert_eq!(take_held_drop(&mut slot, false).unwrap().count, 1); + assert_eq!(slot.as_ref().unwrap().count, 3); + assert_eq!(take_held_drop(&mut slot, true).unwrap().count, 3); + assert!(slot.is_none()); + assert!(take_held_drop(&mut slot, false).is_none()); + } +} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 1ef8e5de9..42bc8e2f5 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -938,8 +938,9 @@ pub enum MobEvent { at: [f64; 3], amount: u32, }, - /// Apply an effect to the player (witch potions, bee stings, cave spider poison). + /// Regeneration support after an axolotl-assisted kill. AxolotlSupportPlayer, + /// Apply an effect to the player (witch potions, bee stings, cave spider poison). EffectPlayer { effect: &'static str, ticks: i32, @@ -1151,6 +1152,20 @@ pub struct Seen { pub stats: [f64; 3], } impl Mob { + pub fn burning_time(&self) -> f64 { + let base = finalize::value(self, finalize::Attr::BurningTime); + let protection: u32 = gear::ARMOR + .into_iter() + .map(|slot| gear::level(self, slot, "minecraft:fire_protection")) + .sum(); + (base - 0.15 * f64::from(protection)).max(0.0) + } + pub fn ignite_for_ticks(&mut self, ticks: i32) { + self.fire_ticks = self + .fire_ticks + .max((f64::from(ticks) * self.burning_time()).ceil() as i32); + } + /// What other mobs see of this one this tick (`player`: the player's /// UUID, which villagers' reputation is keyed by). pub fn seen(&self, player: Option<[i32; 4]>) -> Seen { diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 6f010338f..50b1102ca 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -401,8 +401,13 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds()); if fire > 0.0 && !m.kind.flags.fire_immune { - m.fire_ticks = - crate::motion::environment::ignite_contact(m.fire_ticks, false, &mut m.random); + let multiplier = m.burning_time(); + m.fire_ticks = crate::motion::environment::ignite_contact( + m.fire_ticks, + false, + &mut m.random, + multiplier, + ); m.damage(fire, Damage::of(DamageKind::InFire)); } // Fire: water extinguishes, lava ignites, burning hurts every second. @@ -416,7 +421,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { )); } if m.fluids.in_lava && !m.kind.flags.fire_immune { - m.fire_ticks = m.fire_ticks.max(300); + m.ignite_for_ticks(300); m.damage(4.0, Damage::of(DamageKind::Lava)); } if m.fire_ticks > 0 { @@ -666,7 +671,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & } // Mob.aiStep: undead burn in daylight. if m.kind.flags.burns_in_day && m.alive() && sun_burn_tick(m, w) && m.extra.head.is_none() { - m.fire_ticks = m.fire_ticks.max(160); + m.ignite_for_ticks(160); } species_ai_step(m, w, events); } diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index e0bc6c0a8..ac314c730 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -641,10 +641,7 @@ fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { } Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; - s.alive - && !s.playing_dead - && m.distance_sqr(s.position) <= range * range - && m.sees(w, who) + s.alive && m.distance_sqr(s.position) <= range * range && m.sees(w, who) } } } @@ -1430,7 +1427,7 @@ impl B { 1.1 }; let close = if m.species() == Species::Axolotl { - 4 + cx.lr.next_int_bound(12).unwrap_or(0) + 4 } else { 2 }; @@ -2282,13 +2279,21 @@ pub fn set_play_dead(m: &mut Mob) { mem(m).play_dead_ticks.set(super::axolotl::PLAY_DEAD_TICKS); } pub fn hunting_cooldown(m: &Mob) -> Option { - mem_ref(m).and_then(|mm| mm.hunting_cooldown.get().map(|_| mm.hunting_cooldown.ttl)) + mem_ref(m).and_then(|mm| { + mm.hunting_cooldown + .get() + .and_then(|_| (mm.hunting_cooldown.ttl > 0).then_some(mm.hunting_cooldown.ttl)) + }) } pub fn set_hunting_cooldown(m: &mut Mob, ticks: i64) { if m.extra.animal_brain.is_none() { init(m, i64::from(m.id)); } - mem(m).hunting_cooldown.set_ttl(true, ticks); + if ticks > 0 { + mem(m).hunting_cooldown.set_ttl(true, ticks); + } else { + mem(m).hunting_cooldown.clear(); + } } fn validate_play_dead(b: &mut Brain) -> bool { let Some(ticks) = b.mem.play_dead_ticks.value() else { @@ -2395,7 +2400,7 @@ fn axolotl_action(m: &mut Mob, cx: &mut Bx, action: AxolotlAction, until: &mut i .w .target_info(target) .is_some_and(|t| m.within_melee_range(&t)) - && visible_test(m, cx.w, target) + && visible_contains(m, cx.w, target) { mem(m).walk_target.clear(); } else { @@ -2417,7 +2422,7 @@ fn axolotl_action(m: &mut Mob, cx: &mut Bx, action: AxolotlAction, until: &mut i let Some(target) = mm.attack_target.value() else { return false; }; - if !visible_test(m, cx.w, target) + if !visible_contains(m, cx.w, target) || !cx .w .target_info(target) @@ -2435,7 +2440,6 @@ fn axolotl_action(m: &mut Mob, cx: &mut Bx, action: AxolotlAction, until: &mut i events: cx.events, }, ); - m.sound("entity.axolotl.attack", cx.events); mem(m).attack_cooling_down.set_ttl(true, 20); true } @@ -2613,7 +2617,7 @@ fn axolotl_package(seed: i64) -> Vec { e( Idle, B::MakeLove { - t: Timed::new(325, 325), + t: Timed::new(110, 110), spawn_at: 0, }, ), @@ -2864,3 +2868,23 @@ mod axolotl_parity_tests { assert!(kind_for_species(Species::Axolotl).is_some()); } } + +#[cfg(test)] +mod breeding_duration_tests { + use super::*; + #[test] + fn axolotl_breeding_uses_native_110_tick_timeout() { + let package = axolotl_package(1); + let timed = package + .iter() + .find_map(|e| { + if let B::MakeLove { t, .. } = &e.b { + Some(t) + } else { + None + } + }) + .unwrap(); + assert_eq!((timed.min, timed.max), (110, 110)); + } +} diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 0e5a0a2ec..805a58bb2 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -404,9 +404,10 @@ pub enum Attr { SpawnReinforcements, JumpStrength, Armor, + BurningTime, } impl Attr { - pub const ALL: [Self; 8] = [ + pub const ALL: [Self; 9] = [ Self::MaxHealth, Self::MovementSpeed, Self::FollowRange, @@ -415,6 +416,7 @@ impl Attr { Self::SpawnReinforcements, Self::JumpStrength, Self::Armor, + Self::BurningTime, ]; pub fn name(self) -> &'static str { match self { @@ -426,6 +428,7 @@ impl Attr { Self::SpawnReinforcements => "spawn_reinforcements", Self::JumpStrength => "jump_strength", Self::Armor => "armor", + Self::BurningTime => "burning_time", } } /// `RangedAttribute` bounds. @@ -438,6 +441,7 @@ impl Attr { Self::KnockbackResistance | Self::SpawnReinforcements => (0.0, 1.0), Self::JumpStrength => (0.0, 32.0), Self::Armor => (0.0, 30.0), + Self::BurningTime => (0.0, 1024.0), } } } @@ -476,7 +480,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 { .as_ref() .and_then(|s| s.bases.iter().find(|(x, _)| *x == a).map(|(_, v)| *v)) .or_else(|| default_value(m, a)) - .unwrap_or(0.0) + .unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 }) } /// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`). fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { @@ -560,7 +564,7 @@ fn refresh(m: &mut Mob, a: Attr) { Attr::KnockbackResistance => m.attrs.knockback_resistance = value(m, a), Attr::SpawnReinforcements => m.attrs.spawn_reinforcements = value(m, a), Attr::JumpStrength => m.attrs.jump_strength = value(m, a), - Attr::Armor => {} + Attr::Armor | Attr::BurningTime => {} } } /// The value without the transient baby modifier (`speed_bonus` applies diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 6b0996b5b..e435b6ec5 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1000,7 +1000,7 @@ impl Goal for MeleeAttack { let Some(t) = m.target_info(cx.w) else { return false; }; - if !t.alive || !t.can_be_seen_as_enemy { + if !t.alive { return false; } let path = m.create_path_to_entity(cx.w, [t.position.x, t.position.y, t.position.z], 0); @@ -1012,7 +1012,7 @@ impl Goal for MeleeAttack { let Some(t) = m.target_info(cx.w) else { return false; }; - if !t.alive || !t.can_be_seen_as_enemy { + if !t.alive { return false; } if !self.follow_unseen { @@ -2061,12 +2061,7 @@ impl Goal for TryFindWater { !m.ai.nav.is_done() } fn start(&mut self, m: &mut Mob, cx: &mut Cx) { - let speed = if m.species() == Species::Axolotl { - 0.15 - } else { - 1.0 - }; - m.nav_move_to(cx.w, self.wanted, speed); + m.nav_move_to(cx.w, self.wanted, 1.0); } } /// `MoveToBlockGoal`'s shared state: search, walk to and stay at a block. diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1e940a981..9bd50a388 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -140,7 +140,6 @@ pub struct PlayerMotion { pub fire_ticks: i32, pub air: i32, pub respiration: i32, - pub(crate) first_tick: bool, pub position: Vec3, pub velocity: Vec3, @@ -205,6 +204,26 @@ fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) } impl PlayerMotion { + pub fn load_environment_once( + &mut self, + pending: &mut bool, + extra: Option<&horizon_world::nbt::Tag>, + ) { + if std::mem::take(pending) { + self.fire_ticks = extra + .and_then(|t| crate::save::number(t.get("Fire"))) + .unwrap_or(-20) as i32; + self.air = extra + .and_then(|t| crate::save::number(t.get("Air"))) + .unwrap_or(300) as i32; + } + } + pub fn ignite_for_ticks(&mut self, ticks: i32) -> Result<()> { + let scaled = (f64::from(ticks) * self.attribute("minecraft:burning_time")?).ceil() as i32; + self.fire_ticks = self.fire_ticks.max(scaled); + Ok(()) + } + pub fn new(resources: &MotionResources, position: Vec3) -> Result { // Process-owned identities determine native collection callback order. // Differential fixtures can replay a reference process's identities. @@ -279,10 +298,9 @@ impl PlayerMotion { eye_in_water: false, in_lava: false, swimming: false, - fire_ticks: 0, + fire_ticks: -20, air: 300, respiration: 0, - first_tick: true, speed: 0.0, item_use_speed: None, last_climbable: None, @@ -538,7 +556,8 @@ impl MotionWorld<'_, '_, '_> { let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying - && !self.player.in_water; + && !self.player.in_water + && !self.player.in_lava; if jumping && !toggled && !was_jumping && !self.player.fall_flying && can_glide { self.player.fall_flying = true; } @@ -548,7 +567,8 @@ impl MotionWorld<'_, '_, '_> { let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying - && !self.player.in_water; + && !self.player.in_water + && !self.player.in_lava; if !still { self.player.fall_flying = false; } else if (self.player.fall_fly_ticks + 1) % 10 == 0 @@ -587,8 +607,11 @@ impl MotionWorld<'_, '_, '_> { /// Resident simulation phases in native order. Enclosing entity/world tick /// services are still incomplete; this composes clocks, movement and hunger. pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> { - self.player.health.advance_clock(); self.update_fluid_environment()?; + self.simulation_tick_with_fluids(direction, jumping) + } + fn simulation_tick_with_fluids(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> { + self.player.health.advance_clock(); self.tick_environment_damage()?; let previous = self.player.position; self.player.swimming = self.player.sprinting @@ -616,7 +639,7 @@ impl MotionWorld<'_, '_, '_> { self.player.auto_jump_time -= 1; keys.jump = true; } - self.sample_fluid_environment(false)?; + self.update_fluid_environment()?; self.player.sprint_input_tick(keys)?; self.player.shift_key_down = keys.shift; let direction = keys.direction(); @@ -628,7 +651,7 @@ impl MotionWorld<'_, '_, '_> { } else { None }; - self.simulation_tick( + self.simulation_tick_with_fluids( crate::input::modify_input(direction, self.player.item_use_speed, sneak), keys.jump, ) @@ -665,11 +688,8 @@ impl MotionWorld<'_, '_, '_> { input.x = 0.0; input.z = 0.0; } - if self.player.shift_key_down - && !self.player.flying - && (self.player.in_water || self.player.in_lava) - { - self.player.velocity.y -= 0.04; + if self.player.shift_key_down && !self.player.flying && self.player.in_water { + self.player.velocity.y -= f64::from(0.04f32); } if self.player.jumping { let height = self.player.fluids.fluid_height( @@ -684,7 +704,7 @@ impl MotionWorld<'_, '_, '_> { && (self.player.in_water || self.player.in_lava) && (!self.player.ground.on_ground || height > 0.4) { - self.player.velocity.y += 0.04; + self.player.velocity.y += f64::from(0.04f32); } else if self.player.ground.on_ground && self.player.no_jump_delay == 0 { self.jump_from_ground()?; self.player.no_jump_delay = 10; @@ -692,6 +712,21 @@ impl MotionWorld<'_, '_, '_> { } else { self.player.no_jump_delay = 0; } + if self.player.swimming { + let look_y = f64::from(-self.player.pitch.to_radians().sin()); + let near_surface = BlockPos::containing(Vec3::new( + self.player.position.x, + self.player.position.y + 0.9, + self.player.position.z, + )); + if look_y <= 0.0 + || self.player.jumping + || self.fluid_at(near_surface)?.kind() != horizon_world::fluid::FluidKind::Empty + { + let blend = if look_y < -0.2 { 0.085 } else { 0.06 }; + self.player.velocity.y += (look_y - self.player.velocity.y) * blend; + } + } if self.player.fall_flying { self.travel_fall_flying()?; } else if self.player.flying { @@ -1492,7 +1527,7 @@ mod tests { } w.player.fire_ticks = 160; w.controlled_simulation_tick(Default::default()).unwrap(); - assert_eq!(w.player.fire_ticks, 0); + assert!(w.player.fire_ticks <= 0); w.player.air = -19; w.player.health.hurt.cooldown = 0; let hp = w.player.health.health(); @@ -1525,16 +1560,28 @@ mod tests { } w.player.position = Vec3::new(20.5, 4.0, 20.5); w.player.velocity = Vec3::ZERO; + w.player.fire_ticks = -20; w.player.health.hurt.cooldown = 0; let hp = w.player.health.health(); w.controlled_simulation_tick(Default::default()).unwrap(); - assert!(w.player.fire_ticks > 0); + assert!( + w.player.fire_ticks < 0, + "direct fire hurts during the immunity delay" + ); assert!(w.player.health.health() < hp); w.player.status.fire_resistance = true; w.player.health.hurt.cooldown = 0; let hp = w.player.health.health(); w.controlled_simulation_tick(Default::default()).unwrap(); assert_eq!(w.player.health.health(), hp); + w.player.invulnerable = true; + w.player.fire_ticks = -20; + w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!( + w.player.fire_ticks, 1, + "creative fire contact must remain visible" + ); + w.player.invulnerable = false; // Sprint swimming must keep full input, not the dry crawl/sneak multiplier. for x in 19..=21 { for y in 2..=7 { @@ -1563,6 +1610,42 @@ mod tests { w.player.velocity ); assert!(!w.player.moving_slowly()); + w.player.position = Vec3::new(20.5, 4.0, 20.5); + w.player.velocity = Vec3::ZERO; + w.player.pitch = 45.0; + w.controlled_simulation_tick(crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }) + .unwrap(); + assert!( + w.player.velocity.y < -0.04, + "look down must steer a swimming player downward" + ); + w.player.position = Vec3::new(20.5, 4.0, 20.5); + w.player.velocity = Vec3::ZERO; + w.player.pitch = -45.0; + w.controlled_simulation_tick(crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }) + .unwrap(); + assert!( + w.player.velocity.y > 0.02, + "look up must steer a submerged swimmer upward" + ); + let extra = horizon_world::nbt::Tag::compound([ + ("Fire", horizon_world::nbt::Tag::Short(160)), + ("Air", horizon_world::nbt::Tag::Short(8)), + ]); + let mut pending = true; + w.player.load_environment_once(&mut pending, Some(&extra)); + assert_eq!((w.player.fire_ticks, w.player.air), (160, 8)); + let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + respawn.load_environment_once(&mut pending, Some(&extra)); + assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300)); w.player.in_water = false; assert!( w.player.moving_slowly(), diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index 1ddd79047..9d5044b6f 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -12,7 +12,7 @@ use horizon_world::{ pub(super) const WATER: FluidTagId = FluidTagId(0); pub(super) const LAVA: FluidTagId = FluidTagId(1); impl MotionWorld<'_, '_, '_> { - fn fluid_at(&self, p: BlockPos) -> Result { + pub(super) fn fluid_at(&self, p: BlockPos) -> Result { Ok(FluidState::from_block( self.assets .registry @@ -21,9 +21,6 @@ impl MotionWorld<'_, '_, '_> { )?) } pub(super) fn update_fluid_environment(&mut self) -> Result<()> { - self.sample_fluid_environment(true) - } - pub(super) fn sample_fluid_environment(&mut self, push: bool) -> Result<()> { let mut fluids = std::mem::take(&mut self.player.fluids); let result = fluids .update(self, false, 4096) @@ -38,7 +35,7 @@ impl MotionWorld<'_, '_, '_> { if self.player.in_water { self.player.fall_distance = 0.0; } - if push && !self.player.flying && !self.player.spectator { + if !self.player.flying && !self.player.spectator { fluids.apply_current(self, WATER, 0.014)?; fluids.apply_current( self, @@ -51,7 +48,6 @@ impl MotionWorld<'_, '_, '_> { )?; } self.player.fluids = fluids; - self.player.first_tick = false; Ok(()) } fn environment_hurt(&mut self, source: &str, damage: f32) -> Result<()> { @@ -69,9 +65,12 @@ impl MotionWorld<'_, '_, '_> { Ok(()) } pub(super) fn tick_environment_damage(&mut self) -> Result<()> { - if self.player.in_water || self.player.invulnerable || self.player.spectator { + if self.player.in_water || self.player.spectator { self.player.fire_ticks = 0; } + if self.player.invulnerable && self.player.fire_ticks > 1 { + self.player.fire_ticks = 1; + } if self.player.fire_ticks > 0 { if self.player.fire_ticks % 20 == 0 && !self.player.in_lava { self.environment_hurt("minecraft:on_fire", 1.0)?; @@ -98,24 +97,39 @@ impl MotionWorld<'_, '_, '_> { self.player.air = (self.player.air + 4).min(300); } if self.player.in_lava { - self.player.fire_ticks = self.player.fire_ticks.max(300); + if self.player.invulnerable { + self.player.fire_ticks = 1; + } else { + self.player.ignite_for_ticks(300)?; + } self.environment_hurt("minecraft:lava", 4.0)?; self.player.fall_distance *= 0.5; } Ok(()) } pub(super) fn apply_fire_contact(&mut self) -> Result<()> { - if self.player.spectator || self.player.invulnerable { + if self.player.spectator { self.player.fire_ticks = 0; return Ok(()); } let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds()); if damage > 0.0 { if !self.player.in_water { - self.player.fire_ticks = - ignite_contact(self.player.fire_ticks, true, &mut self.scene.random); + if self.player.invulnerable { + self.player.fire_ticks = 1; + } else { + let multiplier = self.player.attribute("minecraft:burning_time")?; + self.player.fire_ticks = ignite_contact( + self.player.fire_ticks, + true, + &mut self.scene.random, + multiplier, + ); + } } self.environment_hurt("minecraft:in_fire", damage)?; + } else if self.player.fire_ticks <= 0 { + self.player.fire_ticks = -20; } Ok(()) } @@ -308,7 +322,12 @@ impl MotionWorld<'_, '_, '_> { } } -pub(crate) fn ignite_contact(ticks: i32, player: bool, random: &mut impl RandomSource) -> i32 { +pub(crate) fn ignite_contact( + ticks: i32, + player: bool, + random: &mut impl RandomSource, + multiplier: f64, +) -> i32 { let ticks = if ticks < 0 { ticks + 1 } else if player { @@ -316,5 +335,24 @@ pub(crate) fn ignite_contact(ticks: i32, player: bool, random: &mut impl RandomS } else { ticks }; - if ticks >= 0 { ticks.max(160) } else { ticks } + if ticks >= 0 { + ticks.max((160.0 * multiplier).ceil() as i32) + } else { + ticks + } +} + +#[cfg(test)] +mod fire_ignition_tests { + use super::*; + #[test] + fn fire_hurts_before_twenty_tick_ignition_and_scales_duration() { + let mut r = horizon_core::random::LegacyRandom::new(3); + let mut ticks = -20; + for _ in 0..19 { + ticks = ignite_contact(ticks, true, &mut r, 0.4); + assert!(ticks < 0); + } + assert_eq!(ignite_contact(ticks, true, &mut r, 0.4), 64); + } } diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index cc93757ef..64473fbd6 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -151,6 +151,21 @@ impl Sprites { } } +#[cfg(test)] +pub(crate) fn test_animation(size: u32, layer: u32) -> SpriteAnimation { + let frame = |blue: u8| { + (0..size * size) + .flat_map(|i| [(i % size) as u8, (i / size) as u8, blue, 255]) + .collect() + }; + let metadata = AnimationMetadata::from_json(r#"{"frametime":1,"frames":[0,1]}"#).unwrap(); + SpriteAnimation { + layer, + frames: Arc::new(vec![frame(0), frame(99)]), + clip: Arc::new(metadata.clip(2).unwrap().unwrap()), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/tests/test_item_action_animation.py b/tests/test_item_action_animation.py deleted file mode 100644 index 145a21993..000000000 --- a/tests/test_item_action_animation.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Compile the actual drop and ignition branches with world effects stubbed.""" -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] - - -def block(source, start): - opening = source.index("{", start) - depth, end = 1, opening + 1 - while depth: - depth += (source[end] == "{") - (source[end] == "}") - end += 1 - return source[start:end] - - -class ItemActionAnimationTests(unittest.TestCase): - @unittest.skipUnless(shutil.which("rustc"), "rustc is required for action-policy tests") - def test_successful_drop_and_ignition_start_a_swing(self): - source = (ROOT / "crates/horizon-client/src/game.rs").read_text() - drop = block(source, source.index("fn drop_held(")) - ignition = block(source, source.index("if self.can_place_used_fire(target)")) - caller_start = source.index(" let swings = self.swings_started;", source.index("fn use_item_as_player(")) - caller = source[caller_start:source.index(" if self.use_potion_item", caller_start)] - program = """ -type Result = std::result::Result>; -enum UseResult { Pass, Fail, Success { swing: bool } } -#[derive(Clone)] struct ItemStack { count: u32, item: String } -struct Hit { pos: [i32; 3], face: [i32; 3] } -struct Facts; impl Facts { fn is_air(&self, state:u8)->bool { state == 0 } } -struct Res { facts:Facts } -struct Random; impl Random { fn next_float(&mut self)->f32 { 0.5 } } -struct World { air:bool, path:bool, random:Random } -impl World { fn block(&self,_:i32,_:i32,_:i32)->u8 { if self.air {0} else {1} } } -struct Audio { sounds:u32 } impl Audio { fn play(&mut self,_:&str,_:Option<[f64;3]>,_:f32,_:f32) {self.sounds+=1;} } -struct Game { selected:usize, inventory:[Option;1], alive:bool, swings:u32, drops:u32, res:Res, world:World, audio:Audio } -impl Game { - DROP - fn ignite(&mut self,item:&str)->Result<()> { - let stack=ItemStack {count:1,item:item.into()}; - CALLER - Ok(()) - } - fn use_tool(&mut self,stack:&ItemStack)->Result { - let item=stack.item.as_str(); - let hit = Hit { pos:[0;3], face:[0,1,0] }; - let at = |p:[i32;3]| p.map(f64::from); - let target = [0,1,0]; - IGNITION - Ok(UseResult::Fail) - } - fn eye_position(&self)->Option<[f64;3]> { self.alive.then_some([0.0;3]) } - fn player_drop(&mut self,stack:ItemStack) { self.drops += stack.count; } - fn swing_arm(&mut self) { self.swings += 1; } - fn try_light_portal(&mut self,_:[i32;3])->Result {Ok(false)} - fn may_build(&self)->bool {true} - fn can_place_used_fire(&self,_:[i32;3])->bool {self.world.air&&!self.world.path} - fn place_used_fire(&mut self,_:[i32;3])->Result<()> {Ok(())} - fn consume_held(&mut self) {} fn damage_held(&mut self,_:u32) {} -} -fn game()->Game { Game { selected:0, inventory:[Some(ItemStack { count:4,item:"minecraft:stone".into() })], alive:true, swings:0, drops:0, res:Res {facts:Facts}, world:World {air:true,path:false,random:Random}, audio:Audio {sounds:0} } } -#[test] fn dropping_one_and_all_swings_only_on_success() { - let mut g=game();g.drop_held(false);assert_eq!((g.drops,g.swings),(1,1)); - g.drop_held(true);assert_eq!((g.drops,g.swings),(4,2)); - g.drop_held(false);assert_eq!(g.swings,2); - let mut g=game();g.alive=false;g.drop_held(false);assert_eq!(g.swings,0); -} -#[test] fn successful_ignition_swings_but_blocked_ignition_does_not() { - for item in ["flint_and_steel","fire_charge"] { - let mut g=game();g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(1,1)); - let mut g=game();g.world.air=false;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0)); - let mut g=game();g.world.path=true;g.ignite(item).unwrap();assert_eq!((g.swings,g.audio.sounds),(0,0)); - } -} -""".replace("DROP", drop).replace("IGNITION", ignition).replace("CALLER", caller) - program = program.replace("self.swings_started", "self.swings") - with tempfile.TemporaryDirectory(prefix="horizon-item-action-") as directory: - path = Path(directory) - (path / "probe.rs").write_text(program) - compiled = subprocess.run( - ["rustc", "--edition=2024", "--test", str(path / "probe.rs"), "-o", str(path / "probe")], - capture_output=True, text=True, check=False, - ) - self.assertEqual(compiled.returncode, 0, compiled.stderr) - tested = subprocess.run([str(path / "probe")], capture_output=True, text=True, check=False) - self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_sprite_animation_upload.py b/tests/test_sprite_animation_upload.py deleted file mode 100644 index 5a7d14395..000000000 --- a/tests/test_sprite_animation_upload.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Exercise the actual animation uploader with a recording queue, without a GPU/window.""" -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - -from test_item_action_animation import block - -ROOT = Path(__file__).resolve().parents[1] - - -class SpriteAnimationUploadTests(unittest.TestCase): - @unittest.skipUnless(shutil.which("rustc"), "rustc is required") - def test_animation_updates_entire_layer_and_every_mip(self): - source = (ROOT / "crates/horizon-client/src/gfx.rs").read_text() - animate = block(source, source.index("fn animate(&mut self, tick: u64)")) - mips = block(source, source.index("fn mip_chain(")) - program = r""" -use std::cell::RefCell; -mod wgpu { - pub struct Texture(pub u32); - impl Texture {pub fn width(&self)->u32 {self.0}} - pub struct Origin3d {pub x:u32,pub y:u32,pub z:u32} - pub enum TextureAspect {All} - pub struct TexelCopyTextureInfo { - pub texture:&LIFETIME Texture,pub mip_level:u32,pub origin:Origin3d,pub aspect:TextureAspect, - } - pub struct TexelCopyBufferLayout {pub offset:u64,pub bytes_per_row:Option,pub rows_per_image:Option} - pub struct Extent3d {pub width:u32,pub height:u32,pub depth_or_array_layers:u32} -} -struct Queue {writes:RefCell>>} -impl Queue { - fn write_texture(&self, info:wgpu::TexelCopyTextureInfo, pixels:&[u8], layout:wgpu::TexelCopyBufferLayout, extent:wgpu::Extent3d) { - let size=info.texture.width() >> info.mip_level; - assert_eq!((extent.width,extent.height,extent.depth_or_array_layers),(size,size,1),"animation must update the entire mip, not a quarter"); - assert_eq!((layout.bytes_per_row,layout.rows_per_image,layout.offset),(Some(size*4),Some(size),0)); - assert_eq!((info.origin.x,info.origin.y,info.origin.z),(0,0,7)); - assert_eq!(pixels.len(),(size*size*4) as usize); - self.writes.borrow_mut().push(pixels.to_vec()); - } -} -struct Animation {layer:u32,pixels:Vec} -impl Animation {fn frame(&self,tick:u64)->usize {if tick==0 {0} else {1}} fn pixels(&self,_:usize)->&[u8] {&self.pixels}} -struct Gfx {animations:Vec<(Animation,usize)>,mip_levels:u32,sprite_texture:wgpu::Texture,queue:Queue} -MIPS -impl Gfx {ANIMATE} -fn main() { - for size in [16u32,32] { - let pixels:Vec=(0..size*size).flat_map(|i|[(i%size) as u8,(i/size) as u8,99,255]).collect(); - let (expected,levels)=mip_chain(&pixels,size,1); - let mut gfx=Gfx {animations:vec![(Animation {layer:7,pixels:pixels.clone()},0)],mip_levels:levels,sprite_texture:wgpu::Texture(size),queue:Queue {writes:RefCell::default()}}; - gfx.animate(0);assert!(gfx.queue.writes.borrow().is_empty()); - gfx.animate(1); - assert_eq!(gfx.queue.writes.borrow().len(),levels as usize); - assert_eq!(gfx.queue.writes.borrow()[0],pixels,"the bottom-right texel must animate too"); - assert_eq!(gfx.queue.writes.borrow().concat(),expected); - gfx.animate(1);assert_eq!(gfx.queue.writes.borrow().len(),levels as usize); - } -} -""".replace("LIFETIME", chr(39)+"a").replace("MIPS", mips).replace("ANIMATE", animate) - with tempfile.TemporaryDirectory(prefix="horizon-animation-upload-") as directory: - path = Path(directory) - (path / "probe.rs").write_text(program) - subprocess.run(["rustc", "--edition=2024", "-Awarnings", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True) - result = subprocess.run([str(path / "probe")], capture_output=True, text=True) - self.assertEqual(result.returncode, 0, result.stderr) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_world_runtime_reset.py b/tests/test_world_runtime_reset.py deleted file mode 100644 index e42827203..000000000 --- a/tests/test_world_runtime_reset.py +++ /dev/null @@ -1,39 +0,0 @@ -"""The actual world-entry reset must invalidate previously loaded player progress.""" -from pathlib import Path -import shutil -import subprocess -import tempfile -import unittest - -ROOT = Path(__file__).resolve().parents[1] - - -def run_reset(source): - start = source.index(" self.persist = Default::default();", source.index(" fn open_world(")) - reset = source[start:source.index(" // RandomSequences", start)] - program = """ -#[derive(Default)] struct Game {persist:bool,score:bool,fns:bool,bosses:bool,adv:bool,stats:bool} -impl Game {fn enter_world(&mut self) {RESET}} -fn main() { - let mut game=Game {persist:true,score:true,fns:true,bosses:true,adv:true,stats:true}; - game.enter_world(); - assert!(!game.adv,"loaded advancement progress must not survive world entry"); - assert!(!game.stats,"loaded statistics must not survive world entry"); -} -""".replace("RESET", reset) - with tempfile.TemporaryDirectory(prefix="horizon-world-reset-") as directory: - path = Path(directory) - (path / "probe.rs").write_text(program) - subprocess.run(["rustc", "--edition=2024", str(path / "probe.rs"), "-o", str(path / "probe")], check=True, capture_output=True) - return subprocess.run([str(path / "probe")], capture_output=True, text=True) - - -class WorldRuntimeResetTests(unittest.TestCase): - @unittest.skipUnless(shutil.which("rustc"), "rustc is required") - def test_world_entry_invalidates_loaded_progress(self): - result = run_reset((ROOT / "crates/horizon-client/src/game.rs").read_text()) - self.assertEqual(result.returncode, 0, result.stderr) - - -if __name__ == "__main__": - unittest.main() From 2236c9607f07b6bc95c139e6a1026a5c290b673c Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 10:08:37 -0400 Subject: [PATCH 04/23] Apply burning-time scaling to Fire Aspect ignition too --- crates/horizon-client/src/game/enchant_effects.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index e4b8e2fe5..77f262dbc 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -163,7 +163,7 @@ impl Game<'_> { && let Some(m) = self.mobs.get_mut(mob) && !m.kind.flags.fire_immune { - m.fire_ticks = m.fire_ticks.max((ignite * 20.0) as i32); + m.ignite_for_ticks((ignite * 20.0) as i32); } } /// Thorns on worn armor when a mob at `from` hits the player. From e8283540408eda842322db1cf4b457ea1dbf9541 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 11:02:27 -0400 Subject: [PATCH 05/23] Apply fluid currents to primed TNT and show fire in inventory preview --- crates/horizon-client/src/game/perspective.rs | 117 ++++-- crates/horizon-client/src/game/tnt.rs | 340 ++++++++++++++++-- 2 files changed, 397 insertions(+), 60 deletions(-) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 34a2f0398..ff500a08f 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -482,31 +482,12 @@ impl Game<'_> { * glam::Mat4::from_translation(glam::Vec3::new(0.0, height / 2.0 + offset_y, 0.0)) * glam::Mat4::from_rotation_z(std::f32::consts::PI) * glam::Mat4::from_rotation_x((y_angle * 20.0).to_radians()); - let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); - for q in verts.as_chunks::<4>().0 { - let p: [glam::Vec3; 4] = - std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos))); - let n = (p[1] - p[0]).cross(p[2] - p[0]); - // The winding gives inward normals: faces with n.z >= 0 point away. - if n.z >= 0.0 { - continue; - } - let n = n.normalize_or_zero(); - // Lighting.Entry.ENTITY_IN_UI, roughly: lit from the front and above. - let shade = (0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0); - let c = q[0].color; - let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s; - let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16); - let depth = p.iter().map(|v| v.z).sum::() / 4.0; - quads.push(( - depth, - p.map(|v| [v.x, v.y]), - std::array::from_fn(|i| q[i].uv), - color, - )); - } - // Far (low z) first: the viewer is on the +z side. - quads.sort_by(|a, b| a.0.total_cmp(&b.0)); + let fire = self + .player + .as_ref() + .filter(|p| p.fire_ticks > 0 && !p.spectator) + .map(|p| (p.dimensions.width, p.dimensions.height)); + let quads = player_preview_quads(verts, gui, fire, &atlas.sprites); let start = batch.vertices.len(); for (_, p, uv, color) in quads { batch.quad(p, uv, color); @@ -579,3 +560,89 @@ impl Game<'_> { ); } } + +fn player_preview_quads( + mut verts: Vec, + gui: glam::Mat4, + fire: Option<(f32, f32)>, + sprites: &std::collections::HashMap, +) -> Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> { + let flame_start = verts.len(); + if let Some((width, height)) = fire { + horizon_client::fire_render::flames( + [0.0; 3], + width, + height, + glam::DVec3::ZERO, + 0.0, + sprites, + 0xff, + &mut verts, + ); + } + let mut quads: Vec<(f32, [[f32; 2]; 4], [[f32; 2]; 4], u32)> = Vec::new(); + for (index, q) in verts.as_chunks::<4>().0.iter().enumerate() { + let p: [glam::Vec3; 4] = + std::array::from_fn(|i| gui.transform_point3(glam::Vec3::from_array(q[i].pos))); + let n = (p[1] - p[0]).cross(p[2] - p[0]); + // The winding gives inward normals: faces with n.z >= 0 point away. + if n.z >= 0.0 { + continue; + } + let n = n.normalize_or_zero(); + // Lighting.Entry.ENTITY_IN_UI, roughly: lit from the front and above. + let shade = if index * 4 >= flame_start { + 1.0 + } else { + (0.55 + 0.45 * -n.z - 0.15 * n.y).clamp(0.4, 1.0) + }; + let c = q[0].color; + let ch = |s: u32| ((((c >> s) & 255) as f32 * shade) as u32) << s; + let color = (c & 0xFF00_0000) | ch(0) | ch(8) | ch(16); + let depth = p.iter().map(|v| v.z).sum::() / 4.0; + quads.push(( + depth, + p.map(|v| [v.x, v.y]), + std::array::from_fn(|i| q[i].uv), + color, + )); + } + // Far (low z) first: the viewer is on the +z side. + quads.sort_by(|a, b| a.0.total_cmp(&b.0)); + quads +} + +#[cfg(test)] +mod preview_tests { + use super::*; + #[test] + fn burning_inventory_preview_keeps_visible_fullbright_flames() { + let rect = |u0| horizon_client::hud::Rect { + u0, + v0: 0.0, + u1: u0 + 0.1, + v1: 0.1, + w: 16, + h: 16, + }; + let sprites = std::collections::HashMap::from([ + ("block/fire_0".into(), rect(0.0)), + ("block/fire_1".into(), rect(0.5)), + ]); + for pitch in [-30.0f32, 0.0, 30.0] { + let gui = glam::Mat4::from_scale(glam::Vec3::new(30.0, 30.0, -30.0)) + * glam::Mat4::from_rotation_z(std::f32::consts::PI) + * glam::Mat4::from_rotation_x(pitch.to_radians()); + assert!(player_preview_quads(Vec::new(), gui, None, &sprites).is_empty()); + let quads = player_preview_quads(Vec::new(), gui, Some((0.6, 1.8)), &sprites); + assert!( + !quads.is_empty(), + "inventory projection must not cull all flames" + ); + assert!(quads.iter().all(|q| q.3 == 0xffff_ffff)); + assert!(quads.iter().any(|q| q.2[0][0] <= 0.1)); + assert!(quads.iter().any(|q| q.2[0][0] >= 0.5)); + assert!(quads.windows(2).all(|q| q[0].0 <= q[1].0)); + } + } +} diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 38889cf98..2a1404ace 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -31,6 +31,78 @@ impl PrimedTnt { ), ) } + fn tick( + &mut self, + world: &horizon_client::world::World, + collision: &horizon_world::block_collision::BlockCollisionRegistry<'_>, + assets: &horizon_client::assets::Assets, + facts: &horizon_client::blocks::BlockFacts, + ) -> Result<()> { + self.previous = self.position; + self.velocity.y -= 0.04; + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let wanted = self.velocity; + let moved = scene + .resolve(self.bounds(), wanted, 0.0, self.on_ground) + .unwrap_or(Vec3::ZERO); + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + self.on_ground = wanted.y < 0.0 && moved.y != wanted.y; + if moved.x != wanted.x { + self.velocity.x = 0.0; + } + if moved.z != wanted.z { + self.velocity.z = 0.0; + } + if moved.y != wanted.y { + self.velocity.y = 0.0; + } + self.velocity = Vec3::new( + self.velocity.x * 0.98, + self.velocity.y * 0.98, + self.velocity.z * 0.98, + ); + if self.on_ground { + self.velocity = Vec3::new( + self.velocity.x * 0.7, + self.velocity.y * -0.5, + self.velocity.z * 0.7, + ); + } + self.fuse -= 1; + if self.fuse > 0 { + // PrimedTnt updates immersion after moving and decrementing its fuse. + let mut fluids = + horizon_world::entity_fluid::EntityFluidInteraction::new([WATER, LAVA]); + let mut fluid_world = TntFluidWorld { + tnt: self, + world, + assets, + facts, + }; + fluids + .update(&mut fluid_world, false, 4096) + .map_err(|e| std::io::Error::other(e.to_string()))?; + fluids.apply_current(&mut fluid_world, WATER, 0.014)?; + fluids.apply_current( + &mut fluid_world, + LAVA, + if world.fast_lava { + 0.007 + } else { + 0.0023333333333333335 + }, + )?; + } + Ok(()) + } } impl Game<'_> { @@ -83,41 +155,12 @@ impl Game<'_> { let mut i = 0; while i < count { let t = &mut self.tnts[i]; - t.previous = t.position; - t.velocity.y -= 0.04; - let mut scene = SceneCollisions { - world: &self.world, - binding: self.collision, - subject: None, - }; - let wanted = t.velocity; - let moved = scene - .resolve(t.bounds(), wanted, 0.0, t.on_ground) - .unwrap_or(Vec3::ZERO); - t.position = Vec3::new( - t.position.x + moved.x, - t.position.y + moved.y, - t.position.z + moved.z, - ); - t.on_ground = wanted.y < 0.0 && moved.y != wanted.y; - if moved.x != wanted.x { - t.velocity.x = 0.0; - } - if moved.z != wanted.z { - t.velocity.z = 0.0; - } - if moved.y != wanted.y { - t.velocity.y = 0.0; - } - t.velocity = Vec3::new( - t.velocity.x * 0.98, - t.velocity.y * 0.98, - t.velocity.z * 0.98, - ); - if t.on_ground { - t.velocity = Vec3::new(t.velocity.x * 0.7, t.velocity.y * -0.5, t.velocity.z * 0.7); - } - t.fuse -= 1; + t.tick( + &self.world, + self.collision, + &self.res.assets, + &self.res.facts, + )?; if t.fuse <= 0 { let center = [ t.position.x, @@ -269,3 +312,230 @@ impl Game<'_> { } } } + +use horizon_world::{ + entity_fluid::{ + CurrentTarget, FluidInteractionWorld, FluidMembership, FluidSections, FluidTagId, + }, + fluid::{FluidHeightWorld, FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, +}; +const WATER: FluidTagId = FluidTagId(0); +const LAVA: FluidTagId = FluidTagId(1); +struct TntFluidWorld<'a> { + tnt: &'a mut PrimedTnt, + world: &'a horizon_client::world::World, + assets: &'a horizon_client::assets::Assets, + facts: &'a horizon_client::blocks::BlockFacts, +} +impl TntFluidWorld<'_> { + fn state(&self, p: BlockPos) -> horizon_world::registry::BlockStateId { + self.world.block(p.x, p.y, p.z) + } + fn fluid_at(&self, p: BlockPos) -> std::io::Result { + FluidState::from_block( + self.assets + .registry + .state(self.state(p)) + .ok_or_else(|| std::io::Error::other("missing TNT fluid state"))?, + ) + } +} +impl FluidMembership for TntFluidWorld<'_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + match tag { + WATER => matches!(kind, FluidKind::Water | FluidKind::FlowingWater), + LAVA => matches!(kind, FluidKind::Lava | FluidKind::FlowingLava), + _ => false, + } + } +} +impl CurrentTarget for TntFluidWorld<'_> { + type Error = std::io::Error; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> std::io::Result { + Ok(self.tnt.velocity) + } + fn add_delta_movement(&mut self, v: Vec3) -> std::io::Result<()> { + self.tnt.velocity = Vec3::new( + self.tnt.velocity.x + v.x, + self.tnt.velocity.y + v.y, + self.tnt.velocity.z + v.z, + ); + Ok(()) + } +} +impl FluidInteractionWorld for TntFluidWorld<'_> { + type Error = std::io::Error; + type Chunk = (i32, i32); + fn interaction_box(&mut self) -> std::io::Result> { + Ok(Some( + self.tnt.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> std::io::Result> { + Ok(self.world.chunks.contains_key(&(x, z)).then_some((x, z))) + } + fn chunk_sections(&mut self, _: Self::Chunk) -> std::io::Result> { + static SECTIONS: [bool; horizon_client::chunk::SECTIONS] = + [true; horizon_client::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: horizon_client::chunk::MIN_Y / 16, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.tnt.position.y + } + fn block_x(&self) -> i32 { + self.tnt.position.x.floor() as i32 + } + fn block_z(&self) -> i32 { + self.tnt.position.z.floor() as i32 + } + fn eye_y(&mut self) -> std::io::Result { + Ok(self.tnt.position.y + f64::from(0.98f32 * 0.85f32)) + } + fn fluid_state(&mut self, p: BlockPos) -> std::io::Result { + self.fluid_at(p) + } + fn fluid_height(&mut self, s: FluidState, p: BlockPos) -> std::io::Result { + s.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, s: FluidState, p: BlockPos) -> std::io::Result { + s.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, s: FluidState, p: BlockPos) -> std::io::Result { + flow_at(self, s, p) + } +} +impl FluidHeightWorld for TntFluidWorld<'_> { + type Error = std::io::Error; + fn fluid(&mut self, p: [i32; 3]) -> std::io::Result { + self.fluid_at(BlockPos::new(p[0], p[1], p[2])) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> std::io::Result { + Ok(self + .facts + .get(self.state(BlockPos::new(p[0], p[1], p[2]))) + .sturdy_full + & 1 + != 0) + } +} +impl FluidFlowWorld for TntFluidWorld<'_> { + type Error = std::io::Error; + type Block = horizon_world::registry::BlockStateId; + fn fluid(&mut self, p: BlockPos) -> std::io::Result { + self.fluid_at(p) + } + fn block(&mut self, p: BlockPos) -> std::io::Result { + Ok(self.state(p)) + } + fn blocks_fluid_flow(&self, s: Self::Block) -> bool { + self.assets + .blocks_fluid_flow + .contains(&self.assets.registry.state(s).unwrap().name) + } + fn is_ice_class(&self, s: Self::Block) -> bool { + self.facts + .get(s) + .classes + .iter() + .any(|c| c.as_ref() == "IceBlock") + } + fn is_face_sturdy( + &mut self, + s: Self::Block, + _: BlockPos, + d: horizon_core::geometry::Direction, + ) -> std::io::Result { + Ok(self.facts.get(s).sturdy_full & (1 << d as u8) != 0) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn primed_tnt_follows_water_currents_after_moving() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = horizon_client::assets::Assets::load(&root).unwrap(); + let facts = horizon_client::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let collision = horizon_client::collisions::load(&root, assets.registry).unwrap(); + let mut world = horizon_client::world::World::test_scene(&assets, 3).unwrap(); + let stone = assets.registry.default_state("minecraft:stone").unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let mut state = assets.registry.state(water).unwrap().clone(); + state.properties.insert("level".into(), "1".into()); + let flowing = assets.registry.resolve(&state).unwrap(); + for x in 19..=22 { + for z in 19..=21 { + world.set(x, 3, z, stone).unwrap(); + } + } + world.set(20, 4, 20, water).unwrap(); + world.set(21, 4, 20, flowing).unwrap(); + let at = Vec3::new(20.5, 4.0, 20.5); + let mut tnt = PrimedTnt { + position: at, + previous: at, + velocity: Vec3::ZERO, + fuse: 80, + on_ground: false, + }; + tnt.tick(&world, &collision, &assets, &facts).unwrap(); + assert_eq!( + tnt.position.x, at.x, + "current is applied after motion, not before" + ); + assert!( + (tnt.velocity.x - 0.014).abs() < 1e-12, + "water must push primed TNT east: {:?}", + tnt.velocity + ); + assert_eq!(tnt.fuse, 79); + tnt.tick(&world, &collision, &assets, &facts).unwrap(); + assert!((tnt.position.x - at.x - 0.014).abs() < 1e-12); + assert!(tnt.on_ground); + tnt.position = at; + tnt.velocity = Vec3::ZERO; + tnt.fuse = 1; + tnt.tick(&world, &collision, &assets, &facts).unwrap(); + assert_eq!(tnt.fuse, 0); + assert_eq!( + tnt.velocity.x, 0.0, + "expired TNT must not receive a current" + ); + world.set(21, 4, 20, water).unwrap(); + tnt.position = at; + tnt.velocity = Vec3::ZERO; + tnt.fuse = 80; + tnt.tick(&world, &collision, &assets, &facts).unwrap(); + assert_eq!( + tnt.velocity.x, 0.0, + "still water must not add horizontal motion" + ); + world + .set( + 20, + 3, + 20, + assets.registry.default_state("minecraft:air").unwrap(), + ) + .unwrap(); + tnt.on_ground = false; + tnt.velocity = Vec3::ZERO; + tnt.tick(&world, &collision, &assets, &facts).unwrap(); + assert!( + tnt.position.y < at.y && tnt.velocity.y < 0.0, + "TNT sinks; water does not add buoyancy" + ); + } +} From 027ac3cdf1b9447e98548fe964995e4aa09baa08 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:39:49 -0400 Subject: [PATCH 06/23] Address final axolotl bucket and fire review corrections --- crates/horizon-client/src/entity_nbt.rs | 29 ++++++++++++++++--- crates/horizon-client/src/mobs/ai.rs | 6 ++-- .../horizon-client/src/mobs/animal_brain.rs | 2 +- crates/horizon-client/src/motion.rs | 7 +++++ .../horizon-client/src/motion/environment.rs | 4 +-- 5 files changed, 37 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 84fc605e3..95f293295 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -598,7 +598,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.main_hand = None; } m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32; - m.persistent = flag(tag, "PersistenceRequired"); + m.persistent |= flag(tag, "PersistenceRequired"); m.extra.pick_up_loot = flag(tag, "CanPickUpLoot"); m.custom_name = custom_name(tag); if m.kind.category == "creature" { @@ -613,7 +613,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32; m.silent = flag(tag, "Silent"); m.invulnerable_flag = flag(tag, "Invulnerable"); - m.no_gravity = m.no_gravity || flag(tag, "NoGravity"); if m.species() == crate::mobs::Species::Creeper { m.extra.charged = flag(tag, "powered"); } @@ -1578,7 +1577,7 @@ pub fn bucket_data(m: &Mob) -> Tag { ("NoAI", m.no_ai), ("Silent", m.silent), ("NoGravity", m.no_gravity), - ("Glowing", m.glowing || m.has_effect("glowing")), + ("Glowing", m.glowing), ("Invulnerable", m.invulnerable_flag), ("PersistenceRequired", m.persistent), ] { @@ -1632,12 +1631,12 @@ pub fn load_bucket_data(m: &mut Mob, stack: &crate::items::ItemStack) { ("NoGravity", &mut m.no_gravity), ("Glowing", &mut m.glowing), ("Invulnerable", &mut m.invulnerable_flag), - ("PersistenceRequired", &mut m.persistent), ] { if let Some(v) = number(data.get(key)) { *flag = v != 0; } } + m.persistent |= flag(data, "PersistenceRequired"); if m.species() == crate::mobs::Species::Axolotl { crate::mobs::animal_brain::set_hunting_cooldown( m, @@ -1746,6 +1745,28 @@ mod axolotl_nbt_tests { ); assert_eq!(restored.custom_name.as_deref(), Some("Bucket friend")); assert_eq!(restored.health, 5.0); + m.glowing = false; + m.add_effect("glowing", 200, 0); + assert!(m.has_effect("glowing")); + assert!(bucket_data(&m).get("Glowing").is_none()); + m.glowing = true; + assert_eq!(number(bucket_data(&m).get("Glowing")), Some(1)); + for (persistent, expected) in [(None, false), (Some(0), false), (Some(1), true)] { + let mut data = Tag::Compound(Compound::new()); + if let Some(value) = persistent { + put(&mut data, "PersistenceRequired", Tag::Byte(value)); + } + let mut bucket = crate::items::ItemStack::new("minecraft:axolotl_bucket", 1); + bucket + .data_mut() + .set_other("minecraft:bucket_entity_data", Some(data)); + restored.persistent = false; + load_bucket_data(&mut restored, &bucket); + assert_eq!(restored.persistent, expected); + restored.persistent = true; + load_bucket_data(&mut restored, &bucket); + assert!(restored.persistent, "bucket data cannot clear persistence"); + } restored.ticks_frozen = 140; restored.ignite_for_ticks(160); assert_eq!(restored.ticks_frozen, 0); diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a99d09ddc..43f2d3527 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -400,6 +400,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.fall_distance = 0.0; } let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds()); + if fire > 0.0 { + m.ticks_frozen = 0; + } if fire > 0.0 && !m.kind.flags.fire_immune { let multiplier = m.burning_time(); m.fire_ticks = crate::motion::environment::ignite_contact( @@ -408,9 +411,6 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { &mut m.random, multiplier, ); - if m.fire_ticks >= 0 { - m.ticks_frozen = 0; - } m.damage(fire, Damage::of(DamageKind::InFire)); } // Fire: water extinguishes, lava ignites, burning hurts every second. diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 1d26333f3..9920235a9 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -1444,7 +1444,7 @@ impl B { }); mm.look_target.set(Tracker::Entity { who: adult, - eye: eyes, + eye: true, block_eye: eyes, }); true diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index b80d5f06d..16ebd5b19 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -2074,12 +2074,17 @@ mod tests { w.player.velocity = Vec3::ZERO; w.player.fire_ticks = -20; w.player.health.hurt.cooldown = 0; + w.player.ticks_frozen = 140; let hp = w.player.health.health(); w.controlled_simulation_tick(Default::default()).unwrap(); assert!( w.player.fire_ticks < 0, "direct fire hurts during the immunity delay" ); + assert_eq!( + w.player.ticks_frozen, 0, + "fire contact clears freeze during the delay" + ); assert!(w.player.health.health() < hp); w.player.status.fire_resistance = true; w.player.health.hurt.cooldown = 0; @@ -2088,7 +2093,9 @@ mod tests { assert_eq!(w.player.health.health(), hp); w.player.invulnerable = true; w.player.fire_ticks = -20; + w.player.ticks_frozen = 140; w.controlled_simulation_tick(Default::default()).unwrap(); + assert_eq!(w.player.ticks_frozen, 0); assert_eq!( w.player.fire_ticks, -19, "creative preserves the fire-contact delay" diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index 5af3cc98f..c1e34f5c0 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -110,6 +110,7 @@ impl MotionWorld<'_, '_, '_> { } let damage = fire_contact(self.scene, self.assets.registry, self.player.bounds()); if damage > 0.0 { + self.player.ticks_frozen = 0; if !self.player.in_water { let multiplier = self.player.attribute("minecraft:burning_time")?; let ticks = ignite_contact( @@ -119,9 +120,6 @@ impl MotionWorld<'_, '_, '_> { multiplier, ); self.player.set_remaining_fire_ticks(ticks); - if ticks >= 0 { - self.player.ticks_frozen = 0; - } } self.environment_hurt("minecraft:in_fire", damage)?; } else if self.player.fire_ticks <= 0 { From e9da898f972d21a4f62b368e95f1b89617f0479d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:04:45 +0200 Subject: [PATCH 07/23] Water cancels the player's fall damage (#180) The player's movement treated every fluid as empty: is_in_water was always false, LivingEntity.checkFallDamage's updateFluidInteraction was a no-op and Entity.move's fall-reset ray ignored water. A player landing in water (or a waterlogged block, a bubble column, kelp) still took the whole fall. Bind vanilla's Entity.updateFluidInteraction to the player over the existing horizon-world kernels (EntityFluidInteraction heights, eyes and currents, entity_fluid_tick, water_splash, fluid_flow): run it in the base tick and from checkFallDamage, read wasTouchingWater for isInWater, query the water's (first-query cached) shape in the FALLDAMAGE_RESETTING ray, halve the fall in lava after the first tick, and play the splash sound with bubble and splash particles. The scene motion harness gains water/lava fixtures (fluid_tick plus scripted falls through the real Entity.move) against the real vanilla updateFluidInteraction with the #water/#lava tags bound. Co-Authored-By: Claude Opus 5.5 --- .../examples/scene_motion_probe.rs | 40 ++- crates/horizon-client/src/game.rs | 31 ++ crates/horizon-client/src/landing.rs | 6 +- crates/horizon-client/src/motion.rs | 42 ++- crates/horizon-client/src/motion/fluids.rs | 330 ++++++++++++++++++ .../parity/VanillaSceneMotionOracle.java | 40 ++- tools/test_native_scene_motion.py | 119 ++++++- 7 files changed, 584 insertions(+), 24 deletions(-) create mode 100644 crates/horizon-client/src/motion/fluids.rs diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index b56da92fa..d5ef55d37 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -4,7 +4,7 @@ use horizon_client::{ Result, assets::Assets, collisions, - motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion}, + motion::{LAVA, MotionEvent, MotionResources, MotionWorld, PlayerMotion, WATER}, world::World, }; use horizon_core::geometry::Vec3; @@ -174,6 +174,31 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { velocity.y.to_bits(), velocity.z.to_bits() )), + MotionEvent::Splash { + high_speed, + volume, + pitch, + } => Some(format!( + "sound {} entity {:08x} {:08x}", + if *high_speed { "splash-high" } else { "splash" }, + volume.to_bits(), + pitch.to_bits() + )), + MotionEvent::SplashParticle { + bubble, + position, + velocity, + } => Some(format!( + "splash-particle {} {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}", + if *bubble { "bubble" } else { "splash" }, + position.x.to_bits(), + position.y.to_bits(), + position.z.to_bits(), + velocity.x.to_bits(), + velocity.y.to_bits(), + velocity.z.to_bits() + )), + MotionEvent::SplashEvent => Some("splash-event".into()), // The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so. MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()), MotionEvent::Waypoint { receiver, enabled } => Some(format!( @@ -415,6 +440,9 @@ fn main() -> Result<()> { p, )?; } + // Entity.baseTick's fluid phase alone (wasEyeInWater, + // updateFluidInteraction, lava fall halving, firstTick). + "fluid_tick" => world.fluid_base_tick()?, "travel" => world.travel_in_air(vector(&op["value"]))?, "tick" => { let v = vector(&op["value"]); @@ -541,14 +569,20 @@ fn main() -> Result<()> { let stuck = player.stuck_multiplier; writeln!( out, - "block {} frozen {} {} {} {:016x},{:016x},{:016x}", + "block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}", check_block.0, player.ticks_frozen, player.in_powder_snow, player.was_in_powder_snow, stuck.x.to_bits(), stuck.y.to_bits(), - stuck.z.to_bits() + stuck.z.to_bits(), + player.fluids.was_touching_water, + player.fluids.was_eye_in_water, + player.is_eye_in_fluid(WATER), + player.fluids.first_tick, + player.fluid_height(WATER).to_bits(), + player.fluid_height(LAVA).to_bits() )?; writeln!( out, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f2f4859e7..08a6934c4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2836,6 +2836,8 @@ impl Game<'_> { .iter() .flatten() .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); + // The dimension's FAST_LAVA: the Nether's lava pushes harder. + player.fluids.fast_lava = self.dim == Dim::Nether; let grounded = player.ground.on_ground; let before = ( grounded, @@ -2927,6 +2929,35 @@ impl Game<'_> { position, fall_distance, } => self.smash_landing_particles(state, position, fall_distance), + MotionEvent::Splash { + high_speed, + volume, + pitch, + } => { + let name = if high_speed { + "minecraft:entity.player.splash.high_speed" + } else { + "minecraft:entity.player.splash" + }; + self.audio.play(name, Some(feet), volume, pitch); + } + MotionEvent::SplashParticle { + bubble, + position, + velocity, + } => { + use horizon_client::particles::{ParticleOptions, ParticleType}; + let kind = if bubble { + ParticleType::Bubble + } else { + ParticleType::Splash + }; + self.particles.add( + &ParticleOptions::simple(kind), + [position.x, position.y, position.z], + [velocity.x, velocity.y, velocity.z], + ); + } _ => {} } } diff --git a/crates/horizon-client/src/landing.rs b/crates/horizon-client/src/landing.rs index e0e510820..6fb1f7580 100644 --- a/crates/horizon-client/src/landing.rs +++ b/crates/horizon-client/src/landing.rs @@ -219,7 +219,7 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> { type Error = Box; type State = BlockStateId; fn is_in_water(&mut self) -> Result { - Ok(false) + Ok(self.player.fluids.was_touching_water) } fn fall_distance(&self) -> f64 { self.player.fall_distance @@ -253,8 +253,8 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> { } impl LivingLandingWorld for MotionWorld<'_, '_, '_> { fn update_fluid_interaction(&mut self) -> Result { - Ok(false) - } // dry scene + self.update_fluids() + } fn is_server_level(&self) -> bool { true } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 8830fb6f4..131aa0df5 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -43,6 +43,9 @@ use std::{ sync::Arc, }; +mod fluids; +pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER}; + pub struct MotionResources { pub attributes: Arc, pub blocks: BoundMovementProperties, @@ -50,6 +53,7 @@ pub struct MotionResources { pub fall_reset: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, + pub fluids: FluidResources, } impl MotionResources { pub fn load(root: &Path, assets: &Assets) -> Result { @@ -86,6 +90,7 @@ impl MotionResources { Ok(Self { landing: crate::landing::load(root, &properties)?, health: crate::health::HealthResources::load(root)?, + fluids: FluidResources::load(root, assets)?, attributes, blocks: properties.bind(&MovementTags { fences: tag("minecraft:fences")?, @@ -150,6 +155,21 @@ pub enum MotionEvent { position: BlockPos, fall_distance: f64, }, + /// `Entity.doWaterSplashEffect`: the player's splash (or high-speed + /// splash) sound at its position... + Splash { + high_speed: bool, + volume: f32, + pitch: f32, + }, + /// ...its BUBBLE (else SPLASH) particles... + SplashParticle { + bubble: bool, + position: Vec3, + velocity: Vec3, + }, + /// ...and the SPLASH game event. + SplashEvent, } pub struct PlayerMotion { pub position: Vec3, @@ -213,6 +233,8 @@ pub struct PlayerMotion { pub health: crate::health::PlayerHealth, /// Status effects and armor protection seen by movement and damage. pub status: crate::effects::StatusFlags, + /// Water and lava around the player (`Entity.fluidInteraction`). + pub fluids: PlayerFluids, /// `Entity.isInPowderSnow` / `wasInPowderSnow`. pub in_powder_snow: bool, pub was_in_powder_snow: bool, @@ -313,6 +335,7 @@ impl PlayerMotion { sync_position: false, events: Vec::new(), attributes, + fluids: PlayerFluids::default(), in_powder_snow: false, was_in_powder_snow: false, ticks_frozen: 0, @@ -591,6 +614,7 @@ impl MotionWorld<'_, '_, '_> { // Entity.baseTick self.player.was_in_powder_snow = self.player.in_powder_snow; self.player.in_powder_snow = false; + self.fluid_base_tick()?; self.player.old_position = self.player.position; if self.player.jump_trigger_time > 0 { self.player.jump_trigger_time -= 1; @@ -1334,15 +1358,21 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { self.player.fall_distance } fn fall_reset_clip(&mut self, from: Vec3, to: Vec3) -> Result { - // Every fluid in this controlled scene is empty. Tagged reset blocks use - // a full block in ClipContext.FALLDAMAGE_RESETTING, not their collider. + // ClipContext.Block.FALLDAMAGE_RESETTING: tagged reset blocks are a full + // block, not their collider; ClipContext.Fluid.WATER: the water's shape. + // Both shapes are queried for every visited block (the water's first + // query fixes its cached shape), either one hitting ends the ray. let hit = traverse_blocks(from, to, 1_000_000, |p| { + let water = match self.water_clip(from, to, p) { + Ok(hit) => hit, + Err(e) => return Some(Err(e)), + }; let name = &self.assets.registry.state(self.block(p)).unwrap().name; - (self.resources.fall_reset.contains(name) - && VoxelShape::block().clip(from, to, p).is_some()) - .then_some(()) + let reset = self.resources.fall_reset.contains(name) + && VoxelShape::block().clip(from, to, p).is_some(); + (water || reset).then_some(Ok(())) })?; - Ok(hit.is_some()) + hit.transpose().map(|h| h.is_some()) } fn reset_fall_distance(&mut self) -> Result<()> { self.player.fall_distance = 0.0; diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs new file mode 100644 index 000000000..ef4746eaa --- /dev/null +++ b/crates/horizon-client/src/motion/fluids.rs @@ -0,0 +1,330 @@ +//! The player's fluid immersion over the resident scene: `Entity.updateFluidInteraction` +//! (water, waterlogged blocks, bubble columns and lava, with their currents), the +//! water-entry splash and the fall resets that hinge on touching water. +use super::*; +use horizon_world::{ + entity_fluid::{ + CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership, + FluidSections, FluidTagId, + }, + entity_fluid_tick::{self, EntityFluidTickWorld}, + fluid::{FluidHeightWorld, FluidKind, FluidState, FluidStateTable}, + fluid_flow::{FluidFlowWorld, flow_at}, + fluid_shape::FluidShapeCache, + water_splash::{self, SplashParticle, WaterSplashWorld}, +}; +use std::sync::Mutex; + +/// `FluidTags.WATER` and `FluidTags.LAVA`, the fluids with a current. +pub const WATER: FluidTagId = FluidTagId(0); +pub const LAVA: FluidTagId = FluidTagId(1); + +/// Per-state fluid facts the player's immersion and fall-reset rays read. +pub struct FluidResources { + states: FluidStateTable, + /// `isFaceSturdy(FULL)` per `Direction` (bit = ordinal). + sturdy: Vec, + /// `#minecraft:blocks_fluid_flow` membership. + blocks_flow: Vec, + /// `IceBlock` and its subclasses. + ice: Vec, + /// `FlowingFluid.shapes`: the shape of the first query of each fluid + /// state, kept for the whole process like the registered fluid's map. + pub shapes: Mutex, +} +impl FluidResources { + pub fn load(root: &Path, assets: &Assets) -> Result { + let facts = crate::blocks::BlockFacts::load(root, assets.registry)?; + Ok(Self { + states: FluidStateTable::new(assets.registry)?, + sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(), + blocks_flow: facts + .states + .iter() + .map(|s| assets.blocks_fluid_flow.contains(&*s.name)) + .collect(), + ice: facts.states.iter().map(|s| s.has_class("IceBlock")).collect(), + shapes: Mutex::new(FluidShapeCache::default()), + }) + } + pub fn fluid(&self, state: BlockStateId) -> FluidState { + self.states.get(state).unwrap_or(FluidState::EMPTY) + } + fn sturdy(&self, state: BlockStateId, d: Direction) -> bool { + self.sturdy + .get(state.0 as usize) + .is_some_and(|s| s & 1 << d as u8 != 0) + } +} +/// The player's `EntityFluidInteraction` and the water flags around it. +pub struct PlayerFluids { + pub interaction: EntityFluidInteraction, + /// `Entity.wasTouchingWater` (`isInWater`). + pub was_touching_water: bool, + /// `Entity.wasEyeInWater`. + pub was_eye_in_water: bool, + /// `Entity.firstTick`: no splash, and no lava, until the first base tick ends. + pub first_tick: bool, + /// The dimension's `FAST_LAVA` (the Nether), set by the game. + pub fast_lava: bool, +} +impl Default for PlayerFluids { + fn default() -> Self { + Self { + interaction: EntityFluidInteraction::new([WATER, LAVA]), + was_touching_water: false, + was_eye_in_water: false, + first_tick: true, + fast_lava: false, + } + } +} +fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool { + if tag == WATER { + matches!(kind, FluidKind::Water | FluidKind::FlowingWater) + } else { + matches!(kind, FluidKind::Lava | FluidKind::FlowingLava) + } +} +impl PlayerMotion { + pub fn fluid_height(&self, tag: FluidTagId) -> f64 { + self.fluids.interaction.fluid_height(&Membership, tag) + } + pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool { + self.fluids.interaction.is_eye_in_fluid(&Membership, tag) + } + /// `Entity.isInLava`. + pub fn is_in_lava(&self) -> bool { + !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA) + } +} +struct Membership; +impl FluidMembership for Membership { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + is_tagged(kind, tag) + } +} +impl MotionWorld<'_, '_, '_> { + fn fluid_at(&self, p: BlockPos) -> FluidState { + self.resources.fluids.fluid(self.block(p)) + } + /// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`, + /// the lava's fall halving, and the end of the first tick. + pub fn fluid_base_tick(&mut self) -> Result<()> { + self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER); + self.update_fluids()?; + if self.player.is_in_lava() { + self.player.fall_distance *= 0.5; + } + self.player.fluids.first_tick = false; + Ok(()) + } + /// `Entity.updateFluidInteraction`: immersion heights, then touching water + /// resets the fall and splashes on entry, then the currents push. + pub fn update_fluids(&mut self) -> Result { + let mut interaction = std::mem::take(&mut self.player.fluids.interaction); + let result = entity_fluid_tick::update(&mut interaction, self, WATER, LAVA, 1_000_000); + self.player.fluids.interaction = interaction; + result.map_err(|e| e.to_string().into()) + } + /// `ClipContext.Fluid.WATER` in a fall-reset ray: the water's shape. + pub(super) fn water_clip(&mut self, from: Vec3, to: Vec3, p: BlockPos) -> Result { + let fluid = self.fluid_at(p); + if !is_tagged(fluid.kind(), WATER) { + return Ok(false); + } + let resources = self.resources; + let shape = resources + .fluids + .shapes + .lock() + .map_err(|_| "fluid shape cache poisoned")? + .shape(self, fluid, p)?; + Ok(shape.clip(from, to, p).is_some()) + } +} +impl FluidMembership for MotionWorld<'_, '_, '_> { + fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool { + is_tagged(kind, tag) + } +} +impl CurrentTarget for MotionWorld<'_, '_, '_> { + type Error = Box; + fn is_player_class(&self) -> bool { + true + } + fn velocity(&mut self) -> Result { + Ok(self.player.velocity) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<()> { + // Entity.addDeltaMovement and setDeltaMovement keep only finite values. + let v = self.player.velocity; + let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z); + if delta.is_finite() && sum.is_finite() { + self.player.velocity = sum; + } + Ok(()) + } +} +impl FluidInteractionWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + type Chunk = (); + fn interaction_box(&mut self) -> Result> { + // Entity.getFluidInteractionBox (not riding). + Ok(Some( + self.player.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)), + )) + } + fn loaded_chunk(&mut self, x: i32, z: i32) -> Result> { + Ok(self.scene.chunks.contains_key(&(x, z)).then_some(())) + } + fn chunk_sections(&mut self, _: ()) -> Result> { + // Resident sections keep no fluid count: scanning the box finds no + // fluid where a section without fluid would have skipped it. + static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS]; + Ok(FluidSections { + minimum_section_y: crate::chunk::MIN_Y >> 4, + has_fluid: &SECTIONS, + }) + } + fn bounding_box_min_y(&self) -> f64 { + self.player.bounds().min_position().y + } + fn block_x(&self) -> i32 { + self.player.position.x.floor() as i32 + } + fn eye_y(&mut self) -> Result { + Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height)) + } + fn block_z(&self) -> i32 { + self.player.position.z.floor() as i32 + } + fn fluid_state(&mut self, p: BlockPos) -> Result { + Ok(self.fluid_at(p)) + } + fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.height_at(self, [p.x, p.y, p.z]) + } + fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result { + f.camera_height_at(self, [p.x, p.y, p.z]) + } + fn flow(&mut self, f: FluidState, p: BlockPos) -> Result { + flow_at(self, f, p) + } +} +impl EntityFluidTickWorld for MotionWorld<'_, '_, '_> { + /// `Player.isPushedByFluid`: not while flying. + fn is_pushed_by_fluid(&mut self) -> Result { + Ok(!self.player.flying) + } + fn reset_fall_distance(&mut self) -> Result<()> { + self.player.fall_distance = 0.0; + Ok(()) + } + fn was_touching_water(&self) -> bool { + self.player.fluids.was_touching_water + } + fn first_tick(&self) -> bool { + self.player.fluids.first_tick + } + fn water_splash(&mut self) -> Result<()> { + water_splash::water_splash(self, 1_000_000).map_err(|e| e.to_string())?; + Ok(()) + } + fn set_was_touching_water(&mut self, value: bool) { + self.player.fluids.was_touching_water = value; + } + fn fast_lava(&mut self) -> Result { + Ok(self.player.fluids.fast_lava) + } +} +impl FluidHeightWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + fn fluid(&mut self, p: [i32; 3]) -> Result { + Ok(self.fluid_at(BlockPos::new(p[0], p[1], p[2]))) + } + fn sturdy_down(&mut self, p: [i32; 3]) -> Result { + let state = MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2])); + Ok(self.resources.fluids.sturdy(state, Direction::Down)) + } +} +impl FluidFlowWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.fluid_at(p)) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(MotionWorld::block(self, p)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.resources + .fluids + .blocks_flow + .get(s.0 as usize) + .copied() + .unwrap_or(false) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.resources + .fluids + .ice + .get(s.0 as usize) + .copied() + .unwrap_or(false) + } + fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result { + Ok(self.resources.fluids.sturdy(s, d)) + } +} +/// `Entity.doWaterSplashEffect` for the player: the world random draws the +/// pitch and particle offsets. +impl WaterSplashWorld for MotionWorld<'_, '_, '_> { + type Error = Box; + type Entity = (); + /// `Player.getSwimHighSpeedSplashSound` when true, else `getSwimSplashSound`. + type Sound = bool; + fn this_entity(&self) {} + fn controlling_passenger(&mut self) -> Result> { + Ok(None) + } + fn velocity(&mut self, _: ()) -> Result { + Ok(self.player.velocity) + } + fn splash_sound(&mut self, high_speed: bool) -> Result { + Ok(high_speed) + } + fn random_float(&mut self) -> Result { + Ok(self.scene.random.next_float()) + } + fn random_double(&mut self) -> Result { + Ok(self.scene.random.next_double()) + } + fn play_sound(&mut self, high_speed: bool, volume: f32, pitch: f32) -> Result<()> { + self.player.events.push(MotionEvent::Splash { + high_speed, + volume, + pitch, + }); + Ok(()) + } + fn position(&self) -> Vec3 { + self.player.position + } + fn width(&self) -> f32 { + self.player.dimensions.width + } + fn particle(&mut self, kind: SplashParticle, position: Vec3, velocity: Vec3) -> Result<()> { + self.player.events.push(MotionEvent::SplashParticle { + bubble: matches!(kind, SplashParticle::Bubble), + position, + velocity, + }); + Ok(()) + } + fn splash_event(&mut self) -> Result<()> { + // The SPLASH game event: sculk listens to the player's moves itself. + self.player.events.push(MotionEvent::SplashEvent); + Ok(()) + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java index de6e0aed1..9f1ea2af3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java @@ -33,7 +33,7 @@ import static dev.horizonlab.parity.VanillaRegistryCollisionScanOracle.*; * full death services remain controlled boundaries. Clock operations set up the * two damage-clock fields, not the complete enclosing native tick methods. */ public final class VanillaSceneMotionOracle { - static Field position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace; + static Field blockPositionField,position,history,support,noBlocks,last,stuck,delay,trigger,attributeStorage,attributeDirty,attributeCached,impact,grace; static MethodHandle aiStep; static Method refreshAttributes; static EntityDataAccessor healthKey,absorptionKey; @@ -71,6 +71,7 @@ public final class VanillaSceneMotionOracle { static String vectorBits(Vec3 p){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(p.x),Double.doubleToLongBits(p.y),Double.doubleToLongBits(p.z));} static String soundName(SoundEvent s){ if(s==SoundEvents.PLAYER_SMALL_FALL)return "small";if(s==SoundEvents.PLAYER_BIG_FALL)return "big"; + if(s==SoundEvents.PLAYER_SPLASH)return "splash";if(s==SoundEvents.PLAYER_SPLASH_HIGH_SPEED)return "splash-high"; return VanillaBlockLandingOracle.sound(s); } static final class Sources extends DamageSources { @@ -107,6 +108,15 @@ public final class VanillaSceneMotionOracle { @Override public BlockGetter getChunkForCollisions(int x,int z){return chunks.get(key(x,z));} @Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);} @Override public FluidState getFluidState(BlockPos p){return getBlockState(p).getFluidState();} + // No dimension layers: FAST_LAVA keeps its default (the Overworld's slow lava). + static final net.minecraft.world.attribute.EnvironmentAttributeSystem ATTRIBUTES=net.minecraft.world.attribute.EnvironmentAttributeSystem.builder().build(); + @Override public net.minecraft.world.attribute.EnvironmentAttributeSystem environmentAttributes(){return ATTRIBUTES;} + // EntityFluidInteraction.hasFluidAndLoaded: resident chunks only. + @Override public net.minecraft.world.level.chunk.ChunkAccess getChunk(int x,int z,net.minecraft.world.level.chunk.status.ChunkStatus status,boolean load){return chunks.get(key(x,z));} + // Entity.doWaterSplashEffect's particles (a client level adds them). + @Override public void addParticle(net.minecraft.core.particles.ParticleOptions particle,double x,double y,double z,double xd,double yd,double zd){ + actor.events.add("splash-particle "+(particle==net.minecraft.core.particles.ParticleTypes.BUBBLE?"bubble":particle==net.minecraft.core.particles.ParticleTypes.SPLASH?"splash":"unknown")+" "+vectorBits(new Vec3(x,y,z))+" "+vectorBits(new Vec3(xd,yd,zd))); + } @Override public List getEntityCollisions(Entity e,AABB b){return List.of();} @Override public List getPushableEntities(Entity e,AABB b){return List.of();} @Override public List getEntities(Entity e,AABB b){return e!=actor&&b.intersects(actor.getBoundingBox())?List.of(actor):List.of();} @@ -162,7 +172,7 @@ public final class VanillaSceneMotionOracle { @Override public CombatTracker getCombatTracker(){return tracker;} @Override public net.minecraft.server.PlayerAdvancements getAdvancements(){events.add("hurt-criterion");return advancements;} @Override public void onSyncedDataUpdated(EntityDataAccessor key){if(key!=healthKey&&key!=absorptionKey)throw new AssertionError(key);events.add(String.format("updated %d %08x %s",key.id(),Float.floatToIntBits(getEntityData().get(key==healthKey?healthKey:absorptionKey)),getEntityData().isDirty()));} - @Override public void gameEvent(Holder event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else super.gameEvent(event);} + @Override public void gameEvent(Holder event){if(event==GameEvent.ENTITY_DAMAGE)events.add("entity-damage");else if(event==GameEvent.SPLASH)events.add("splash-event");else super.gameEvent(event);} @Override public void die(DamageSource source){dead=true;events.add("death-request");} @Override protected void playHurtSound(DamageSource source){events.add("hurt-sound");} @Override protected SoundEvent getDeathSound(){return SoundEvents.PLAYER_DEATH;} @@ -171,20 +181,18 @@ public final class VanillaSceneMotionOracle { @Override public AttributeMap getAttributes(){return attrs;} @Override protected boolean getSharedFlag(int bit){return (flags&(1< tag){return statisticsFlags!=null&&statFlag(2);} - @Override public boolean isInWater(){return statisticsFlags!=null&&statFlag(3);} + @Override public boolean isEyeInFluid(net.minecraft.tags.TagKey tag){return statisticsFlags!=null?statFlag(2):super.isEyeInFluid(tag);} + @Override public boolean isInWater(){return statisticsFlags!=null?statFlag(3):super.isInWater();} @Override public boolean onClimbable(){return statisticsFlags!=null?statFlag(4):super.onClimbable();} @Override public boolean onGround(){return statisticsFlags!=null?statFlag(5):super.onGround();} @Override public boolean isSprinting(){return statisticsFlags!=null?statFlag(6):super.isSprinting();} @Override public boolean isCrouching(){return statisticsFlags!=null?statFlag(7):super.isCrouching();} - @Override public boolean isInLava(){return false;} - @Override public boolean isInLiquid(){return false;} @Override public boolean isFallFlying(){return statisticsFlags!=null&&statFlag(8);} @Override public boolean isAutoSpinAttack(){return false;} @Override public boolean isSpectator(){return false;} @@ -196,7 +204,6 @@ public final class VanillaSceneMotionOracle { @Override public MoveSimulationType getMoveSimulationType(){return MoveSimulationType.SERVER_AND_CLIENT;} @Override public boolean isClientAuthoritative(){return false;} @Override public void recordMovement(MoverType mover,Vec3 movement){} - @Override protected boolean updateFluidInteraction(){return false;} @Override public void playSound(SoundEvent sound,float volume,float pitch){events.add(String.format("sound %s entity %08x %08x",soundName(sound),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));} @Override protected void playBlockFallSound(){events.add("block-fall-sound");} @Override public void awardStat(net.minecraft.stats.Stat stat,int value){ @@ -213,7 +220,6 @@ public final class VanillaSceneMotionOracle { @Override protected void playStepSound(BlockPos p,BlockState state){} @Override public void gameEvent(Holder event,Entity source){} @Override public LivingEntity getControllingPassenger(){return null;} - @Override public double getFluidHeight(net.minecraft.tags.TagKey tag){return 0;} @Override public double getFluidJumpThreshold(){return .4;} // Block-inside effects and frozen ticks run only in "snow_tick" operations. boolean effects;int frozen;Vec3 tickStart; @@ -243,7 +249,12 @@ public final class VanillaSceneMotionOracle { } } void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;} + // Entity.baseTick's fluid phase: wasEyeInWater, the real + // updateFluidInteraction, lava's fall halving and the first tick's end. + void fluidTick(){wasEyeInWater=isEyeInFluid(net.minecraft.tags.FluidTags.WATER);updateFluidInteraction();if(isInLava())fallDistance*=0.5;firstTick=false;} + String fluidState(){return wasTouchingWater+" "+wasEyeInWater+" "+isEyeInFluid(net.minecraft.tags.FluidTags.WATER)+" "+firstTick+String.format(" %016x %016x",Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.WATER)),Double.doubleToLongBits(getFluidHeight(net.minecraft.tags.FluidTags.LAVA)));} void playerMovementTick(Vec3 input,boolean jumping){ + fluidTick(); preparedInput=true;xxa=(float)input.x;yya=0;zza=(float)input.z;setJumping(jumping); try{aiStep();}finally{preparedInput=false;} } @@ -271,7 +282,7 @@ public final class VanillaSceneMotionOracle { out.printf("%s %s %s %s %s %s %s %016x %s %s %s %08x %d %08x %d %d %s | %s%n",p.horizontalCollision,p.verticalCollision,p.verticalCollisionBelow,p.minorHorizontalCollision, p.onGround(),noBlocks.getBoolean(p),pos(support.get(p)),Double.doubleToLongBits(p.fallDistance),pos(last.get(p)),p.needsSync,p.syncPosition,Float.floatToIntBits(storedSpeed.getFloat(p)),delay.getInt(p),Float.floatToIntBits(p.yHeadRot),trigger.getInt(p),grace.getInt(p),impact.get(p)==null?"none":vectorBits((Vec3)impact.get(p)),String.join(";",attributes)); out.println("events "+String.join(" | ",p.events));p.events.clear(); - out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p))); + out.println("block "+Block.getId(p.level().getBlockState(new BlockPos(25,3,25)))+" frozen "+p.frozen+" "+p.isInPowderSnow+" "+p.wasInPowderSnow+" "+vectorBits((Vec3)stuck.get(p))+" fluid "+p.fluidState()); var pp=p.portalProcess; out.println("portal "+p.getPortalCooldown()+" "+(pp==null?"none":pp.getEntryPosition().getX()+","+pp.getEntryPosition().getY()+","+pp.getEntryPosition().getZ()+" "+pp.getPortalTime()+" "+pp.isInsidePortalThisTick())+" "+(p.travel==null?"-":p.travel));p.travel=null; out.printf("health %08x %08x %08x %d %d %08x %d %d %s %d %s %s %s %s %s %d%n", @@ -285,8 +296,12 @@ public final class VanillaSceneMotionOracle { @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception{ net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(Path.of(args[2]).resolve("block-tags.json"))).getAsJsonObject()); + // The vanilla data pack's #water and #lava fluid tags. + net.minecraft.core.registries.BuiltInRegistries.FLUID.prepareTagReload(new net.minecraft.tags.TagLoader.LoadResult<>(net.minecraft.core.registries.Registries.FLUID,Map.of( + net.minecraft.tags.FluidTags.WATER,List.>of(net.minecraft.world.level.material.Fluids.FLOWING_WATER.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.WATER.builtInRegistryHolder()), + net.minecraft.tags.FluidTags.LAVA,List.>of(net.minecraft.world.level.material.Fluids.FLOWING_LAVA.builtInRegistryHolder(),net.minecraft.world.level.material.Fluids.LAVA.builtInRegistryHolder())))).apply(); var u=Class.forName("sun.misc.Unsafe");var f=u.getDeclaredField("theUnsafe");f.setAccessible(true);var unsafe=f.get(null);var allocate=u.getMethod("allocateInstance",Class.class); - position=field(Entity.class,"position");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier"); + position=field(Entity.class,"position");blockPositionField=field(Entity.class,"blockPosition");history=field(Entity.class,"movementThisTick");support=field(Entity.class,"mainSupportingBlockPos");noBlocks=field(Entity.class,"onGroundNoBlocks");last=field(LivingEntity.class,"lastClimbablePos");stuck=field(Entity.class,"stuckSpeedMultiplier"); var abilities=field(Player.class,"abilities"); healthKey=(EntityDataAccessor)field(LivingEntity.class,"DATA_HEALTH_ID").get(null);absorptionKey=(EntityDataAccessor)field(Player.class,"DATA_PLAYER_ABSORPTION_ID").get(null); healthDead=field(LivingEntity.class,"dead");cooldown=field(LivingEntity.class,"damageCooldownTime");lastHurt=field(LivingEntity.class,"lastHurt");noAction=field(LivingEntity.class,"noActionTime");lastDamage=field(LivingEntity.class,"lastDamageSource");lastStamp=field(LivingEntity.class,"lastDamageStamp");foodExhaustion=field(FoodData.class,"exhaustionLevel");foodTimer=field(FoodData.class,"tickTimer"); @@ -320,6 +335,8 @@ public final class VanillaSceneMotionOracle { p.attrs=new TrackedAttributes(VanillaEntityAttributeOracle.supplier(EntityTypes.PLAYER));write(field(LivingEntity.class,"attributes"),p,p.attrs); write(field(Entity.class,"finalMovementsThisTick"),p,new ArrayList<>());write(field(Entity.class,"visitedBlocks"),p,new it.unimi.dsi.fastutil.longs.LongOpenHashSet()); write(field(Entity.class,"insideEffectCollector"),p,new net.minecraft.world.entity.InsideBlockEffectApplier.StepBasedCollector()); + write(field(Entity.class,"fluidInteraction"),p,new net.minecraft.world.entity.EntityFluidInteraction(Set.of(net.minecraft.tags.FluidTags.WATER,net.minecraft.tags.FluidTags.LAVA))); + write(field(Entity.class,"random"),p,level.rng);field(Entity.class,"firstTick").setBoolean(p,true); write(history,p,new ArrayDeque<>());write(support,p,Optional.empty());write(last,p,Optional.empty());write(stuck,p,Vec3.ZERO);write(abilities,p,new Abilities()); write(field(ServerPlayer.class,"shoulderEntityLeft"),p,new net.minecraft.nbt.CompoundTag());write(field(ServerPlayer.class,"shoulderEntityRight"),p,new net.minecraft.nbt.CompoundTag()); p.connection=(Connection)allocate.invoke(unsafe,Connection.class); @@ -366,6 +383,7 @@ public final class VanillaSceneMotionOracle { case "impulse"->p.setIgnoreFallDamageFromCurrentImpulse(op.get("ignore").getAsBoolean(),op.get("value").isJsonNull()?null:VanillaSceneCollisionOracle.vector(op.get("value"))); case "block"->{var v=op.getAsJsonArray("position");var pos=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt());var state=VanillaSceneCollisionOracle.state(op.get("name").getAsString());if(op.has("properties"))for(var property:op.getAsJsonObject("properties").entrySet())state=VanillaSceneCollisionOracle.property(state,state.getBlock().getStateDefinition().getProperty(property.getKey()),property.getValue().getAsString());level.chunks.get(key(pos.getX()>>4,pos.getZ()>>4)).write(pos,Block.getId(state));} case "landing"->{var v=op.getAsJsonArray("position");p.land(number(op.get("value")),op.get("ground").getAsBoolean(),new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()));} + case "fluid_tick"->p.fluidTick(); case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value"))); case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value"))); case "player_tick"->p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean()); diff --git a/tools/test_native_scene_motion.py b/tools/test_native_scene_motion.py index 8430b29a7..b1cb9bbeb 100644 --- a/tools/test_native_scene_motion.py +++ b/tools/test_native_scene_motion.py @@ -227,12 +227,129 @@ def portal_corpus(): ops += restore() yield dict(position=vec((25.5,4,25.5)),ops=ops) +def water_corpus(): + """Falls into water, waterlogged blocks, bubble columns, kelp/seagrass and + lava (#180). "fluid_tick" runs Entity.baseTick's fluid phase alone + (wasEyeInWater, the real updateFluidInteraction with its fall reset, + splash and currents, lava's fall halving, firstTick); scripted falling + velocities go through the real Entity.move (the FALLDAMAGE_RESETTING ray + with ClipContext.Fluid.WATER, then LivingEntity.checkFallDamage refreshing + the fluids before the fall is applied). No fluid travel: the player never + travels while touching a fluid here.""" + def place(name,positions,properties=None): + return [op('block',name='minecraft:'+name,position=list(p),**({'properties':properties} if properties else {})) for p in positions] + def restore(positions): + return [op('block',name='minecraft:air',position=list(p)) for p in positions] + def fall(start_y,steps,v=0.,settle=4): + # Vanilla's falling speeds (gravity 0.08, drag 0.98), applied by Entity.move. + ops=[] + for _ in range(steps): + ops += [op('fluid_tick'),op('velocity',vec((0,v,0))),op('move',vec((0,v,0)))] + v=(v-.08)*.98 + return ops+[op('fluid_tick') for _ in range(settle)] + def pool(y0,depth,x=range(23,28),z=range(23,28)): + return [(a,y,b) for a in x for y in range(y0,y0+depth) for b in z] + rng=random.Random(0x57415452) + starts=[(25.5,5.2),(25.7,6),(25.5,9),(24.2,16),(25.5,16.3),(26.9,28)] + # Pools of source, flowing and falling water, one to three deep (the + # #180 repro: a 1-deep pool 12 blocks below). + for depth in [1,2,3]: + for properties in [{'level':'0'}]+([{'level':str(l)} for l in (1,4,7,8,12)] if depth==1 else []): + for x,y in starts: + blocks=pool(4,depth) + ops=[op('seed',rng.randrange(1<<31))]+place('water',blocks,properties)+fall(y,45)+restore(blocks) + yield dict(position=vec((x,y,25.3)),ops=ops) + # The same falls with a preset fall distance and speed (teleported, then + # one move into the pool), and falls landing just beside the pool. + for preset,v in [(12,-.9),(3.5,-.5),(30,-3.2),(0,-.08)]: + for x in [25.5,22.9,22.7,27.6,28.31]: + blocks=pool(4,1) + ops=[op('seed',rng.randrange(1<<31))]+place('water',blocks)+[op('fall',bits(preset))]+fall(5.0-v,3,v)+restore(blocks) + yield dict(position=vec((x,5.0-v,25.5)),ops=ops) + # Waterlogged floors: the water's surface is under or above the feet. + for name,properties in [('oak_slab',{'type':'bottom'}),('oak_slab',{'type':'top'}),('oak_stairs',{'facing':'north'}), + ('oak_fence',{}),('oak_trapdoor',{'half':'bottom'}),('oak_trapdoor',{'half':'top','open':'true'}), + ('lantern',{}),('mangrove_roots',{}),('ladder',{'facing':'north'}),('copper_grate',{}),('iron_bars',{})]: + for logged in ['true','false']: + for x,y in [(25.5,9),(25.3,16)]: + blocks=pool(4,1,range(24,27),range(24,27)) + ops=place(name,blocks,dict(properties,waterlogged=logged))+fall(y,40)+restore(blocks) + yield dict(position=vec((x,y,25.5)),ops=ops) + # Bubble columns, kelp and seagrass are water too. + for name,properties in [('bubble_column',{'drag':'true'}),('bubble_column',{'drag':'false'}),('kelp',{'age':'3'}), + ('kelp_plant',{}),('seagrass',{}),('tall_seagrass',{'half':'lower'})]: + for depth in [1,3]: + blocks=pool(4,depth,range(24,27),range(24,27)) + ops=place(name,blocks,properties)+fall(16,45)+restore(blocks) + yield dict(position=vec((25.5,16,25.5)),ops=ops) + # Lava resets nothing but halves the fall every base tick after the first. + for depth in [1,2]: + for properties in [{'level':'0'},{'level':'3'}]: + for x,y in [(25.5,4.5),(25.5,9),(25.5,16)]: + blocks=pool(4,depth) + ops=[op('fall',bits(6))]+place('lava',blocks,properties)+fall(y,45)+restore(blocks) + yield dict(position=vec((x,y,25.5)),ops=ops) + # Water over lava, and a falling player passing a lava layer into water. + lava=pool(6,1,range(24,27),range(24,27));water=pool(4,2,range(24,27),range(24,27)) + ops=place('water',water)+place('lava',lava)+fall(14,40)+restore(lava+water) + yield dict(position=vec((25.5,14,25.5)),ops=ops) + # Fast falls through a hanging water layer: the fall-reset ray finds the + # water only at 1 block per tick or more (and the shape cached by the + # first query of each state). + for properties in [{'level':'0'},{'level':'2'},{'level':'7'},{'level':'8'}]: + for v in [-.99,-1.0,-1.6,-3.5,-9]: + for y in [20,21.3,23.95]: + layer=pool(12,1) + ops=[op('fall',bits(20))]+place('water',layer,properties) + ops += [op('velocity',vec((0,v,0))),op('move',vec((0,v,0))) ]*4+[op('fluid_tick')]+fall(8,12)+restore(layer) + yield dict(position=vec((25.5,y,25.5)),ops=ops) + # Flying players are not pushed but still lose their fall in water. + for flying in [False,True]: + for x,z in [(25.5,25.5),(24.1,26.8)]: + flow=[(25,4,25)] + ring=[(a,4,b) for a in range(23,28) for b in range(23,28) if (a,b)!=(25,25)] + ops=[op('flying',flying,may_fly=True)]+place('water',flow)+[op('block',name='minecraft:water',position=[a,4,b],properties={'level':str(min(7,max(abs(a-25),abs(b-25))))}) for a,_,b in ring] + ops += [op('fall',bits(9))]+[op('fluid_tick') for _ in range(12)]+[op('velocity',vec((0,0,0)))]+[op('fluid_tick') for _ in range(6)] + ops += restore(flow+ring) + yield dict(position=vec((x,4,z)),ops=ops) + # Currents of flowing water, small and large speeds, every cell position. + for i in range(24): + cells=[(a,4,b) for a in range(22,29) for b in range(22,29)] + levels={c:rng.choice(['0','1','2','3','5','7','8','9']) for c in cells} + ops=[op('block',name='minecraft:water',position=list(c),properties={'level':levels[c]}) for c in cells] + ops += [op('velocity',vec((rng.choice([0,.002,-.1]),0,rng.choice([0,.0029,.2]))))] + ops += [op('fluid_tick') for _ in range(8)] + ops += restore(cells) + yield dict(position=vec((rng.uniform(22.4,28.6),4,rng.uniform(22.4,28.6))),ops=ops) + # Eyes under water, splashes of every size: scale changes the eye height + # and the width that counts the particles. + for scale in [.25,.5,1,2.5]: + for start,v in [(10,-.2),(10,-1.2),(7,-.05),(4.3,0)]: + blocks=pool(4,3) + ops=[op('seed',rng.randrange(1<<31)),op('attribute',bits(scale),name='minecraft:scale'),op('refresh_dimensions')] + ops += place('water',blocks)+fall(start,30,v) + # Out of the water and back in: a second splash. + ops += [op('move',vec((0,6,0))),op('fluid_tick'),op('velocity',vec((0,-.6,0))),op('move',vec((0,-.6,0))),op('fluid_tick'),op('fluid_tick')] + ops += restore(blocks) + yield dict(position=vec((25.5,start,25.5)),ops=ops) + # LivingEntity.checkFallDamage on its own, landing with or without having + # touched the water this tick, and on the first tick (no splash). + for wet in [False,True]: + for ticked in [0,1,2]: + for dy in [-.5,-1.5,0]: + blocks=pool(4,1) + ops=([op('block',name='minecraft:water',position=list(b)) for b in blocks] if wet else [])+[op('fluid_tick') for _ in range(ticked)] + ops += [op('fall',bits(8)),op('landing',bits(dy),ground=True,position=[25,3,25]),op('fall',bits(8)),op('landing',bits(dy),ground=False,position=[25,3,25])] + ops += restore(blocks) + yield dict(position=vec((25.5,4,25.5)),ops=ops) + def corpus(): yield from attribute_corpus(False) yield from portal_corpus() yield from pose_corpus(False) yield from powder_snow_corpus() yield from stuck_corpus() + yield from water_corpus() def food(level=20,saturation=5,exhaustion=0,timer=0): return op('food',food=level,saturation=single(saturation),exhaustion=single(exhaustion),timer=timer) # Actual ServerPlayer.checkMovementStatistics with all query contexts. These @@ -560,7 +677,7 @@ def main(): 'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0],'fixtures':len(fixtures), 'operations':operations,'sources_sha256':tested,'resources':resource_hash,'input_sha256':input_hash, 'references':references, - 'scope':('Client sprint scene executes the real LocalPlayer.aiStep prefix through sprint decisions, stopping at the riding/parent movement boundary, followed by real LocalPlayer.modifyInput and the native server actor simulation. Sprint setters dispatch to that server actor, sharing its actual FoodData and collision conditions. Compares local sprint timer/input history and actual attribute changes, movement, distance exhaustion and hunger. Actual local crouch selection precedes new keyboard input; slowdown, sprint eligibility and pose-dependent dimensions share resident state. No effects, equipment, vehicles or fluid physics. Full client/server tick and networking remain unfinished. ' if args.sprint_input else '')+'Stored PlayerMotion binds resident client chunks and registered attributes/coefficients to air travel, jumping, Entity.move, step resolution, ground/support updates, restitution and speed factors. Repeated native Player.travel/jump/move and actual Player.aiStep / direct LivingEntity.aiStep compare position, velocity, bounds, collision/ground flags, support, climb state, fall-reset field, both sync flags, speed, head yaw, jump trigger and jump delay by exact bits. Prepared-local-input Player.aiStep paths verify the stored speed refresh after movement, with empty inventory and no nearby entities. Travel uses the actual Player.getSpeed movement-attribute query, independently of that stored base-living speed field; both getter and setter execute native bodies. Dry aiStep includes small-velocity cleanup, input damping, held/released jump timing and server frost-modifier removal. Snapshots also compare all allocated attribute instances, base/cache/dirty state, modifier values/operations/permanence and pending update/sync membership. Per-reference JVM holder/instance hashes are replayed so pending callback order and resulting ordered events also match. Dry resident scene with standing, crouching and crawling bounds, cached eye height, native pose-fit selection and ledge backoff; zero frozen ticks, empty equipment, no interpolation, fluids, vehicles, effects or other entities. The oracle controls pose storage and invokes actual native refreshDimensions on changes; full synchronized pose schema and network notifications remain separate. Actual pending attribute refresh runs after player movement and before pose selection in simulation operations, clamping health/absorption and rebuilding scale-dependent dimensions. Native ServerPlayer waypoint-receive and inherited transmit callbacks are compared as ordered requests; the waypoint manager and its network delivery remain controlled consumers. Direct refresh operations and the full enclosing tick remain separate boundaries. Actual LivingEntity.checkFallDamage, registered Block.fallOn/bounceOn and Player/LivingEntity.causeFallDamage are composed, including float-narrowed fall-distance accumulation, reset, last-climb clearing, safe-fall and damage-multiplier attributes, impulse exemptions and ordered landing particle/sound/statistic/hit-ground/damage requests. Farmland pushes the stored player and replaces actual chunk state; repeated turtle-egg changes preserve hatch. Block state at the landing fixture is compared after every operation. World RNG is a seeded native legacy stream. Actual ServerPlayer/Player/LivingEntity hurt dispatch now updates native synchronized health and player absorption, modified armor/toughness reduction, exhaustion, damage cooldown/last-source state and velocity synchronization. Native health storage and dirty flags are compared after every operation. Damage sources use actual decoded/tagged pinned damage registries. ServerPlayer jump statistics and exhaustion are included; dead-or-dying state disables movement input and jumping. Empty equipment/hands/effects, configurable difficulty and natural regeneration, damage gamerules enabled, loaded client and no spawn-extra fall particles define this scene domain. Ordered health/statistic/combat-record/broadcast/sound/criterion/death requests are compared; criterion argument payloads retain the separate combat gate. Actual health changes are applied, but audiovisual playback, persistent statistics, combat tracker internals, full death/drop/respawn services, block neighbor/drop/block-entity callbacks, movement emission, block-inside and networking remain controlled consumers. Actual FoodData.tick and ServerPlayer.tickRegeneration now share the same stored health, attributes, exhaustion and registered starvation damage. Snapshots compare food level, saturation, exhaustion, timer and tick count. Cases cover all four difficulties, regeneration rule changes, absorption during starvation, Peaceful recovery, timer overflow and nonfinite food values. Simulation operations compose clock setup, actual player movement and actual food ticking in their native order, including fall damage followed by regeneration in the same tick. Explicit clock operations establish cooldown/hurt-time/game-time/tick-count state; full enclosing native tick/doTick methods are not invoked by those setup operations. Input preparation has its own client comparison. ServerPlayer.checkMovementStatistics executes on accepted resident deltas after movement and before food ticking. Additional direct method fixtures cover all 512 overlapping passenger/swim/eye-water/water/climb/ground/sprint/crouch/glide flag combinations, invulnerable abilities, centimeter rounding, overflow, signed zero and nonfinite deltas. Those query contexts apply only to the statistics method; fluid/vehicle/glide physics remain unbound. ServerGamePacketListener packet acceptance/rejection and scheduling are not executed. Powder snow operations (snow_tick) run the clock, the powder snow flags and old position of baseTick, then actual aiStep with the real Entity.applyEffectsFromBlocks (movement-path block sweep, StepBasedCollector, PowderSnowBlock.entityInside: stuck multiplier, ALTERNATIVE snowflake particles from the level random, FREEZE/EXTINGUISH, ServerPlayer.onInsideBlock criteria; NetherPortalBlock.entityInside (setAsInsidePortal, with portal_tick running the cooldown and PortalProcessor of Entity.handlePortal without a destination), WebBlock.entityInside with and without Weaving and SweetBerryBushBlock.entityInside at every age through Player.makeStuckInBlock, with sweet_berry_bush damage on the known movement) and the server freezing phase (thaw, frost modifier, freeze damage every 40 ticks); leather boots are a component-less stack and #freeze_immune_wearables is emulated by them. Outside snow_tick block-inside effects stay disabled on both sides. No full Player.tick, consumable item-use lifecycle, local input lifecycle, nonempty inventory/equipment ticks, full freezing, complete death lifecycle or full gameplay parity claim.'}) + 'scope':('Client sprint scene executes the real LocalPlayer.aiStep prefix through sprint decisions, stopping at the riding/parent movement boundary, followed by real LocalPlayer.modifyInput and the native server actor simulation. Sprint setters dispatch to that server actor, sharing its actual FoodData and collision conditions. Compares local sprint timer/input history and actual attribute changes, movement, distance exhaustion and hunger. Actual local crouch selection precedes new keyboard input; slowdown, sprint eligibility and pose-dependent dimensions share resident state. No effects, equipment, vehicles or fluid physics. Full client/server tick and networking remain unfinished. ' if args.sprint_input else '')+'Stored PlayerMotion binds resident client chunks and registered attributes/coefficients to air travel, jumping, Entity.move, step resolution, ground/support updates, restitution and speed factors. Repeated native Player.travel/jump/move and actual Player.aiStep / direct LivingEntity.aiStep compare position, velocity, bounds, collision/ground flags, support, climb state, fall-reset field, both sync flags, speed, head yaw, jump trigger and jump delay by exact bits. Prepared-local-input Player.aiStep paths verify the stored speed refresh after movement, with empty inventory and no nearby entities. Travel uses the actual Player.getSpeed movement-attribute query, independently of that stored base-living speed field; both getter and setter execute native bodies. Dry aiStep includes small-velocity cleanup, input damping, held/released jump timing and server frost-modifier removal. Snapshots also compare all allocated attribute instances, base/cache/dirty state, modifier values/operations/permanence and pending update/sync membership. Per-reference JVM holder/instance hashes are replayed so pending callback order and resulting ordered events also match. Dry resident scene with standing, crouching and crawling bounds, cached eye height, native pose-fit selection and ledge backoff; zero frozen ticks, empty equipment, no interpolation, fluid travel, vehicles, effects or other entities. The oracle controls pose storage and invokes actual native refreshDimensions on changes; full synchronized pose schema and network notifications remain separate. Actual pending attribute refresh runs after player movement and before pose selection in simulation operations, clamping health/absorption and rebuilding scale-dependent dimensions. Native ServerPlayer waypoint-receive and inherited transmit callbacks are compared as ordered requests; the waypoint manager and its network delivery remain controlled consumers. Direct refresh operations and the full enclosing tick remain separate boundaries. Actual LivingEntity.checkFallDamage, registered Block.fallOn/bounceOn and Player/LivingEntity.causeFallDamage are composed, including float-narrowed fall-distance accumulation, reset, last-climb clearing, safe-fall and damage-multiplier attributes, impulse exemptions and ordered landing particle/sound/statistic/hit-ground/damage requests. Farmland pushes the stored player and replaces actual chunk state; repeated turtle-egg changes preserve hatch. Block state at the landing fixture is compared after every operation. World RNG is a seeded native legacy stream. Actual ServerPlayer/Player/LivingEntity hurt dispatch now updates native synchronized health and player absorption, modified armor/toughness reduction, exhaustion, damage cooldown/last-source state and velocity synchronization. Native health storage and dirty flags are compared after every operation. Damage sources use actual decoded/tagged pinned damage registries. ServerPlayer jump statistics and exhaustion are included; dead-or-dying state disables movement input and jumping. Empty equipment/hands/effects, configurable difficulty and natural regeneration, damage gamerules enabled, loaded client and no spawn-extra fall particles define this scene domain. Ordered health/statistic/combat-record/broadcast/sound/criterion/death requests are compared; criterion argument payloads retain the separate combat gate. Actual health changes are applied, but audiovisual playback, persistent statistics, combat tracker internals, full death/drop/respawn services, block neighbor/drop/block-entity callbacks, movement emission, block-inside and networking remain controlled consumers. Actual FoodData.tick and ServerPlayer.tickRegeneration now share the same stored health, attributes, exhaustion and registered starvation damage. Snapshots compare food level, saturation, exhaustion, timer and tick count. Cases cover all four difficulties, regeneration rule changes, absorption during starvation, Peaceful recovery, timer overflow and nonfinite food values. Simulation operations compose clock setup, actual player movement and actual food ticking in their native order, including fall damage followed by regeneration in the same tick. Explicit clock operations establish cooldown/hurt-time/game-time/tick-count state; full enclosing native tick/doTick methods are not invoked by those setup operations. Input preparation has its own client comparison. ServerPlayer.checkMovementStatistics executes on accepted resident deltas after movement and before food ticking. Additional direct method fixtures cover all 512 overlapping passenger/swim/eye-water/water/climb/ground/sprint/crouch/glide flag combinations, invulnerable abilities, centimeter rounding, overflow, signed zero and nonfinite deltas. Those query contexts apply only to the statistics method; fluid/vehicle/glide physics remain unbound. ServerGamePacketListener packet acceptance/rejection and scheduling are not executed. Powder snow operations (snow_tick) run the clock, the powder snow flags and old position of baseTick, then actual aiStep with the real Entity.applyEffectsFromBlocks (movement-path block sweep, StepBasedCollector, PowderSnowBlock.entityInside: stuck multiplier, ALTERNATIVE snowflake particles from the level random, FREEZE/EXTINGUISH, ServerPlayer.onInsideBlock criteria; NetherPortalBlock.entityInside (setAsInsidePortal, with portal_tick running the cooldown and PortalProcessor of Entity.handlePortal without a destination), WebBlock.entityInside with and without Weaving and SweetBerryBushBlock.entityInside at every age through Player.makeStuckInBlock, with sweet_berry_bush damage on the known movement) and the server freezing phase (thaw, frost modifier, freeze damage every 40 ticks); leather boots are a component-less stack and #freeze_immune_wearables is emulated by them. Outside snow_tick block-inside effects stay disabled on both sides. Water operations (fluid_tick) run Entity.baseTick's fluid phase alone with the real updateFluidInteraction over the vanilla #water/#lava fluid tags (EntityFluidInteraction heights, eyes, currents with Player.isPushedByFluid, fall reset, Entity.doWaterSplashEffect sound/BUBBLE/SPLASH particles/SPLASH game event from the level random, firstTick) and lava's fall halving; every player tick runs that phase first. Scripted falls through the real Entity.move cover the FALLDAMAGE_RESETTING ray with ClipContext.Fluid.WATER (first-query fluid shape cache) and LivingEntity.checkFallDamage refreshing the fluids before applying the fall: source, flowing and falling water, waterlogged slabs/stairs/fences/trapdoors/lanterns/roots/ladders/grates/bars, bubble columns, kelp, seagrass and lava. The player never travels while touching a fluid (no water travel/swimming here). No full Player.tick, consumable item-use lifecycle, local input lifecycle, nonempty inventory/equipment ticks, full freezing, complete death lifecycle or full gameplay parity claim.'}) print(f'Scoped scene motion parity passed: {report}',flush=True) if __name__=='__main__':main() From 03309dee95675c6845657c944c0c628f54128744 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 22:13:34 +0200 Subject: [PATCH 08/23] Format the player fluid binding Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/motion/fluids.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index ef4746eaa..94e9404e9 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -43,7 +43,11 @@ impl FluidResources { .iter() .map(|s| assets.blocks_fluid_flow.contains(&*s.name)) .collect(), - ice: facts.states.iter().map(|s| s.has_class("IceBlock")).collect(), + ice: facts + .states + .iter() + .map(|s| s.has_class("IceBlock")) + .collect(), shapes: Mutex::new(FluidShapeCache::default()), }) } From e7e35fa6e1689db1c89c871c24f176583c3e8dd8 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:53:10 -0400 Subject: [PATCH 09/23] Correct resident fluid phase and breathing decisions --- crates/horizon-client/src/effects.rs | 2 + crates/horizon-client/src/motion.rs | 275 ++++++++++++++++-- .../horizon-client/src/motion/environment.rs | 29 +- crates/horizon-client/src/motion/fluids.rs | 19 +- 4 files changed, 302 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index dbde71b6b..71a9377ed 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -287,6 +287,7 @@ impl PlayerEffects { weaving: self.get("weaving").is_some(), water_breathing: self.get("water_breathing").is_some() || self.get("conduit_power").is_some(), + breath_of_the_nautilus: self.get("breath_of_the_nautilus").is_some(), protection: Vec::new(), } } @@ -384,6 +385,7 @@ pub struct StatusFlags { /// Weaving: cobwebs hold half as much (`WebBlock.entityInside`). pub weaving: bool, pub water_breathing: bool, + pub breath_of_the_nautilus: bool, /// Armor enchantment protection per damage type id (`EnchantmentHelper.getDamageProtection`). pub protection: Vec<(String, f32)>, } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0c5df91b2..1be338e2c 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -526,7 +526,7 @@ impl PlayerMotion { minor_horizontal_collision: self.collision.minor, moving_slowly: self.moving_slowly(), in_water: self.fluids.was_touching_water, - under_water: self.is_eye_in_fluid(WATER), + under_water: self.is_under_water(), swimming: self.swimming, ..Default::default() }; @@ -744,18 +744,13 @@ impl MotionWorld<'_, '_, '_> { /// Resident simulation phases in native order. Enclosing entity/world tick /// services are still incomplete; this composes clocks, movement and hunger. pub fn simulation_tick(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> { + self.player.health.advance_clock(); self.fluid_base_tick()?; self.simulation_tick_with_fluids(direction, jumping) } fn simulation_tick_with_fluids(&mut self, direction: [f32; 2], jumping: bool) -> Result<()> { - self.player.health.advance_clock(); self.tick_environment_damage()?; let previous = self.player.position; - self.player.swimming = self.player.sprinting - && self.player.fluids.was_touching_water - && (self.player.swimming || self.player.is_eye_in_fluid(WATER)) - && !self.player.flying - && !self.player.spectator; self.player_movement_tick_with_fluids(direction, jumping)?; self.apply_fire_contact()?; self.player.refresh_attributes()?; @@ -776,6 +771,7 @@ impl MotionWorld<'_, '_, '_> { self.player.auto_jump_time -= 1; keys.jump = true; } + self.player.health.advance_clock(); self.fluid_base_tick()?; self.player.sprint_input_tick(keys)?; self.player.shift_key_down = keys.shift; @@ -832,17 +828,13 @@ impl MotionWorld<'_, '_, '_> { self.player.velocity.y -= f64::from(0.04f32); } if self.player.jumping { - let height = self - .player - .fluid_height(if self.player.fluids.was_touching_water { - WATER - } else { - LAVA - }); - if !self.player.flying - && (self.player.fluids.was_touching_water || self.player.is_in_lava()) - && (!self.player.ground.on_ground || height > 0.4) - { + let in_lava = self.player.is_in_lava(); + let height = self.player.fluid_height(if in_lava { LAVA } else { WATER }); + let water_jump = self.player.fluids.was_touching_water + && height > 0.0 + && (!self.player.ground.on_ground || height > 0.4); + let lava_jump = in_lava && (!self.player.ground.on_ground || height > 0.4); + if !self.player.flying && (water_jump || lava_jump) { self.player.velocity.y += f64::from(0.04f32); } else if self.player.ground.on_ground && self.player.no_jump_delay == 0 { self.jump_from_ground()?; @@ -2150,6 +2142,17 @@ mod tests { ..Default::default() }) .unwrap(); + assert!(w.player.sprinting); + assert!( + !w.player.swimming, + "sprint input follows the swimming phase" + ); + w.controlled_simulation_tick(crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }) + .unwrap(); assert!(w.player.swimming); assert_eq!(w.player.pose, crate::pose::Pose::Swimming); // Direct fire contact ignites; resistance prevents damage but does not hide flames. @@ -2276,6 +2279,242 @@ mod tests { ); } + #[test] + fn resident_swimming_uses_previous_eyes_and_requires_water_at_the_feet() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, 3).unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + for y in 4..=6 { + scene.set(20, y, 20, water).unwrap(); + } + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.player.local_crouching = true; + let sprint = crate::sprint::Keys { + forward: true, + sprint: true, + ..Default::default() + }; + w.fluid_base_tick().unwrap(); + assert!(w.player.is_eye_in_fluid(WATER)); + assert!(!w.player.is_under_water()); + w.player.sprint_input_tick(sprint).unwrap(); + assert!( + !w.player.sprinting, + "new eye immersion cannot bypass crouching" + ); + w.fluid_base_tick().unwrap(); + assert!(w.player.is_under_water()); + w.player.sprint_input_tick(sprint).unwrap(); + assert!(w.player.sprinting); + assert!(!w.player.swimming, "sprint starts after the base tick"); + w.fluid_base_tick().unwrap(); + assert!(w.player.swimming); + let air = assets.registry.default_state("minecraft:air").unwrap(); + w.scene.set(20, 4, 20, air).unwrap(); + w.player.swimming = false; + w.fluid_base_tick().unwrap(); + assert!(w.player.is_under_water()); + assert!( + !w.player.swimming, + "starting a swim requires water in the feet cell" + ); + w.player.swimming = true; + w.fluid_base_tick().unwrap(); + assert!( + w.player.swimming, + "an existing swim only requires touching water" + ); + w.player.flying = true; + w.fluid_base_tick().unwrap(); + assert!(!w.player.swimming); + w.player.flying = false; + w.player.spectator = true; + w.scene.set(20, 4, 20, water).unwrap(); + w.fluid_base_tick().unwrap(); + assert!( + w.player.swimming, + "spectator flight is applied later in aiStep" + ); + } + + #[test] + fn resident_fire_precedes_first_tick_lava_and_water_extinguishing() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + for name in ["minecraft:lava", "minecraft:water"] { + let mut scene = World::test_scene(&assets, 3).unwrap(); + let fluid = assets.registry.default_state(name).unwrap(); + scene.set(20, 4, 20, fluid).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + player.fire_ticks = 160; + player.fall_distance = 8.0; + let mut w = MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.fluid_base_tick().unwrap(); + assert_eq!( + w.player.health.health(), + 19.0, + "base on-fire damage: {name}" + ); + if name == "minecraft:lava" { + assert_eq!(w.player.fire_ticks, 159); + assert_eq!(w.player.fall_distance, 8.0, "first tick excludes lava"); + w.fluid_base_tick().unwrap(); + assert_eq!( + w.player.fall_distance, 4.0, + "later ticks halve exactly once" + ); + } else { + assert_eq!(w.player.fire_ticks, 0, "water extinguishes after the hurt"); + assert_eq!(w.player.fall_distance, 0.0); + w.player.fire_ticks = -7; + w.fluid_base_tick().unwrap(); + assert_eq!( + w.player.fire_ticks, -7, + "clearing fire retains negative delay" + ); + } + } + } + + #[test] + fn resident_bubble_columns_and_nautilus_preserve_their_air_rules() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, 3).unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + scene.set(20, 4, 20, water).unwrap(); + scene.set(20, 5, 20, water).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + for (extra_effect, expected_air) in [ + (None, -19), + (Some("water_breathing"), -15), + (Some("conduit_power"), -15), + ] { + let mut effects = crate::effects::PlayerEffects::default(); + effects.add(crate::effects::EffectInstance::new( + "breath_of_the_nautilus", + 200, + 0, + )); + if let Some(id) = extra_effect { + effects.add(crate::effects::EffectInstance::new(id, 200, 0)); + } + w.player.status = effects.status(); + assert!(w.player.status.breath_of_the_nautilus); + w.player.air = -19; + w.fluid_base_tick().unwrap(); + w.tick_environment_damage().unwrap(); + assert_eq!(w.player.air, expected_air); + assert_eq!(w.player.health.health(), 20.0); + } + w.player.status.water_breathing = false; + for (name, nautilus) in [ + ("minecraft:bubble_column", false), + ("minecraft:bubble_column", true), + ("minecraft:air", true), + ] { + w.scene + .set(20, 5, 20, assets.registry.default_state(name).unwrap()) + .unwrap(); + w.player.status.breath_of_the_nautilus = nautilus; + w.player.air = -19; + w.fluid_base_tick().unwrap(); + w.tick_environment_damage().unwrap(); + assert_eq!(w.player.air, -15, "{name}, nautilus={nautilus}"); + assert_eq!(w.player.health.health(), 20.0); + } + w.scene.set(20, 5, 20, water).unwrap(); + w.player.status.breath_of_the_nautilus = false; + w.player.air = -19; + w.fluid_base_tick().unwrap(); + w.tick_environment_damage().unwrap(); + assert_eq!(w.player.air, 0); + assert_eq!(w.player.health.health(), 18.0); + } + + #[test] + fn resident_mixed_fluids_use_lava_height_for_ground_jumps() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + for (water_level, lava_level, ground_jump) in [(0, 6, true), (6, 0, false)] { + let mut scene = World::test_scene(&assets, 3).unwrap(); + for (name, level, x) in [ + ("minecraft:water", water_level, 20), + ("minecraft:lava", lava_level, 21), + ] { + let mut state = assets + .registry + .state(assets.registry.default_state(name).unwrap()) + .unwrap() + .clone(); + state.properties.insert("level".into(), level.to_string()); + scene + .set(x, 4, 20, assets.registry.id(&state).unwrap()) + .unwrap(); + } + let mut player = PlayerMotion::new(&resources, Vec3::new(21.0, 4.0, 20.5)).unwrap(); + player.ground.on_ground = true; + let mut w = MotionWorld { + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.fluid_base_tick().unwrap(); + assert!(w.player.fluids.was_touching_water && w.player.is_in_lava()); + assert_eq!(w.player.fluid_height(LAVA) <= 0.4, ground_jump); + assert_eq!(w.player.fluid_height(WATER) > 0.4, ground_jump); + w.dry_tick(TickInput::PreparedLocal { + direction: [0.0; 2], + jumping: true, + }) + .unwrap(); + assert_eq!(w.player.no_jump_delay == 10, ground_jump); + } + } + #[test] fn footsteps_follow_the_walked_distance_not_the_tick() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index 0783843af..7f1dca470 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -20,8 +20,8 @@ impl MotionWorld<'_, '_, '_> { .hurt(&self.resources.health, self.scene.health_rules, id, damage)?; Ok(()) } - pub(super) fn tick_environment_damage(&mut self) -> Result<()> { - if self.player.fluids.was_touching_water || self.player.spectator { + pub(super) fn tick_remaining_fire(&mut self) -> Result<()> { + if self.player.spectator { self.player.fire_ticks = 0; } if self.player.invulnerable && self.player.fire_ticks > 1 { @@ -33,8 +33,26 @@ impl MotionWorld<'_, '_, '_> { } self.player.fire_ticks -= 1; } - if self.player.is_eye_in_fluid(WATER) + if self.player.fluids.was_touching_water { + self.player.fire_ticks = self.player.fire_ticks.min(0); + } + Ok(()) + } + pub(super) fn tick_environment_damage(&mut self) -> Result<()> { + let eye = BlockPos::containing(self.player.position.add_vector(Vec3::new( + 0.0, + f64::from(self.player.dimensions.eye_height), + 0.0, + ))); + let bubble_column = self + .assets + .registry + .state(self.block(eye)) + .is_some_and(|state| state.name == "minecraft:bubble_column"); + let submerged = self.player.is_eye_in_fluid(WATER) && !bubble_column; + if submerged && !self.player.status.water_breathing + && !self.player.status.breath_of_the_nautilus && !self.player.invulnerable && !self.player.spectator { @@ -49,7 +67,10 @@ impl MotionWorld<'_, '_, '_> { self.player.air = 0; self.environment_hurt("minecraft:drown", 2.0)?; } - } else { + } else if !submerged + || !self.player.status.breath_of_the_nautilus + || self.player.status.water_breathing + { self.player.air = (self.player.air + 4).min(300); } if self.player.is_in_lava() { diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index d94798528..6ae547aa8 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -97,6 +97,10 @@ impl PlayerMotion { pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool { self.fluids.interaction.is_eye_in_fluid(&Membership, tag) } + /// `Player.isUnderWater`: the eye sample from the start of the base tick. + pub fn is_under_water(&self) -> bool { + self.fluids.was_eye_in_water && self.fluids.was_touching_water + } /// `Entity.isInLava`. pub fn is_in_lava(&self) -> bool { !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA) @@ -113,10 +117,23 @@ impl MotionWorld<'_, '_, '_> { self.resources.fluids.fluid(self.block(p)) } /// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`, - /// the lava's fall halving, and the end of the first tick. + /// swimming and remaining fire, lava's fall halving, then the first-tick clear. pub fn fluid_base_tick(&mut self) -> Result<()> { self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER); self.update_fluids()?; + self.player.swimming = !self.player.flying + && self.player.sprinting + && if self.player.swimming { + self.player.fluids.was_touching_water + } else { + self.player.is_under_water() + && is_tagged( + self.fluid_at(BlockPos::containing(self.player.position)) + .kind(), + WATER, + ) + }; + self.tick_remaining_fire()?; if self.player.is_in_lava() { self.player.fall_distance *= 0.5; } From 42eda649a8d75e1221a55010297d95ca976d291b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:45:40 +0100 Subject: [PATCH 10/23] Render Classic menu panorama with vanilla cube-map filtering --- crates/horizon-client/src/game.rs | 91 +---- crates/horizon-client/src/game/packs.rs | 2 + crates/horizon-client/src/gfx.rs | 28 +- crates/horizon-client/src/gfx/panorama.rs | 346 ++++++++++++++++++++ crates/horizon-client/src/gfx/panorama.wgsl | 30 ++ crates/horizon-client/src/hud.rs | 16 +- 6 files changed, 409 insertions(+), 104 deletions(-) create mode 100644 crates/horizon-client/src/gfx/panorama.rs create mode 100644 crates/horizon-client/src/gfx/panorama.wgsl diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2d16d4e28..9a7026d86 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -580,6 +580,7 @@ pub struct Resources { biomes: Arc, environment: Environment, atlas: HudAtlas, + panorama: horizon_client::gfx::panorama::Faces, layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, @@ -6035,91 +6036,6 @@ impl Game<'_> { self.capture(false); Ok(()) } - /// The title panorama as six camera-centred faces (panorama_0..5: - /// front, right, back, left, up, down). - fn panorama_geometry(&self) -> Vec { - let mut out = Vec::new(); - let d = 100.0; - let faces: [(&str, [glam::Vec3; 4]); 6] = [ - ( - "0", - [ - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(-d, -d, -d), - ], - ), - ( - "1", - [ - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(d, -d, -d), - ], - ), - ( - "2", - [ - glam::Vec3::new(d, d, d), - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, -d, d), - glam::Vec3::new(d, -d, d), - ], - ), - ( - "3", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(-d, -d, d), - ], - ), - ( - "4", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(-d, d, -d), - ], - ), - ( - "5", - [ - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(-d, -d, d), - ], - ), - ]; - for (index, corners) in faces { - let Some(r) = self - .res - .atlas - .sprites - .get(&format!("gui/title/background/panorama_{index}")) - .copied() - else { - continue; - }; - let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; - for (p, uv) in corners.iter().zip(uv) { - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 2, - color: 0xFFFF_FFFF, - light: 0, - }); - } - } - out - } /// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges). fn apply_equipment(&mut self) { let Some(player) = self.player.as_mut() else { @@ -6976,6 +6892,7 @@ impl Game<'_> { self.res.atlas.height, ), (&self.res.forcefield.2, self.res.forcefield.0), + &self.res.panorama, )) } fn apply_settings(&mut self) { @@ -7788,7 +7705,7 @@ impl Game<'_> { } } let celestial = if title && !live { - self.panorama_geometry() + Vec::new() } else if self.dim == Dim::Overworld && self.potions.effects.get("darkness").is_none() && self.potions.effects.get("blindness").is_none() @@ -8874,6 +8791,7 @@ pub fn run() -> Result<()> { let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], @@ -8941,6 +8859,7 @@ pub fn run() -> Result<()> { biomes, environment, atlas, + panorama, item_renderer: Arc::new(horizon_client::item_render::ItemRenderer::load(&root)?), layer_names, providers: Providers::load(&root), diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index f1e476f8d..0d3f8a74a 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -112,6 +112,7 @@ impl Game<'_> { fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let assets = std::sync::Arc::new(self.res.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(root); atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let item_renderer = horizon_client::item_render::ItemRenderer::load(root)?; @@ -137,6 +138,7 @@ impl Game<'_> { self.res.assets = assets; self.res.context = context.clone(); self.res.atlas = atlas; + self.res.panorama = panorama; self.res.item_renderer = std::sync::Arc::new(item_renderer); self.res.clouds = super::load_clouds(root); self.res.forcefield = super::load_forcefield(root); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 6d8e5384d..698a2528e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -83,6 +83,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod occlusion; +pub mod panorama; mod timing; mod world_post; @@ -137,7 +138,7 @@ pub struct Frame<'a> { /// Skip sections the camera cannot see through open faces (vanilla's /// occlusion graph; off in spectator-like views inside blocks). pub cave_culling: bool, - /// Title screen: only the panorama (in `celestial`) and the HUD. + /// Title screen: only the dedicated panorama cube map and the HUD. pub title: bool, /// Dimensions without a skybox (the Nether) clear to the fog colour. pub skybox: bool, @@ -246,6 +247,7 @@ pub struct Renderer { additive_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. border_pipeline: wgpu::RenderPipeline, border_group: wgpu::BindGroup, @@ -398,6 +400,7 @@ impl Renderer { animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), + panorama_faces: &panorama::Faces, ) -> Result { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); @@ -1357,6 +1360,12 @@ impl Renderer { .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); + let panorama = panorama::Panorama::new( + &device, + &queue, + config.format.remove_srgb_suffix(), + panorama_faces, + ); Ok(Self { instance, surface, @@ -1385,6 +1394,7 @@ impl Renderer { additive_pipeline, celestial_pipeline, celestial_buffer, + panorama, border_pipeline, border_group, border_uniform, @@ -1864,6 +1874,15 @@ impl Renderer { frame.block_flicker, ); let view_proj = self.view_projection(frame); + if frame.title { + self.panorama.prepare( + &self.queue, + self.config.width, + self.config.height, + frame.yaw, + frame.pitch, + ); + } let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let view = crate::camera::view_matrix(frame.yaw, frame.pitch); let sun_angle = frame.sky.sun_angle.to_radians(); @@ -2210,12 +2229,15 @@ impl Renderer { Some(f) => f.sky_end > 2.0, None => !frame.underwater, }; - if sky_visible && (frame.skybox || frame.end_sky) { + if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { if !frame.title && frame.skybox { pass.set_pipeline(&self.sky); pass.draw(0..3, 0..1); } - if celestial_vertices > 0 { + if frame.title { + self.panorama.draw(&mut pass); + pass.set_bind_group(0, &self.group, &[]); + } else if celestial_vertices > 0 { pass.set_pipeline(&self.celestial_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); diff --git a/crates/horizon-client/src/gfx/panorama.rs b/crates/horizon-client/src/gfx/panorama.rs new file mode 100644 index 000000000..d53cd4501 --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.rs @@ -0,0 +1,346 @@ +//! Vanilla 26.3's CubeMapTexture and CubeMap, separate from the pixel-filtered GUI atlas. +use crate::{Result, hud::decode}; +use glam::Mat4; +use std::path::Path; +use wgpu::util::DeviceExt; + +/// Native cube order: +X, -X, +Y, -Y, +Z, -Z (CubeMapTexture.SUFFIXES). +const FACE_ORDER: [u8; 6] = [1, 3, 5, 4, 0, 2]; + +#[derive(Debug)] +pub struct Faces { + pub size: u32, + pub pixels: Vec, +} + +impl Faces { + pub fn load(root: &Path) -> Self { + Self::try_load(root).unwrap_or_else(|error| { + log::warn!("Horizon: title panorama unavailable ({error})"); + Self { + size: 1, + pixels: [96, 110, 111, 255].repeat(6), + } + }) + } + + fn try_load(root: &Path) -> Result { + let background = root.join("assets/minecraft/textures/gui/title/background"); + let mut size = 0; + let mut pixels = Vec::new(); + for face in FACE_ORDER { + let path = background.join(format!("panorama_{face}.png")); + let (w, h, data) = decode(&path)?; + if w != h || (size != 0 && w != size) { + return Err(format!( + "{}: panorama faces must be equally sized squares", + path.display() + ) + .into()); + } + size = w; + // CubeMapTexture copies each original image with flipY=true. Keep every texel. + for row in data.chunks_exact((w * 4) as usize).rev() { + pixels.extend_from_slice(row); + } + } + Ok(Self { size, pixels }) + } +} + +fn projection(width: u32, height: u32, yaw: f32, pitch: f32) -> Mat4 { + // CubeMap.render: 85-degree FOV, near/far 0.05/10, rotationX(PI), rotateX, rotateY. + Mat4::perspective_rh( + 85.0f32.to_radians(), + width as f32 / height.max(1) as f32, + 0.05, + 10.0, + ) * Mat4::from_rotation_x(std::f32::consts::PI) + * Mat4::from_rotation_x(pitch.to_radians()) + * Mat4::from_rotation_y(yaw.to_radians()) +} + +pub(super) struct Panorama { + pipeline: wgpu::RenderPipeline, + group: wgpu::BindGroup, + uniform: wgpu::Buffer, +} + +impl Panorama { + pub(super) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + faces: &Faces, + ) -> Self { + let texture = device.create_texture_with_data( + queue, + &wgpu::TextureDescriptor { + label: Some("Title panorama cube"), + size: wgpu::Extent3d { + width: faces.size, + height: faces.size, + depth_or_array_layers: 6, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &faces.pixels, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::Cube), + ..Default::default() + }); + // CubeMapTexture's blur=true metadata: linear minification and magnification, no mips. + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Title panorama linear filtering"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Title panorama projection"), + size: 64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Title panorama bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::Cube, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Title panorama resources"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Title panorama shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("panorama.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Title panorama layout"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Title panorama"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_panorama"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_panorama"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + group, + uniform, + } + } + + pub(super) fn prepare( + &self, + queue: &wgpu::Queue, + width: u32, + height: u32, + yaw: f32, + pitch: f32, + ) { + queue.write_buffer( + &self.uniform, + 0, + bytemuck::cast_slice(&projection(width, height, yaw, pitch).to_cols_array()), + ); + } + + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) { + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.group, &[]); + pass.draw(0..36, 0..1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + fs, + sync::atomic::{AtomicU32, Ordering}, + }; + + struct Fixture(std::path::PathBuf); + impl Fixture { + fn new(size: u32) -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let root = std::env::temp_dir().join(format!( + "horizon-panorama-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + let fixture = Self(root); + fs::create_dir_all(fixture.background()).unwrap(); + for face in 0..6 { + fixture.write(face, size, size); + } + fixture + } + fn background(&self) -> std::path::PathBuf { + self.0 + .join("assets/minecraft/textures/gui/title/background") + } + fn write(&self, face: u8, w: u32, h: u32) { + let file = + fs::File::create(self.background().join(format!("panorama_{face}.png"))).unwrap(); + let mut encoder = png::Encoder::new(file, w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels: Vec = (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| [face, (x % 251) as u8, (y % 253) as u8, 255]) + }) + .collect(); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn original_resolution_texels_and_vanilla_cube_orientation_are_preserved() { + let f = Fixture::new(1024); + let faces = Faces::try_load(&f.0).unwrap(); + assert_eq!(faces.size, 1024); + assert_eq!(faces.pixels.len(), 6 * 1024 * 1024 * 4); + // CubeMapTexture's actual layer suffixes, with each source row flipped vertically. + for (layer, source_face) in [1, 3, 5, 4, 0, 2].into_iter().enumerate() { + for y in 0..1024 { + for x in 0..1024 { + let at = ((layer * 1024 + y) * 1024 + x) * 4; + assert_eq!( + faces.pixels[at..at + 4], + [source_face, (x % 251) as u8, ((1023 - y) % 253) as u8, 255] + ); + } + } + } + } + + #[test] + fn placeholders_load_and_incomplete_or_mismatched_cubes_fall_back() { + let f = Fixture::new(1); + assert_eq!(Faces::try_load(&f.0).unwrap().size, 1); + f.write(5, 2, 1); + assert!( + Faces::try_load(&f.0) + .unwrap_err() + .to_string() + .contains("equally sized squares") + ); + let fallback = Faces::load(&f.0); + assert_eq!(fallback.pixels.len(), 24); + f.write(5, 2, 2); + assert!(Faces::try_load(&f.0).is_err()); + fs::remove_file(f.background().join("panorama_5.png")).unwrap(); + assert!(Faces::try_load(&f.0).is_err()); + assert_eq!(Faces::load(&f.0).size, 1); + } + + #[test] + fn cube_shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("panorama.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } + + #[test] + fn vanilla_camera_centres_the_positive_z_face_and_pitches_ten_degrees() { + let straight = projection(1920, 1080, 0.0, 0.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + assert!((straight.x / straight.w).abs() < 1e-6); + assert!((straight.y / straight.w).abs() < 1e-6); + assert!(straight.w > 0.0); + let pitched = projection(1920, 1080, 0.0, 10.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + let expected_y = 10.0f32.to_radians().tan() / 42.5f32.to_radians().tan(); + assert!((pitched.y / pitched.w - expected_y).abs() < 1e-6); + } +} diff --git a/crates/horizon-client/src/gfx/panorama.wgsl b/crates/horizon-client/src/gfx/panorama.wgsl new file mode 100644 index 000000000..26c53949a --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.wgsl @@ -0,0 +1,30 @@ +// CubeMap's position-only cube and panorama.vsh/fsh: sample its untransformed direction. +struct Projection { view_proj: mat4x4 } +@group(0) @binding(0) var projection: Projection; +@group(0) @binding(1) var panorama: texture_cube; +@group(0) @binding(2) var panorama_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) direction: vec3, +} +@vertex fn vs_panorama(@builtin(vertex_index) index: u32) -> Out { + let corners = array, 8>( + vec3(-1.0, -1.0, -1.0), vec3(1.0, -1.0, -1.0), + vec3(1.0, 1.0, -1.0), vec3(-1.0, 1.0, -1.0), + vec3(-1.0, -1.0, 1.0), vec3(1.0, -1.0, 1.0), + vec3(1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0), + ); + let indices = array( + 4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1, + 1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4, + 7, 3, 2, 7, 2, 6, 0, 4, 5, 0, 5, 1, + ); + let position = corners[indices[index]]; + var out: Out; + out.clip = projection.view_proj * vec4(position, 1.0); + out.direction = position; + return out; +} +@fragment fn fs_panorama(in: Out) -> @location(0) vec4 { + return textureSample(panorama, panorama_sampler, in.direction); +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 6161160dd..568faa36e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -147,9 +147,7 @@ impl HudAtlas { walk(&textures.join("map"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); - (!s.contains("title/background") || s.contains("panorama_")) - && !s.contains("realms") - && !s.contains("presets") + !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { let name = path @@ -166,18 +164,6 @@ impl HudAtlas { } else { pixels }; - // Title panorama faces are downsampled to 256 for the shared atlas. - if name.contains("panorama_") && w >= 512 && w == h { - let step = (w / 256) as usize; - let mut small = Vec::with_capacity(256 * 256 * 4); - for y in 0..256usize { - for x in 0..256usize { - let i = ((y * step) * w as usize + x * step) * 4; - small.extend_from_slice(&pixels[i..i + 4]); - } - } - return Some((name, 256, 256, small)); - } (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); From 2f34bf7b4665378abe88882a6ed2b5e53073939b Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Wed, 14 Oct 2026 16:57:51 -0400 Subject: [PATCH 11/23] Invert crosshair rendering and show attack cooldown indicators --- crates/horizon-client/src/game.rs | 15 ++- crates/horizon-client/src/game/hand.rs | 178 ++++++++++++++++++++++++- crates/horizon-client/src/hud.rs | 162 +++++++++++++++++----- crates/horizon-client/src/hud.wgsl | 5 + 4 files changed, 325 insertions(+), 35 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 88163e47c..0db6f3c09 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3292,12 +3292,19 @@ impl Game<'_> { self.draw_spyglass(&mut batch); // Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth / // extractVehicleHealth and the experience bar, laid out by hud_layout. - // Horizon has no attack cooldown yet: the strength is always full. + let attack_speed = self.main_hand_attack_speed(); + let attack_strength = self.hand_strength.scale(0.0, attack_speed); let indicator = self.settings.attack_indicator; if self.camera_type.first_person() && !spectator { - let attack = (indicator == 1).then_some(1.0); - let draws = hud_layout::crosshair(wi, hi, attack, false); + let attack = (indicator == 1).then_some(attack_strength); + let full = indicator == 1 + && attack_strength >= 1.0 + && horizon_client::attack_strength::delay(attack_speed) > 5.0 + && self.crosshair_attack_ready(attack_strength, attack_speed); + let draws = hud_layout::crosshair(wi, hi, attack, full); + let start = batch.vertices.len(); hud_layout::paint(&mut batch, &self.res.atlas, &draws); + batch.invert_since(start); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -3306,7 +3313,7 @@ impl Game<'_> { offhand: self.offhand.is_some(), slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)), offhand_pop: 0.0, - attack: (indicator == 2).then_some(1.0), + attack: (indicator == 2).then_some(attack_strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); hud_layout::paint(&mut batch, &self.res.atlas, &draws); diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 5ad7a7f22..11b68768d 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -14,6 +14,39 @@ use horizon_client::{ /// The off hand's place in `visible_hands` (the main hand uses its hotbar slot). const OFFHAND: usize = usize::MAX; +/// `Hud.extractCrosshair`: a charged, living target before any obstruction. +fn attack_indicator_ready( + strength: f32, + speed: f64, + living: Option, + obstruction: Option, + range: Option<&serde_json::Value>, + creative: bool, +) -> bool { + let Some(distance) = living else { + return false; + }; + if !(strength >= 1.0 && horizon_client::attack_strength::delay(speed) > 5.0) + || obstruction.is_some_and(|d| d <= distance) + { + return false; + } + let Some(range) = range else { + return true; + }; + let value = |key: &str, default: f32| range[key].as_f64().map_or(default, |v| v as f32); + let (min, max) = if creative { + ( + value("min_creative_reach", 0.0), + value("max_creative_reach", 5.0), + ) + } else { + (value("min_reach", 0.0), value("max_reach", 3.0)) + }; + let margin = value("hitbox_margin", 0.3); + distance >= f64::from(min - margin) && distance <= f64::from(max + margin) +} + impl Game<'_> { /// `LivingEntity.swing` with `getModifiedSwingDuration`. pub(super) fn swing_hand(&mut self, hand: Hand, animation: SwingAnimation) { @@ -213,13 +246,62 @@ impl Game<'_> { } } /// `Attributes.ATTACK_SPEED` with the main-hand item's modifier. - fn main_hand_attack_speed(&self) -> f64 { + pub(super) fn main_hand_attack_speed(&self) -> f64 { horizon_client::attack_strength::BASE_ATTACK_SPEED + self .held() .and_then(|h| self.res.items.get(&h.item)) .map_or(0.0, |i| f64::from(i.attack_speed)) } + pub(super) fn crosshair_attack_ready(&self, strength: f32, speed: f64) -> bool { + let living = [ + self.mob_hit().map(|h| h.1), + self.armor_stand_hit().map(|h| h.1), + ] + .into_iter() + .flatten() + .min_by(f64::total_cmp); + let block = self.pick().and_then(|hit| { + let eye = self.eye_position()?; + Some( + (0..3) + .map(|i| (hit.point[i] - eye[i]).powi(2)) + .sum::() + .sqrt(), + ) + }); + let obstruction = [ + block, + self.painting_hit().map(|h| h.1), + self.frame_hit().map(|h| h.1), + self.boat_hit().map(|h| h.1), + self.cart_hit().map(|h| h.1), + self.dragon_hit().map(|h| h.1), + ] + .into_iter() + .flatten() + .min_by(f64::total_cmp); + let active = self + .using + .and_then(|(slot, _)| self.inventory.get(slot).and_then(Option::as_ref)) + .or_else(|| self.held()); + let components = active.map(|stack| { + self.res + .item_renderer + .models + .components(&horizon_client::item_render::stack_view(stack)) + }); + attack_indicator_ready( + strength, + speed, + living, + obstruction, + components + .as_ref() + .and_then(|c| c.get("minecraft:attack_range")), + self.creative, + ) + } /// The visible main- and off-hand items. pub(super) fn visible_hand_items(&self) -> [Option; 2] { [ @@ -374,3 +456,97 @@ impl HandWorld for GameHands<'_, '_> { } fn release_using(&mut self) {} } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn full_attack_indicator_requires_a_charged_living_target_before_obstructions() { + assert!(attack_indicator_ready( + 1.0, + 1.6, + Some(2.0), + None, + None, + false + )); + for (strength, speed, living, obstruction) in [ + (0.99, 1.6, Some(2.0), None), + (f32::NAN, 1.6, Some(2.0), None), + (1.0, 4.0, Some(2.0), None), + (1.0, f64::NAN, Some(2.0), None), + (1.0, 1.6, None, None), + (1.0, 1.6, Some(2.0), Some(1.5)), + (1.0, 1.6, Some(2.0), Some(2.0)), + ] { + assert!(!attack_indicator_ready( + strength, + speed, + living, + obstruction, + None, + false + )); + } + assert!(attack_indicator_ready( + 1.0, + 1.6, + Some(2.0), + Some(2.5), + None, + false + )); + } + + #[test] + fn full_attack_indicator_uses_inclusive_float_attack_range_bounds() { + let range = serde_json::json!({ + "min_reach": 2.0, + "max_reach": 4.5, + "min_creative_reach": 2.0, + "max_creative_reach": 6.5, + "hitbox_margin": 0.125, + }); + for (creative, min, max) in [(false, 1.875, 4.625), (true, 1.875, 6.625)] { + for distance in [min, max] { + assert!(attack_indicator_ready( + 1.0, + 1.6, + Some(distance), + None, + Some(&range), + creative + )); + } + for distance in [min - 0.0001, max + 0.0001] { + assert!(!attack_indicator_ready( + 1.0, + 1.6, + Some(distance), + None, + Some(&range), + creative + )); + } + } + let defaults = serde_json::json!({}); + let max = f64::from(3.0f32 + 0.3f32); + assert!(attack_indicator_ready( + 1.0, + 1.6, + Some(max), + None, + Some(&defaults), + false + )); + assert!(!attack_indicator_ready( + 1.0, + 1.6, + Some(max + 1e-8), + None, + Some(&defaults), + false + )); + } +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 71db32199..2d441fb5a 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -287,6 +287,7 @@ pub static GUI_SCALE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU3 /// One frame of overlay geometry in GUI pixels. pub struct HudBatch { pub vertices: Vec, + inverse_ranges: Vec>, pub scale: f32, pub width: f32, pub height: f32, @@ -310,12 +311,44 @@ impl HudBatch { } Self { vertices: Vec::new(), + inverse_ranges: Vec::new(), scale: scale as f32, width: (window[0] as f32 / scale as f32).ceil(), height: (window[1] as f32 / scale as f32).ceil(), patches: Vec::new(), } } + /// Use the crosshair's destination-dependent blend for vertices just emitted. + /// Calls follow draw order, so ordinary HUD geometry keeps its own blend. + pub fn invert_since(&mut self, start: usize) { + let range = start as u32..self.vertices.len() as u32; + if range.is_empty() { + return; + } + if let Some(last) = self.inverse_ranges.last_mut() { + debug_assert!(last.end <= range.start); + if last.end == range.start { + last.end = range.end; + return; + } + } + self.inverse_ranges.push(range); + } + /// Split the shared vertex buffer without changing the order of overlays. + fn draw_ranges(&self) -> impl Iterator, bool)> + '_ { + let end = self.vertices.len() as u32; + self.inverse_ranges + .iter() + .cloned() + .chain(std::iter::once(end..end)) + .scan(0, |start, inverse| { + let normal = *start..inverse.start; + *start = inverse.end; + Some([(normal, false), (inverse, true)]) + }) + .flatten() + .filter(|(range, _)| !range.is_empty()) + } /// `AbstractContainerScreen.init`: center in integer GUI coordinates. pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) { ( @@ -604,6 +637,7 @@ pub struct HudRenderer { /// The shared atlas texture, for run-time glyph uploads. pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, + inverse_pipeline: wgpu::RenderPipeline, group: wgpu::BindGroup, uniform: wgpu::Buffer, buffer: wgpu::Buffer, @@ -684,35 +718,50 @@ impl HudRenderer { ..Default::default() }); let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4]; - let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: Some("HUD"), - layout: Some(&pipeline_layout), - vertex: wgpu::VertexState { - module: &shader, - entry_point: Some("vs_main"), - compilation_options: Default::default(), - buffers: &[Some(wgpu::VertexBufferLayout { - array_stride: std::mem::size_of::() as u64, - step_mode: wgpu::VertexStepMode::Vertex, - attributes: &attributes, - })], + let make_pipeline = |label, blend, fragment_entry| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(label), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + compilation_options: Default::default(), + buffers: &[Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &attributes, + })], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(fragment_entry), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: Some(blend), + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }) + }; + let pipeline = make_pipeline("HUD", wgpu::BlendState::ALPHA_BLENDING, "fs_main"); + let inverse_pipeline = make_pipeline( + "HUD crosshair", + wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::OneMinusDst, + dst_factor: wgpu::BlendFactor::OneMinusSrc, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent::REPLACE, }, - primitive: Default::default(), - depth_stencil: None, - multisample: Default::default(), - fragment: Some(wgpu::FragmentState { - module: &shader, - entry_point: Some("fs_main"), - compilation_options: Default::default(), - targets: &[Some(wgpu::ColorTargetState { - format, - blend: Some(wgpu::BlendState::ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - }), - multiview_mask: None, - cache: None, - }); + "fs_crosshair", + ); let capacity = 1 << 16; let buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("HUD vertices"), @@ -723,6 +772,7 @@ impl HudRenderer { Ok(Self { atlas_texture: None, pipeline, + inverse_pipeline, group, uniform, buffer, @@ -800,10 +850,16 @@ impl HudRenderer { color_attachments: &attachments, ..Default::default() }); - pass.set_pipeline(&self.pipeline); pass.set_bind_group(0, &self.group, &[]); pass.set_vertex_buffer(0, self.buffer.slice(..)); - pass.draw(0..count as u32, 0..1); + for (range, inverse) in batch.draw_ranges() { + pass.set_pipeline(if inverse { + &self.inverse_pipeline + } else { + &self.pipeline + }); + pass.draw(range, 0..1); + } } } @@ -811,12 +867,58 @@ impl HudRenderer { mod tests { use super::*; + #[test] + fn hud_shader_validates_both_fragment_entries() { + let module = naga::front::wgsl::parse_str(include_str!("hud.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } + + #[test] + fn crosshair_blend_ranges_preserve_overlay_order() { + let mut batch = HudBatch::new([640, 480]); + assert!(batch.draw_ranges().next().is_none()); + let quad = |batch: &mut HudBatch| batch.quad([[0.0; 2]; 4], [[0.0; 2]; 4], u32::MAX); + quad(&mut batch); + assert_eq!(batch.draw_ranges().collect::>(), [(0..6, false)]); + // Missing sprites emit nothing and must not switch the blend. + batch.invert_since(batch.vertices.len()); + let start = batch.vertices.len(); + quad(&mut batch); + batch.invert_since(start); + // Adjacent crosshair pieces use the same pipeline. + let start = batch.vertices.len(); + quad(&mut batch); + batch.invert_since(start); + quad(&mut batch); + let start = batch.vertices.len(); + quad(&mut batch); + batch.invert_since(start); + assert_eq!( + batch.draw_ranges().collect::>(), + [ + (0..6, false), + (6..18, true), + (18..24, false), + (24..30, true) + ] + ); + // A later menu stays on the ordinary blend and draws over the crosshair. + quad(&mut batch); + assert_eq!(batch.draw_ranges().last(), Some((30..36, false))); + } + #[test] fn container_origins_use_java_integer_division() { // Odd scaled dimensions, odd image sizes and an oversized panel. for (width, height) in [(640, 360), (641, 361), (456, 256), (534, 300), (100, 100)] { let batch = HudBatch { vertices: Vec::new(), + inverse_ranges: Vec::new(), scale: 3.0, width: width as f32, height: height as f32, diff --git a/crates/horizon-client/src/hud.wgsl b/crates/horizon-client/src/hud.wgsl index ab7c4642a..055bfc1f1 100644 --- a/crates/horizon-client/src/hud.wgsl +++ b/crates/horizon-client/src/hud.wgsl @@ -26,3 +26,8 @@ struct Out { if c.a < 0.004 { discard; } return c; } +@fragment fn fs_crosshair(in: Out) -> @location(0) vec4 { + let c = textureSample(atlas, atlas_sampler, in.uv) * in.color; + if c.a == 0.0 { discard; } + return c; +} From 99514c4b7944d630f0b4eec52ab5c11357207e80 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:16:21 +0100 Subject: [PATCH 12/23] perf(client): buffer model and render JSON reads --- .../examples/json_readers_bench.rs | 205 ++++++++++++++++++ crates/horizon-client/src/models.rs | 4 +- crates/horizon-client/src/models/catalog.rs | 2 +- 3 files changed, 208 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/examples/json_readers_bench.rs diff --git a/crates/horizon-client/examples/json_readers_bench.rs b/crates/horizon-client/examples/json_readers_bench.rs new file mode 100644 index 000000000..a9e370f0a --- /dev/null +++ b/crates/horizon-client/examples/json_readers_bench.rs @@ -0,0 +1,205 @@ +//! Compare the exact read/deserialize sequences used by the model loaders. +//! Run with `cargo run -p horizon-client --profile fast --example json_readers_bench`. +//! Optional arguments: resource directory, repetitions (default 9). +use serde_json::{Map, Value, json}; +use std::{ + collections::BTreeMap, + fmt::Debug, + fs::{self, File}, + hint::black_box, + io::BufReader, + path::{Path, PathBuf}, + time::Instant, +}; + +type Result = horizon_client::Result; + +#[derive(Clone, Copy)] +enum Reader { + File, + Buffered, + Slice, +} +const READERS: [Reader; 3] = [Reader::File, Reader::Buffered, Reader::Slice]; + +// These match the map types and reader expressions at all three production sites. +macro_rules! reader { + ($name:ident, $map:ty) => { + fn $name(path: &Path, reader: Reader) -> Result<$map> { + Ok(match reader { + Reader::File => serde_json::from_reader(File::open(path)?)?, + Reader::Buffered => serde_json::from_reader(BufReader::new(File::open(path)?))?, + Reader::Slice => serde_json::from_slice(&fs::read(path)?)?, + }) + } + }; +} +reader!(prepare_facts, Map); +reader!(catalog_facts, BTreeMap); + +struct Fixture(PathBuf); +impl Fixture { + fn new() -> Result { + let root = + std::env::temp_dir().join(format!("horizon-json-readers-{}", std::process::id())); + fs::create_dir(&root)?; + Ok(Self(root)) + } +} +impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } +} + +fn fixtures(root: &Path) -> Result<()> { + let states: Vec<_> = (0..56) + .map(|i| { + json!({"facing": (["north", "east", "south", "west"][i % 4]), + "powered": if i / 4 % 2 == 0 { "false" } else { "true" }, + "age": (i / 8).to_string()}) + }) + .collect(); + let mut models = Map::new(); + let mut render = Map::new(); + for i in 0..1024 { + let name = format!("minecraft:fixture_block_{i:04}"); + models.insert( + name.clone(), + json!({ + "schema": {"facing": {"named": ["north", "east", "south", "west"]}, + "powered": {"named": ["false", "true"]}, "age": {"integer": [0, 6]}}, + "states": states + }), + ); + render.insert( + name, + json!({"rule": "never", "can_occlude": true, "bars_tag": false}), + ); + } + fs::write(root.join("model-states.json"), serde_json::to_vec(&models)?)?; + fs::write( + root.join("render-definitions.json"), + serde_json::to_vec(&render)?, + )?; + Ok(()) +} + +fn benchmark( + label: &str, + path: &Path, + repetitions: usize, + read: impl Fn(&Path, Reader) -> Result, +) -> Result<()> { + let expected = read(path, Reader::File)?; + for reader in READERS { + assert_eq!(expected, read(path, reader)?); + for _ in 0..2 { + black_box(read(black_box(path), reader)?); + } + } + drop(expected); + let mut samples: [Vec; 3] = std::array::from_fn(|_| Vec::new()); + for repetition in 0..repetitions { + // Rotate reader order to distribute drift across implementations. + for offset in 0..3 { + let index = (repetition + offset) % 3; + let start = Instant::now(); + let value = black_box(read(black_box(path), READERS[index])?); + samples[index].push(start.elapsed().as_secs_f64() * 1000.0); + drop(value); // Match the loaders: retain the parsed tree after loading. + } + } + let median: Vec<_> = samples + .iter_mut() + .map(|s| { + s.sort_by(f64::total_cmp); + s[s.len() / 2] + }) + .collect(); + println!( + "{label}: {} bytes, {repetitions} samples/reader, median ms: File={:.3}, BufReader={:.3}, read+slice={:.3}; slice speedup={:.2}x", + fs::metadata(path)?.len(), + median[0], + median[1], + median[2], + median[0] / median[2] + ); + Ok(()) +} + +fn main() -> Result<()> { + let args: Vec<_> = std::env::args().skip(1).collect(); + let fixture = if args.is_empty() { + Some(Fixture::new()?) + } else { + None + }; + let root = fixture + .as_ref() + .map(|f| f.0.clone()) + .unwrap_or_else(|| PathBuf::from(&args[0])); + if fixture.is_some() { + fixtures(&root)?; + println!( + "Generated representative fixtures: 1024 blocks, 57344 model states; warm filesystem cache." + ); + } + let repetitions = args.get(1).map(|s| s.parse()).transpose()?.unwrap_or(9); + assert!(repetitions > 0, "repetitions must be positive"); + benchmark( + "prepare model states", + &root.join("model-states.json"), + repetitions, + prepare_facts, + )?; + benchmark( + "catalog model states", + &root.join("model-states.json"), + repetitions, + catalog_facts, + )?; + benchmark( + "render definitions", + &root.join("render-definitions.json"), + repetitions, + catalog_facts, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reader_equivalence_and_errors() -> Result<()> { + let fixture = Fixture::new()?; + let path = fixture.0.join("test.json"); + fs::write(&path, br#"{"minecraft:stone":{"schema":{},"states":[{}]},"unicode":"\u2603","duplicate":1,"duplicate":2}"#)?; + let expected = prepare_facts(&path, Reader::File)?; + for reader in READERS { + assert_eq!(expected, prepare_facts(&path, reader)?); + assert_eq!( + expected.iter().collect::>(), + catalog_facts(&path, reader)?.iter().collect() + ); + } + for invalid in [b"{\"a\": ".as_slice(), b"{} trailing", b"{\"a\":\"\xff\"}"] { + fs::write(&path, invalid)?; + for reader in READERS { + let error = prepare_facts(&path, reader).unwrap_err(); + assert!(error.downcast_ref::().is_some()); + assert!(catalog_facts(&path, reader).is_err()); + } + } + fs::remove_file(&path)?; + for reader in READERS { + let error = prepare_facts(&path, reader).unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::NotFound + ); + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 23280150b..b593c1f66 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -56,7 +56,7 @@ pub fn prepare( sprites: &mut Sprites, ) -> Result { let facts: serde_json::Map = - serde_json::from_reader(std::fs::File::open(root.join("model-states.json"))?)?; + serde_json::from_slice(&std::fs::read(root.join("model-states.json"))?)?; let blocks: Vec<&str> = facts .keys() .filter(|name| registry.default_state(name).is_some()) @@ -111,7 +111,7 @@ pub fn load_visibility( .tag; let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; let raw: BTreeMap = - serde_json::from_reader(fs::File::open(root.join("render-definitions.json"))?)?; + serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?; let definitions = raw .into_iter() .map(|(name, v)| { diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 61db847a0..d39d19a49 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -56,7 +56,7 @@ impl StateModels { sprites: &mut Sprites, ) -> Result { let facts: BTreeMap = - serde_json::from_reader(fs::File::open(root.join("model-states.json"))?)?; + serde_json::from_slice(&fs::read(root.join("model-states.json"))?)?; let mut choices = Vec::new(); let mut states = BTreeMap::new(); let mut variants = BTreeSet::new(); From 2217ebcb331921d753a21e4538d0525005436507 Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:21:03 +0100 Subject: [PATCH 13/23] perf(client): parse large fact JSON from in-memory bytes --- .../examples/json_load_bench.rs | 124 ++++++++++++++++++ crates/horizon-client/src/assets.rs | 5 +- crates/horizon-client/src/blocks.rs | 12 +- tools/json_load_fixtures.py | 74 +++++++++++ 4 files changed, 208 insertions(+), 7 deletions(-) create mode 100644 crates/horizon-client/examples/json_load_bench.rs create mode 100644 tools/json_load_fixtures.py diff --git a/crates/horizon-client/examples/json_load_bench.rs b/crates/horizon-client/examples/json_load_bench.rs new file mode 100644 index 000000000..8d0ae0d0c --- /dev/null +++ b/crates/horizon-client/examples/json_load_bench.rs @@ -0,0 +1,124 @@ +//! Compare the read + Value parse stages in BlockFacts::load and Assets::load. +//! Usage: json_load_bench RESOURCE_ROOT [REPETITIONS]; see tools/json_load_fixtures.py. +use serde_json::Value; +use std::{ + fs::{self, File}, + hint::black_box, + io::BufReader, + path::Path, + time::{Duration, Instant}, +}; + +type Result = std::result::Result>; + +fn reader(path: &Path) -> Result { + Ok(serde_json::from_reader(BufReader::new(File::open(path)?))?) +} + +fn slice(path: &Path) -> Result { + Ok(serde_json::from_slice(&fs::read(path)?)?) +} + +fn measure(path: &Path, load: fn(&Path) -> Result) -> Result { + let start = Instant::now(); + let value = black_box(load(black_box(path))?); + let elapsed = start.elapsed(); + // Value destruction is excluded; the temporary byte buffer is released by slice(). + drop(value); + Ok(elapsed) +} + +fn main() -> Result<()> { + let mut args = std::env::args().skip(1); + let root = args + .next() + .ok_or("usage: json_load_bench ROOT [REPETITIONS]")?; + let repetitions: usize = args.next().map_or(Ok(15), |s| s.parse())?; + if repetitions == 0 { + return Err("REPETITIONS must be positive".into()); + } + for name in ["gameplay-facts.json", "facts.json"] { + let path = Path::new(&root).join(name); + // Validate complete parsed trees on the exact files being timed. + assert_eq!(reader(&path)?, slice(&path)?); + for _ in 0..2 { + measure(&path, reader)?; + measure(&path, slice)?; + } + let (mut before, mut after) = (Vec::new(), Vec::new()); + for i in 0..repetitions { + // Alternate order to reduce filesystem cache / frequency bias. + if i % 2 == 0 { + before.push(measure(&path, reader)?); + after.push(measure(&path, slice)?); + } else { + after.push(measure(&path, slice)?); + before.push(measure(&path, reader)?); + } + } + before.sort_unstable(); + after.sort_unstable(); + let median = |samples: &[Duration]| { + (samples[(samples.len() - 1) / 2].as_secs_f64() + + samples[samples.len() / 2].as_secs_f64()) + * 500.0 + }; + let (before, after) = (median(&before), median(&after)); + println!( + "{name}: {} bytes; {repetitions} samples; reader {before:.3} ms; slice {after:.3} ms; {:.2}x", + fs::metadata(&path)?.len(), + before / after + ); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reader_and_slice_preserve_values_and_error_categories() -> Result<()> { + let path = + std::env::temp_dir().join(format!("horizon-json-load-{}.json", std::process::id())); + let check = || -> Result<()> { + fs::write( + &path, + br#"{"states":[{"id":0,"hardness":-1.5,"name":"escaped\n\u2603","outline":[[0,0,0,1,1,1]],"enabled":true}],"defaults":null}"#, + )?; + assert_eq!(reader(&path)?, slice(&path)?); + for invalid in [ + &b"{\"states\":["[..], + &b"{\"states\":tru}"[..], + &b"{} trailing"[..], + &b"{\"name\":\"\xff\"}"[..], + ] { + fs::write(&path, invalid)?; + let before = reader(&path).unwrap_err(); + let after = slice(&path).unwrap_err(); + assert_eq!( + before + .downcast_ref::() + .unwrap() + .classify(), + after + .downcast_ref::() + .unwrap() + .classify() + ); + } + fs::remove_file(&path)?; + for load in [reader, slice] { + let error = load(&path).unwrap_err(); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::NotFound + ); + } + Ok(()) + }; + let result = check(); + let _ = fs::remove_file(path); + result + } +} diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index edfdcf0ea..2f74697e0 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -9,7 +9,7 @@ use horizon_world::{ use serde_json::Value; use std::{ collections::BTreeSet, - fs::File, + fs::{self, File}, io::{self, BufReader}, path::Path, sync::Arc, @@ -95,8 +95,7 @@ impl Assets { if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) { return Err(invalid("resources do not match Horizon's pinned data version").into()); } - let facts: Value = - serde_json::from_reader(BufReader::new(File::open(root.join("facts.json"))?))?; + let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; let states = facts["states"] .as_array() .ok_or_else(|| invalid("missing registry state facts"))?; diff --git a/crates/horizon-client/src/blocks.rs b/crates/horizon-client/src/blocks.rs index 25a3033c3..8174a7aa8 100644 --- a/crates/horizon-client/src/blocks.rs +++ b/crates/horizon-client/src/blocks.rs @@ -3,7 +3,13 @@ use crate::Result; use horizon_world::registry::{BlockRegistry, BlockStateId}; use serde_json::Value; -use std::{collections::HashMap, fs::File, io::BufReader, path::Path, sync::Arc}; +use std::{ + collections::HashMap, + fs::{self, File}, + io::BufReader, + path::Path, + sync::Arc, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum RenderShape { @@ -106,9 +112,7 @@ pub struct BlockFacts { } impl BlockFacts { pub fn load(root: &Path, registry: &BlockRegistry) -> Result { - let raw: Value = serde_json::from_reader(BufReader::new(File::open( - root.join("gameplay-facts.json"), - )?))?; + let raw: Value = serde_json::from_slice(&fs::read(root.join("gameplay-facts.json"))?)?; let entries = raw["states"] .as_array() .ok_or("missing gameplay state facts")?; diff --git a/tools/json_load_fixtures.py b/tools/json_load_fixtures.py new file mode 100644 index 000000000..bd1269d4b --- /dev/null +++ b/tools/json_load_fixtures.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""Generate schema-shaped synthetic JSON for json_load_bench (not vanilla exports). + +Usage: python3 tools/json_load_fixtures.py OUTPUT_DIRECTORY +Targets match the reported production file sizes in decimal MB. Fields mirror +VanillaGameplayFactsExporter and VanillaHeightmapOracle; values/shapes/state +distribution are synthetic. These fixtures measure parsing, not registry validity. +""" +import json +from pathlib import Path +import sys + + +def gameplay(i): + solid = i % 4 != 0 + boxes = [[0.0, 0.0, 0.0, 1.0, (j + 1) / 4, 1.0] for j in range(i % 4)] + edges = [] + for axis in range(3): + for u, v in [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]: + start = [0.0] * 3 + start[(axis + 1) % 3], start[(axis + 2) % 3] = u, v + end = start.copy() + end[axis] = 1.0 + edges.append(start + end) + return dict( + id=i, emission=i % 16, dampening=15 if solid else 0, + skylight_down=not solid, shape_occlusion=not solid, can_occlude=solid, + solid_render=solid, hardness=(i % 20) / 4, requires_tool=solid, + replaceable=not solid, random_ticks=i % 3 == 0, block_entity=i % 5 == 0, + render_shape="MODEL", liquid=False, ignited_by_lava=not solid, + push="NORMAL", offset=not solid, full_collision=solid, map_color=8368696, + outline_offset=not solid, outline=boxes, outline_edges=edges, + friction=0.6, speed_factor=1.0, jump_factor=1.0, explosion_resistance=6.0, + item=f"minecraft:fixture_{i % 128}", + sound=dict(volume=1.0, pitch=1.0, **{ + event: {"id": f"minecraft:block.stone.{event}"} + for event in ["break", "step", "place", "hit", "fall"] + }), + ) + + +def facts(i): + name = f"minecraft:fixture_{i // 16}" + properties = dict(facing=["north", "south", "east", "west"][i % 4], + level=str(i % 16), waterlogged=str(i % 2 == 0).lower()) + description = name + "[" + ",".join(f"{k}={v}" for k, v in properties.items()) + "]" + return [name, False, i % 2 == 0, description, + dict(Name=name, Properties=properties)] + + +def write(path, target, entry, defaults=False): + with path.open("wb") as output: + output.write(b'{"states":[') + count = 0 + while output.tell() < target: + if count: + output.write(b",") + output.write(json.dumps(entry(count), separators=(",", ":")).encode()) + count += 1 + output.write(b"]") + if defaults: + output.write(b',"defaults":') + output.write(json.dumps({f"minecraft:fixture_{i // 16}": i + for i in range(0, count, 16)}, + separators=(",", ":")).encode()) + output.write(b"}") + print(f"{path.name}: {path.stat().st_size} bytes, {count} states") + + +root = Path(sys.argv[1]) +root.mkdir(parents=True, exist_ok=True) +write(root / "gameplay-facts.json", 55_700_000, gameplay) +# Leave room for the defaults object (~95 KB at this state count). +write(root / "facts.json", 10_020_000, facts, defaults=True) From dacdf69293785b5728c6eaafaa430a874b79e7a4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:20:06 +0200 Subject: [PATCH 14/23] LAN: offline players get a kept generated name instead of Player (#195) Every offline Horizon player joined as Player, the LAN host's own offline profile, so the host refused every guest with "You logged in from another location". Vanilla's client defaults --username to Player + millis % 1000 and the launcher passes the account's name. Horizon now generates Player + five digits once and keeps it in horizon-player.txt next to options.txt (same name, same offline UUID, same inventory on a friend's world). --name, HORIZON_PLAYER_NAME and a signed-in account still win. tools/test_lan_lifecycle.py: two default guests join one host together, keep their names across rejoins, and a guest named Player is refused. Fixes #195 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 28 +++-- crates/horizon-client/src/game/agent.rs | 5 + crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/offline_name.rs | 122 ++++++++++++++++++++++ tools/test_lan_lifecycle.py | 101 +++++++++++++++--- 6 files changed, 237 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client/src/offline_name.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..5752d9a57 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -208,12 +208,24 @@ struct Options { offscreen: bool, /// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name. server: Option, - player_name: String, + /// `--name`, `HORIZON_PLAYER_NAME` or the signed-in account's name; else + /// [`Options::player_name`] uses the kept offline name. + player_name: Option, /// `--dedicated`: run as a dedicated server; vanilla's server arguments /// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow. dedicated: Option>, } impl Options { + /// The name to join servers with: the one given, else the offline name kept + /// next to options.txt (created on first use). + fn player_name(&self) -> String { + self.player_name.clone().unwrap_or_else(|| { + std::env::current_dir().map_or_else( + |_| horizon_client::offline_name::generate(0), + |dir| horizon_client::offline_name::load_or_create(&dir), + ) + }) + } fn read() -> Result> { let sibling = std::env::current_exe()? .parent() @@ -246,7 +258,9 @@ impl Options { .ok() .and_then(|v| v.parse().ok()), server: None, - player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), + player_name: std::env::var("HORIZON_PLAYER_NAME") + .ok() + .filter(|n| !n.is_empty()), dedicated: None, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); @@ -255,7 +269,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -298,7 +312,7 @@ impl Options { "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), "--server" => o.server = Some(value), - "--name" => o.player_name = value, + "--name" => o.player_name = Some(value), "--session-file" => session_file = Some(value), "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), @@ -324,7 +338,7 @@ impl Options { if let Some(path) = session_file.filter(|p| !p.is_empty()) { match horizon_client::auth::AuthSession::load(path.as_ref()) { Ok(session) => { - o.player_name = session.name.clone(); + o.player_name = Some(session.name.clone()); horizon_client::auth::set_current(session); } Err(e) => eprintln!("Horizon: not signed in: {e}"), @@ -8444,7 +8458,7 @@ impl ApplicationHandler for Game<'_> { creative, } => self.open_world(&folder, Some(&name), seed, creative)?, Action::Connect { address } => { - self.connect_server(&address, &self.options.player_name.clone())? + self.connect_server(&address, &self.options.player_name())? } Action::None => {} } @@ -9283,7 +9297,7 @@ pub fn run() -> Result<()> { _ if game.options.server.is_some() => { let (address, name) = ( game.options.server.clone().unwrap_or_default(), - game.options.player_name.clone(), + game.options.player_name(), ); game.connect_server(&address, &name)?; if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index e2b02d199..e554cd520 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -506,6 +506,11 @@ impl Game<'_> { Mode::Error { message, .. } => { json!({ "mode": "world-operation-error", "message": message }) } + Mode::Multiplayer(horizon_client::multiplayer::Screen::Disconnected { + reason, .. + }) => { + json!({ "mode": "multiplayer", "disconnected": reason }) + } Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }), } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 567dd3a72..61c0cce0a 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -484,7 +484,7 @@ impl Game<'_> { } let name = words .get(2) - .map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); + .map_or_else(|| self.options.player_name(), |n| (*n).to_owned()); self.connect_server(arg(1)?, &name)?; ok() } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index cb8fec3a6..1e1aab960 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -100,6 +100,7 @@ pub mod music; pub mod nbt_path; pub mod net; pub mod nether_portal; +pub mod offline_name; pub mod options_file; pub mod options_fixes; pub mod options_horizon; diff --git a/crates/horizon-client/src/offline_name.rs b/crates/horizon-client/src/offline_name.rs new file mode 100644 index 000000000..552f15570 --- /dev/null +++ b/crates/horizon-client/src/offline_name.rs @@ -0,0 +1,122 @@ +//! The offline player name, when neither `--name`, `HORIZON_PLAYER_NAME` nor a +//! signed-in account gives one. Vanilla's client defaults `--username` to +//! `"Player" + System.currentTimeMillis() % 1000` (net.minecraft.client.main.Main) +//! and the official launcher always passes the account's name, so two players +//! rarely share one. Horizon used plain `Player` for everyone, which is also +//! the LAN host's own profile: every guest got the host's offline UUID and was +//! refused with "You logged in from another location". The generated name is +//! kept in `horizon-player.txt` next to `options.txt` so the same player gets +//! the same offline UUID (and inventory on a friend's world) every time. +use std::{fs, path::Path}; + +pub const FILE: &str = "horizon-player.txt"; +const KEY: &str = "name:"; + +/// StringUtil.isValidPlayerName, plus not empty (the login screen sends at least one character). +pub fn is_valid(name: &str) -> bool { + crate::lan::conn::valid_name(name) +} + +/// `Player` and five digits (vanilla's default has three: one shared name in a +/// thousand pairs is too many for a game that keeps it). +pub fn generate(seed: u64) -> String { + format!("Player{:05}", seed % 100_000) +} + +/// The name kept in `dir`, created on first use. A file that can't be written +/// still yields a name for this run. +pub fn load_or_create(dir: &Path) -> String { + let path = dir.join(FILE); + if let Some(name) = fs::read_to_string(&path).ok().and_then(|text| parse(&text)) { + return name; + } + let name = generate(seed()); + if let Err(e) = fs::write(&path, format!("{KEY}{name}\n")) { + log::warn!( + "Horizon: could not keep the player name in {}: {e}", + path.display() + ); + } + name +} + +fn parse(text: &str) -> Option { + text.lines() + .find_map(|line| line.trim_end_matches('\r').strip_prefix(KEY)) + .filter(|name| is_valid(name)) + .map(str::to_owned) +} + +fn seed() -> u64 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); + // Two players starting the game in the same millisecond still differ. + let mut x = nanos ^ u64::from(std::process::id()).rotate_left(32); + x ^= x >> 33; + x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); + x ^ (x >> 33) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!( + "horizon-offline-name-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn generated_names_are_valid_and_never_the_hosts_profile() { + for seed in [0, 7, 99_999, 100_000, u64::MAX] { + let name = generate(seed); + assert!(is_valid(&name), "{name}"); + // The LAN host's own profile (game/chat.rs PLAYER_NAME). + assert_ne!(name, "Player"); + assert_eq!(name.len(), 11); + } + assert_eq!(generate(42), "Player00042"); + } + + #[test] + fn the_name_is_kept_and_reused() { + let d = dir("kept"); + let first = load_or_create(&d); + assert_eq!( + fs::read_to_string(d.join(FILE)).unwrap(), + format!("name:{first}\n") + ); + assert_eq!(load_or_create(&d), first); + // An edited name is used as it is. + fs::write(d.join(FILE), "name:Alex_2\r\n").unwrap(); + assert_eq!(load_or_create(&d), "Alex_2"); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn invalid_names_are_replaced() { + for text in [ + "", + "name:", + "name:has space", + "name:ThisNameIsTooLong17", + "name:été", + ] { + let d = dir("invalid"); + fs::write(d.join(FILE), text).unwrap(); + let name = load_or_create(&d); + assert!( + name.starts_with("Player") && is_valid(&name), + "{text:?} -> {name}" + ); + assert_eq!(load_or_create(&d), name); + let _ = fs::remove_dir_all(&d); + } + } +} diff --git a/tools/test_lan_lifecycle.py b/tools/test_lan_lifecycle.py index 5344e7564..1ad67d0f9 100644 --- a/tools/test_lan_lifecycle.py +++ b/tools/test_lan_lifecycle.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 -"""Check LAN shutdown when leaving a singleplayer world through the pause menu. +"""Check LAN shutdown when leaving a singleplayer world through the pause menu, +and that offline guests joining with their default names are not refused as the +host's profile (#195: everyone was "Player"). Requires a built horizon-client, prepared resources and a display on Unix: xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client @@ -101,6 +103,45 @@ def scenario(endpoint, scanner): command(endpoint, 'quit') +def start_client(client, resources, home, endpoint, log, *extra): + return subprocess.Popen([ + str(client), '--resources', str(resources), '--render-distance', '2', + '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', *extra, + ], cwd=home, env=dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO='1', + HORIZON_MENU_STYLE='classic', HORIZON_PLAYER_NAME=''), + stdout=log, stderr=subprocess.STDOUT) + + +def guest_names(endpoint, port, guests): + """Two guests with default names join together; a guest named like the host is refused.""" + names = [] + for home, guest in guests: + wait_for(guest, 'screen', lambda value: value['screen'] == 'title') + command(guest, f'connect 127.0.0.1:{port}') + wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) + kept = (home / 'horizon-player.txt').read_text() + assert kept.startswith('name:Player') and kept.strip() != 'name:Player', kept + names.append(kept.strip().removeprefix('name:')) + assert names[0] != names[1], names + status = wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 2) + assert sorted(g['name'] for g in status['guests']) == sorted(names), status + # The same home keeps its name: leave and join again as the same profile. + home, guest = guests[0] + command(guest, 'disconnect') + wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 1) + command(guest, f'connect 127.0.0.1:{port}') + wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) + assert (home / 'horizon-player.txt').read_text().strip() == f'name:{names[0]}' + # A guest that really is the host's offline profile is refused, the others stay. + command(guest, 'disconnect') + command(guest, f'connect 127.0.0.1:{port} Player') + refused = wait_for(guest, 'screen', lambda value: (value.get('menu') or {}).get('disconnected')) + assert 'another location' in refused['menu']['disconnected'], refused + status = command(endpoint, 'lan status') + assert [g['name'] for g in status['guests']] == [names[1]], status + return names + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--client', type=Path, required=True) @@ -116,12 +157,7 @@ def main(): scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0')) with (work / 'client.log').open('w+') as log: - process = subprocess.Popen([ - str(client), '--resources', str(resources), '--render-distance', '2', - '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', - ], cwd=work, env=dict(os.environ, HORIZON_HOME=str(work), HORIZON_NO_AUDIO='1', - HORIZON_MENU_STYLE='classic'), - stdout=log, stderr=subprocess.STDOUT) + process = start_client(client, resources, work, endpoint, log) try: scenario(endpoint, scanner) assert process.wait(timeout=20) == 0, 'client exited unsuccessfully' @@ -130,14 +166,51 @@ def main(): print('\n'.join(log.read().splitlines()[-20:])) raise finally: - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=10) - except subprocess.TimeoutExpired: - process.kill() - process.wait(timeout=10) + stop(process) + names = guests_scenario(client, resources, work) print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private') + print(f'LAN guests passed: default names {names[0]} and {names[1]} joined together and kept; ' + '"Player" refused as the host\'s profile') + + +def stop(process): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + +def guests_scenario(client, resources, work): + host_home = work / 'host' + homes = [work / 'guest-a', work / 'guest-b'] + processes, logs = [], [] + try: + for home in [host_home, *homes]: + home.mkdir() + log = (home / 'client.log').open('w+') + logs.append(log) + processes.append(start_client(client, resources, home, home / 'control.sock', log)) + endpoint = host_home / 'control.sock' + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + command(endpoint, 'open LanGuests 0 creative') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + port = command(endpoint, 'lan open 0')['port'] + return guest_names(endpoint, port, [(home, home / 'control.sock') for home in homes]) + except Exception: + for log in logs: + log.seek(0) + print(f'--- {log.name}') + print('\n'.join(log.read().splitlines()[-20:])) + raise + finally: + for process in processes: + stop(process) + for log in logs: + log.close() if __name__ == '__main__': From bf7b3d140f8da83540a4f555a80e90b5efce44a9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:22:08 +0200 Subject: [PATCH 15/23] Play the player's hurt sound for every damage, by its damage effects (#144) Vanilla plays the hurt sound on the client from broadcastDamageEvent (LivingEntity.handleDamageEvent -> Player.getHurtSound, the damage type's DamageEffects sound, pitch (r - r) * 0.2 + 1). Horizon only played entity.player.hurt by hand for falls and mob hits, so sweet berry bushes (poking -> hurt_sweet_berry_bush), fire and lava (burning -> hurt_on_fire), drowning, freezing, cactus and the rest were silent. The combat port's broadcast_damage now carries its damage source (HealthEvent::DamageBroadcast, same trace line as before) and the game plays hurt_sound(effects) for it; the two hand-written plays are gone. Fixes #144 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 5 +++ crates/horizon-client/src/game.rs | 7 ++-- crates/horizon-client/src/game/combat.rs | 14 +++++++ crates/horizon-client/src/game/creatures.rs | 3 -- crates/horizon-client/src/health.rs | 41 ++++++++++++++++++++- 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 6705235ae..54bd3bda8 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -617,6 +617,11 @@ impl Audio { let seed = self.random.next_long(); self.play_seeded(event, at, volume, pitch, seed); } + /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the + /// client (the entity's own random there, never the server's world random). + pub fn hurt_pitch(&mut self) -> f32 { + (self.random.next_float() - self.random.next_float()) * 0.2 + 1.0 + } /// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound. pub fn play_button_click(&mut self) { self.play_instance( diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..5da5b7654 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2942,9 +2942,10 @@ impl Game<'_> { b.notify_written(level, ticks, position, level_flags::UPDATE_ALL) }); } - MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => { - self.audio - .play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); + MotionEvent::Health(horizon_client::health::HealthEvent::DamageBroadcast { + source, + }) => { + self.player_hurt_sound(source, feet); } MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 73c6b7fc0..14a1133e0 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -54,6 +54,20 @@ impl Game<'_> { .push((damage_type.to_owned(), (mob, name))); } } + /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the + /// source's `DamageEffects` (`Player.getHurtSound`). + pub(super) fn player_hurt_sound( + &mut self, + source: horizon_world::damage_source::DamageTypeId, + at: [f64; 3], + ) { + let Some(d) = self.motion.health.damage.definition(source) else { + return; + }; + let sound = horizon_client::health::hurt_sound(&d.effects); + let pitch = self.audio.hurt_pitch(); + self.audio.play(sound, Some(at), 1.0, pitch); + } /// `CombatTracker.recordDamage` for the motion events of this tick. pub(super) fn record_combat(&mut self, events: &[MotionEvent]) { self.recheck_combat(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8c749b704..ee7f2c111 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1352,9 +1352,6 @@ impl Game<'_> { (player.velocity.y / 2.0 + 0.4).min(0.4), player.velocity.z / 2.0 + dz / l * 0.4, ); - let at = [player.position.x, player.position.y, player.position.z]; - self.audio - .play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); self.hurt_armor(amount); self.thorns(from); } diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 46b4f4542..29cba4610 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -76,6 +76,18 @@ impl HealthResources { .expect("validated landing source") } } +/// `DamageEffects.sound()` by its serialized id: what `Player.getHurtSound` +/// plays for a damage type's `effects` (unknown ids fall back to `hurt`, the codec default). +pub fn hurt_sound(effects: &str) -> &'static str { + match effects { + "drowning" => "minecraft:entity.player.hurt_drown", + "burning" => "minecraft:entity.player.hurt_on_fire", + "poking" => "minecraft:entity.player.hurt_sweet_berry_bush", + "freezing" => "minecraft:entity.player.hurt_freeze", + // HURT and THORNS (both SoundEvents.PLAYER_HURT). + _ => "minecraft:entity.player.hurt", + } +} #[derive(Clone, Copy, Debug)] pub enum HealthEvent { StarvationDamage(f32), @@ -97,6 +109,11 @@ pub enum HealthEvent { amount: f32, }, Phase(&'static str), + /// `ServerLevel.broadcastDamageEvent`: the client's + /// `LivingEntity.handleDamageEvent` plays the source's hurt sound. + DamageBroadcast { + source: DamageTypeId, + }, Criterion { original: f32, amount: f32, @@ -119,6 +136,7 @@ impl HealthEvent { format!("record-damage {:08x}", amount.to_bits()) } Self::Phase(name) => name.into(), + Self::DamageBroadcast { .. } => "broadcast-damage".into(), Self::Criterion { .. } => "hurt-criterion".into(), } } @@ -559,7 +577,10 @@ impl HurtWorld for Environment<'_> { Ok(()) } fn broadcast_damage(&mut self, _: &mut State) -> io::Result<()> { - self.phase("broadcast-damage") + self.event(HealthEvent::DamageBroadcast { + source: self.source.type_id(), + }); + Ok(()) } fn mark_hurt(&mut self, _: &mut State) -> io::Result<()> { *self.sync_velocity = true; @@ -655,3 +676,21 @@ impl ServerPlayerHurtWorld for Environment<'_> { Ok(true) } } + +#[cfg(test)] +mod tests { + #[test] + fn hurt_sounds_follow_damage_effects() { + // DamageEffects: HURT, THORNS, DROWNING, BURNING, POKING, FREEZING. + for (effects, sound) in [ + ("hurt", "minecraft:entity.player.hurt"), + ("thorns", "minecraft:entity.player.hurt"), + ("drowning", "minecraft:entity.player.hurt_drown"), + ("burning", "minecraft:entity.player.hurt_on_fire"), + ("poking", "minecraft:entity.player.hurt_sweet_berry_bush"), + ("freezing", "minecraft:entity.player.hurt_freeze"), + ] { + assert_eq!(super::hurt_sound(effects), sound, "{effects}"); + } + } +} From aec497c94b088c31f48fbd5657d6b4077a74db76 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:31:19 +0200 Subject: [PATCH 16/23] Items, orbs and arrows fly to whoever picks them up (#142) Vanilla's ClientPacketListener.handleTakeItemEntity adds an ItemPickupParticle for every take: the taken entity's render state (extracted at partial tick 1) moves to the collector's x, (y + eyeY) / 2, z along ((life + partial) / 3)^2 over three ticks, the target lerped between ticks (ItemPickupParticleGroup). Horizon removed taken entities at once. game/pickups.rs keeps those particles (joining the group at the end of the particle tick, as ParticleEngine.tick does) and the item, orb and arrow renderers draw them frozen at the moving position. Takes by the player (items, orbs, arrows), by mobs (allays, villagers, piglins, sulfur cubes, raid banners), by LAN guests on the host, and ClientboundTakeItemEntity on a LAN guest or server all add one. Fixes #142 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 39 +++- crates/horizon-client/src/game/allays.rs | 5 + crates/horizon-client/src/game/creatures.rs | 23 ++- crates/horizon-client/src/game/item_draw.rs | 20 +- crates/horizon-client/src/game/lan_actions.rs | 21 +- crates/horizon-client/src/game/pickups.rs | 185 ++++++++++++++++++ crates/horizon-client/src/game/piglins.rs | 5 + crates/horizon-client/src/game/raids.rs | 9 + crates/horizon-client/src/game/remote.rs | 16 ++ crates/horizon-client/src/game/render_tick.rs | 1 + .../horizon-client/src/game/sulfur_cubes.rs | 5 + crates/horizon-client/src/game/villagers.rs | 8 + 12 files changed, 324 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/src/game/pickups.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..6b021757e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -81,6 +81,7 @@ mod paintings; mod passengers; mod persist; mod perspective; +mod pickups; mod piglins; mod postprocess; mod potions; @@ -720,6 +721,8 @@ struct Game<'a> { dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, + /// `ItemPickupParticle`s: taken items, orbs and arrows flying to their collector. + pickups: pickups::Pickups, /// Sign text being edited (`SignEditScreen`). sign_edit: Option, /// An open book, book and quill or lectern screen. @@ -1401,6 +1404,10 @@ impl Game<'_> { match self.give(item.stack.clone()) { None => { self.stats.add("picked_up", &kind, before as i32); + self.add_pickup( + pickups::Taken::Item(Box::new(item)), + pickups::Collector::Player, + ); let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 @@ -1414,6 +1421,10 @@ impl Game<'_> { if rest.count < before { self.stats .add("picked_up", &kind, (before - rest.count) as i32); + self.add_pickup( + pickups::Taken::Item(Box::new(item.clone())), + pickups::Collector::Player, + ); self.audio .play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); } @@ -4924,16 +4935,25 @@ impl Game<'_> { ); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - for o in &self.orbs { - let p = glam::DVec3::new( + let live = self.orbs.iter().map(|o| { + let at = [ o.previous.x + (o.position.x - o.previous.x) * alpha, - o.previous.y + (o.position.y - o.previous.y) * alpha + 0.1, + o.previous.y + (o.position.y - o.previous.y) * alpha, o.previous.z + (o.position.z - o.previous.z) * alpha, - ) - camera; + ]; + (o, at, alpha as f32) + }); + // ItemPickupParticle: the render state extracted at partial tick 1. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + pickups::Taken::Orb(o) => Some((&**o, pickups::position(p, alpha), 1.0)), + _ => None, + }); + for (o, at, partial) in live.chain(taken) { + let p = glam::DVec3::new(at[0], at[1] + 0.1, at[2]) - camera; let icon = o.icon(); let (du, dv) = ((r.u1 - r.u0) / 4.0, (r.v1 - r.v0) / 4.0); let (u0, v0) = (r.u0 + (icon % 4) as f32 * du, r.v0 + (icon / 4) as f32 * dv); - let t = (o.age as f32 + alpha as f32) / 2.0; + let t = (o.age as f32 + partial) / 2.0; let red = ((t.sin() + 1.0) * 0.5 * 255.0) as u32; let blue = (((t + 4.188_79).sin() + 1.0) * 0.1 * 255.0) as u32; let color = 0x8000_0000 | blue << 16 | 255 << 8 | red; @@ -5693,6 +5713,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.experience = Experience { level: self.level.xp_level, @@ -5844,6 +5865,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.mining = None; self.travelling = Some((player, destination)); @@ -5994,6 +6016,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.screen = Screen::Playing; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); @@ -6689,6 +6712,7 @@ impl Game<'_> { let mut orbs = std::mem::take(&mut self.orbs); orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); let mut gained = 0; + let mut taken = Vec::new(); if let Some((min, max)) = bounds { orbs.retain(|o| { let touching = o.position.x + 0.25 > min[0] @@ -6701,12 +6725,16 @@ impl Game<'_> { // ExperienceOrb.playerTouch: one orb every 2 ticks. self.xp_delay = 2; gained += o.value; + taken.push(o.clone()); return false; } true }); } self.orbs = orbs; + for o in taken { + self.add_pickup(pickups::Taken::Orb(Box::new(o)), pickups::Collector::Player); + } if gained > 0 { gained = self.mending(gained); } @@ -9097,6 +9125,7 @@ pub fn run() -> Result<()> { dropped: Vec::new(), next_entity: 0, particles, + pickups: Default::default(), sign_edit: None, book: None, lectern_pulses: Vec::new(), diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index c948663b1..a2a5842b5 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -54,6 +54,11 @@ impl Game<'_> { .inflate(horizon_core::geometry::Vec3::new(1.0, 1.0, 1.0)); if b.contains(e.position) { let take = (max - carried).min(e.stack.count as i32); + let (item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(item)), + super::pickups::Collector::Mob(id), + ); self.mobs[i].extra.ints[1] += take; let e = &mut self.dropped[j]; e.stack.count -= take as u32; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8c749b704..7e2d20ecb 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1434,6 +1434,7 @@ impl Game<'_> { // Player.hasInfiniteMaterials. let creative = self.creative; let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + let mut picked = Vec::new(); projectiles.retain(|shot| { let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else { return true; @@ -1461,10 +1462,17 @@ impl Game<'_> { 0.2, pitch, ); + picked.push(shot.clone()); } !taken }); self.creatures.projectiles = projectiles; + for shot in picked { + self.add_pickup( + super::pickups::Taken::Arrow(Box::new(shot)), + super::pickups::Collector::Player, + ); + } } fn tick_projectiles(&mut self) -> Result<()> { @@ -2672,12 +2680,21 @@ impl Game<'_> { ); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - for a in &self.creatures.projectiles { - let p = glam::DVec3::new( + let live = self.creatures.projectiles.iter().map(|a| { + let at = [ a.previous.x + (a.position.x - a.previous.x) * alpha, a.previous.y + (a.position.y - a.previous.y) * alpha, a.previous.z + (a.position.z - a.previous.z) * alpha, - ) - camera; + ]; + (a, at) + }); + // ItemPickupParticle: a picked-up arrow flying to its collector. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + super::pickups::Taken::Arrow(a) => Some((&**a, super::pickups::position(p, alpha))), + _ => None, + }); + for (a, at) in live.chain(taken) { + let p = glam::DVec3::from_array(at) - camera; let c = p.as_vec3(); let light = self.world.light( a.position.x.floor() as i32, diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index a30a02127..72dd7ea59 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -310,13 +310,25 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - for item in &self.dropped { + let live = self.dropped.iter().map(|item| { let (p, q) = (item.previous, item.position); - let pos = glam::DVec3::new( + let at = [ p.x + (q.x - p.x) * alpha, p.y + (q.y - p.y) * alpha, p.z + (q.z - p.z) * alpha, - ) - camera; + ]; + (item, at, alpha as f32) + }); + // ItemPickupParticle: the render state extracted at partial tick 1. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + super::pickups::Taken::Item(item) => { + Some((&**item, super::pickups::position(p, alpha), 1.0)) + } + _ => None, + }); + for (item, at, partial) in live.chain(taken) { + let q = item.position; + let pos = glam::DVec3::from_array(at) - camera; if pos.length_squared() > 64.0 * 64.0 { continue; } @@ -331,7 +343,7 @@ impl Game<'_> { if state.is_empty() { continue; } - let age = item.age as f32 + alpha as f32; + let age = item.age as f32 + partial; let (lo, _) = state.bounding_box(); let min_offset_y = -lo.y + 0.0625; let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 577bc5777..293afdcdd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -748,10 +748,12 @@ impl Game<'_> { let rest = self.as_guest(host, conn, |g| g.give(stack)).flatten(); match rest { None => { - self.dropped.remove(i); + let item = self.dropped.remove(i); + self.guest_pickup(host, id, item); taken.push((item_id, before)); } Some(rest) if rest.count < before => { + self.guest_pickup(host, id, self.dropped[i].clone()); self.dropped[i].stack = rest; taken.push((item_id, before - self.dropped[i].stack.count)); } @@ -765,6 +767,23 @@ impl Game<'_> { } } + /// The host's own `ItemPickupParticle` toward the guest's model. + fn guest_pickup( + &mut self, + host: &LanHost, + id: i32, + item: horizon_client::entities::ItemEntity, + ) { + use super::pickups::{Collector, Taken, guest_target}; + if let Some(target) = guest_target(host, id as u32) { + self.add_pickup_toward( + Taken::Item(Box::new(item)), + Collector::Guest(id as u32), + target, + ); + } + } + /// Positional sounds and level events of the tick, for the guests. pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) { let sounds = self.audio.capture.take().unwrap_or_default(); diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs new file mode 100644 index 000000000..2729dc98f --- /dev/null +++ b/crates/horizon-client/src/game/pickups.rs @@ -0,0 +1,185 @@ +//! `ItemPickupParticle`: a taken item entity, experience orb or arrow flies +//! into whoever took it over three ticks (`ClientPacketListener.handleTakeItemEntity` +//! adds one for every `ClientboundTakeItemEntityPacket`), drawn with the render +//! state it had when it was taken (`extractEntity(from, 1.0F)`). +use super::Game; +use horizon_client::{ + entities::{ExperienceOrb, ItemEntity}, + projectiles::Projectile, +}; + +/// `ItemPickupParticle.LIFE_TIME`. +const LIFE_TIME: u32 = 3; + +/// The taken entity, as it was when taken. +pub(super) enum Taken { + Item(Box), + Orb(Box), + Arrow(Box), +} +impl Taken { + /// The render state's position: the entity's at partial tick 1. + fn position(&self) -> [f64; 3] { + let p = match self { + Taken::Item(i) => i.position, + Taken::Orb(o) => o.position, + Taken::Arrow(a) => a.position, + }; + [p.x, p.y, p.z] + } +} + +/// Whoever took it: the particle's `target`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Collector { + Player, + /// A mob, or another player on a server (both kept as mobs here). + Mob(u32), + /// A LAN guest, by entity id (the host draws it as a model). + Guest(u32), +} + +pub(super) struct Pickup { + pub taken: Taken, + collector: Collector, + life: u32, + target: [f64; 3], + target_old: [f64; 3], +} + +/// `ParticleEngine`'s ITEM_PICKUP group and the particles waiting to join it. +#[derive(Default)] +pub(super) struct Pickups { + pub live: Vec, + added: Vec, +} +impl Pickups { + pub fn clear(&mut self) { + self.live.clear(); + self.added.clear(); + } +} + +/// `ItemPickupParticleGroup.ParticleInstance.fromParticle`: the position at +/// `partial`, from the taken entity's to the collector's (lerped between ticks) +/// along the square of the particle's age. +pub(super) fn position(p: &Pickup, partial: f64) -> [f64; 3] { + let time = (p.life as f32 + partial as f32) / LIFE_TIME as f32; + let time = f64::from(time * time); + let from = p.taken.position(); + std::array::from_fn(|i| { + let target = p.target_old[i] + partial * (p.target[i] - p.target_old[i]); + from[i] + time * (target - from[i]) + }) +} + +/// A LAN guest's target, from the model the host draws for it. +pub(super) fn guest_target(host: &super::lan::LanHost, id: u32) -> Option<[f64; 3]> { + let m = host.models.values().find(|m| m.id == id)?; + let (p, eye) = (m.position, m.eye_height()); + Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z]) +} + +impl Game<'_> { + /// `ItemPickupParticle.updatePosition`: the collector's x and z, halfway up to its eyes. + fn collector_target(&self, collector: Collector) -> Option<[f64; 3]> { + let (p, eye) = match collector { + Collector::Player => { + let p = self.player.as_ref()?; + (p.position, f64::from(p.dimensions.eye_height)) + } + Collector::Mob(id) => { + let m = self.mobs.iter().find(|m| m.id == id)?; + (m.position, m.eye_height()) + } + Collector::Guest(id) => { + return guest_target(self.lan.as_ref()?, id); + } + }; + Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z]) + } + /// `handleTakeItemEntity`: `particleEngine.add(new ItemPickupParticle(...))` when the + /// collector is known; it joins the group at the end of the next particle tick. + pub(super) fn add_pickup(&mut self, taken: Taken, collector: Collector) { + if let Some(target) = self.collector_target(collector) { + self.add_pickup_toward(taken, collector, target); + } + } + /// [`Self::add_pickup`] with the collector's first target given (a LAN + /// guest's model while the host is taken out for its tick). + pub(super) fn add_pickup_toward( + &mut self, + taken: Taken, + collector: Collector, + target: [f64; 3], + ) { + self.pickups.added.push(Pickup { + taken, + collector, + life: 0, + target, + target_old: target, + }); + } + /// `ParticleEngine.tick` for the ITEM_PICKUP group: age (removed at + /// `LIFE_TIME`), follow the collector, then let the new particles in. + pub(super) fn tick_pickups(&mut self) { + let mut live = std::mem::take(&mut self.pickups.live); + live.retain_mut(|p| { + p.life += 1; + if p.life == LIFE_TIME { + return false; + } + p.target_old = p.target; + if let Some(t) = self.collector_target(p.collector) { + p.target = t; + } + true + }); + live.append(&mut self.pickups.added); + self.pickups.live = live; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn orb_at(x: f64, y: f64, z: f64) -> Taken { + let at = horizon_core::geometry::Vec3::new(x, y, z); + Taken::Orb(Box::new(ExperienceOrb { + position: at, + previous: at, + velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0), + value: 1, + age: 0, + on_ground: false, + })) + } + + #[test] + fn flies_along_the_square_of_its_age_to_the_moving_target() { + let mut p = Pickup { + taken: orb_at(0.0, 64.0, 0.0), + collector: Collector::Player, + life: 0, + target: [3.0, 65.0, 0.0], + target_old: [3.0, 65.0, 0.0], + }; + // Added this tick: still at the orb. + assert_eq!(position(&p, 0.0), [0.0, 64.0, 0.0]); + // Halfway through the first tick: (0.5 / 3)^2 of the way. + let t = (0.5f32 / 3.0) * (0.5 / 3.0); + let mid = position(&p, 0.5); + assert!((mid[0] - 3.0 * f64::from(t)).abs() < 1e-9, "{mid:?}"); + // Last tick before removal, the target moved: lerped between its ticks. + p.life = 2; + p.target_old = [3.0, 65.0, 0.0]; + p.target = [4.0, 65.0, 0.0]; + let end = position(&p, 1.0); + assert!( + (end[0] - 4.0).abs() < 1e-9 && (end[1] - 65.0).abs() < 1e-9, + "{end:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index c51941d02..3515b380b 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -64,6 +64,11 @@ impl Game<'_> { } // Nuggets come whole, anything else one at a time. let item = e.stack.item.clone(); + let (taken_item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(taken_item)), + super::pickups::Collector::Mob(id), + ); let taken = if &*item == "minecraft:gold_nugget" { self.dropped.remove(j).stack.count } else { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index ecb173822..1f1fa3507 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -770,6 +770,7 @@ impl Game<'_> { .map(|(i, e)| (i, e.position)) .collect(); let mut taken: Vec = Vec::new(); + let mut collectors: Vec<(usize, u32)> = Vec::new(); let mut recruit: Vec<(i32, Vec3)> = Vec::new(); let mut joins: Vec<(u32, i32, f32)> = Vec::new(); let mut new_leaders: Vec<(i32, i32, u32)> = Vec::new(); @@ -868,6 +869,7 @@ impl Game<'_> { if p.distance_squared(position) < 1.414 * 1.414 { // pickUpItem: the banner becomes the wave's leader. taken.push(*i); + collectors.push((*i, m.id)); leaders.insert((id, s.wave)); new_leaders.push((id, s.wave, m.id)); s.banner_at = None; @@ -878,6 +880,13 @@ impl Game<'_> { } } } + for (i, mob) in collectors { + let item = self.dropped[i].clone(); + self.add_pickup( + super::pickups::Taken::Item(Box::new(item)), + super::pickups::Collector::Mob(mob), + ); + } taken.sort_unstable(); for i in taken.into_iter().rev() { self.dropped.remove(i); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index bafb71f9e..7156f37c6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -186,6 +186,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.falling.clear(); self.travelling = None; @@ -278,6 +279,7 @@ impl Game<'_> { self.mobs.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.score.board = Default::default(); self.tab_list = Default::default(); self.border = Default::default(); @@ -469,6 +471,7 @@ impl Game<'_> { self.mobs.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); @@ -982,6 +985,19 @@ impl Game<'_> { self.audio .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } + // ItemPickupParticle toward the collector (this player, another one or a mob). + if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() { + let collector = if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) + { + super::pickups::Collector::Player + } else { + super::pickups::Collector::Mob(p.player as u32) + }; + self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector); + } self.remove_entity(p.item); } C::HurtAnimation(p) => { diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4c916e773..46255667a 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -331,6 +331,7 @@ impl Game<'_> { .map(|p| ([p.position.x, p.position.y, p.position.z], p.velocity.y)), }; self.particles.tick(&level); + self.tick_pickups(); for (name, at, volume, pitch) in std::mem::take(&mut self.particles.sounds) { self.audio.play(name, Some(at), volume, pitch); } diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 5a8ae361f..4606f6859 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -126,6 +126,11 @@ impl Game<'_> { continue; } let item = e.stack.item.clone(); + let (taken_item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(taken_item)), + super::pickups::Collector::Mob(id), + ); let e = &mut self.dropped[j]; e.stack.count -= 1; if e.stack.count == 0 { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 0d547c0b0..72fa2839a 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -293,7 +293,15 @@ impl Game<'_> { j += 1; continue; } + let before = self.dropped[j].clone(); let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max); + if rest.as_ref().is_none_or(|r| r.count < before.stack.count) { + let id = self.mobs[i].id; + self.add_pickup( + super::pickups::Taken::Item(Box::new(before)), + super::pickups::Collector::Mob(id), + ); + } match rest { None => { self.dropped.remove(j); From a3fcacb212f4cc7247c74f177eef183af9baa0b6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:32:42 +0200 Subject: [PATCH 17/23] Website: the new favicon reaches browsers at once, and /favicon.ico exists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The icon files kept their names while the server lets browsers cache /favicon* for a week, so visitors still saw the old mark. The pages now link each icon with its content hash (?v=…), and the build writes /favicon.ico (the 32-pixel PNG in an ICO container) for browsers that ask for it on their own. Co-Authored-By: Claude Opus 5.5 --- website/build.mjs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/website/build.mjs b/website/build.mjs index 19451900e..6163d6307 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -122,6 +122,28 @@ await mkdir(join(dist, "assets"), { recursive: true }); await cp(join(site, "public"), dist, { recursive: true }); await cp(join(site, "LEGAL.md"), join(dist, "LEGAL.md")); +// The icons keep their names (browsers and other sites ask for /favicon.svg and the +// rest), so the pages link them with their content's hash: a new mark reaches everyone +// at once instead of after the week the server lets browsers keep the old one. +const iconVersions = {}; +for (const icon of ["favicon.svg", "favicon-32.png", "apple-touch-icon.png"]) { + iconVersions[icon] = fingerprint(await readFile(join(site, "public", icon))); +} +// /favicon.ico, which browsers request on their own: the 32-pixel PNG in an ICO +// container (one image entry; ICO has held PNG data since Windows Vista). +const png32 = await readFile(join(site, "public", "favicon-32.png")); +const ico = Buffer.alloc(22); +ico.writeUInt16LE(0, 0); // reserved +ico.writeUInt16LE(1, 2); // type: icon +ico.writeUInt16LE(1, 4); // one image +ico.writeUInt8(32, 6); // width +ico.writeUInt8(32, 7); // height +ico.writeUInt16LE(1, 10); // colour planes +ico.writeUInt16LE(32, 12); // bits per pixel +ico.writeUInt32LE(png32.length, 14); +ico.writeUInt32LE(22, 18); // the image follows the header and its entry +await writeFile(join(dist, "favicon.ico"), Buffer.concat([ico, png32])); + // The page's modules, fingerprinted; each import of a shared module is rewritten to its name. const names = {}; const rewrite = (code) => code.replace(/"\.\/(\w+\.js)"/g, (all, file) => (names[file] ? `"./${names[file]}"` : all)); @@ -184,6 +206,7 @@ for (const page of ["index.html", "404.html"]) { if (!(key in values)) throw new Error(`${page}: unknown placeholder ${all}`); return values[key]; }); + html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`); await writeFile(join(dist, page), html); } From aec1519f915bd40711387d43969fa104e7e0641f Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:52:59 +0100 Subject: [PATCH 18/23] perf(launcher): share startup release response with update check --- launcher/benchmarks/release-loading.md | 46 ++++ launcher/src/backend.rs | 53 +++- launcher/src/backend/release_loading_tests.rs | 240 ++++++++++++++++++ launcher/src/main.rs | 14 +- 4 files changed, 343 insertions(+), 10 deletions(-) create mode 100644 launcher/benchmarks/release-loading.md create mode 100644 launcher/src/backend/release_loading_tests.rs diff --git a/launcher/benchmarks/release-loading.md b/launcher/benchmarks/release-loading.md new file mode 100644 index 000000000..4c933e3c3 --- /dev/null +++ b/launcher/benchmarks/release-loading.md @@ -0,0 +1,46 @@ +# Shared startup release response + +Startup previously fetched `/releases?per_page=100` on two worker threads: one +for game releases and one for updates. It now decodes that response once and +parses game releases once, publishing them before older-launcher fallback +lookups. Manual and four-hour update checks still request fresh data. Release +page retries remain independent. Existing self-update guards still apply. + +Run the committed benchmark against the actual backend implementation: + +```sh +CARGO_INCREMENTAL=0 CARGO_PROFILE_DEV_DEBUG=0 CARGO_PROFILE_TEST_DEBUG=0 \ + cargo test --manifest-path launcher/Cargo.toml --locked --lib \ + backend::release_loading_tests::benchmark_shared_startup_response \ + -- --ignored --nocapture +``` + +Measured on 2026-10-14, Linux x86_64, AMD Ryzen 5 5600X, Rust 1.99.0, +unoptimized Cargo test profile with debug information disabled. A shared +`CARGO_TARGET_DIR` was used for local build reuse. Each case warms up 20 times +and takes the median of 201 samples; outputs are validated for equivalence +and passed to `black_box`. + +| Scenario | Before median | After median | Ratio | Fetches per startup | +| --- | ---: | ---: | ---: | ---: | +| Serial parsing/decoding work, zero transport delay | 14.701 ms | 7.339 ms | 2.003x | 2 → 1 | +| Concurrent startup workers, 5 ms per mock request | 14.778 ms | 13.642 ms | 1.083x | 2 → 1 | + +The measured 201 samples make 402 mock release-list fetches before and 201 +after. The concurrent case reduces elapsed time by 7.7%; the two old requests +can overlap, so halving requests does not halve startup latency. + +The synthetic 453,197-byte JSON contains 99 game releases (including a draft) +with roughly 4 KiB of notes each and one launcher release with a platform asset. +The mock fetch decodes identical bytes for each request; it does not exercise +HTTP, TLS, GitHub rate limits, filesystem installation scans, GUI rendering or +self-update downloads. The comparison covers backend orchestration, JSON +decoding, sorting, filtering and update selection, not end-to-end launcher +startup or release-build timing. Fallback timing is omitted from the benchmark +and its ordering/error behavior is tested separately. No persistent cache or +extra copy of the game-release vector is introduced. + +Validation: 26 launcher library tests passed (benchmark ignored by default); +the benchmark passed explicitly; full launcher all-target check and Clippy +with `-D warnings` passed; root and launcher format checks and `git diff --check` +passed. The GUI compiled but was not launched interactively. diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index d1ddc2b8c..3812f1536 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -193,13 +193,19 @@ pub fn launcher_releases() -> Result, String> { /// a day, so the newest launcher release can be older than all of those: then the newest /// `launcher-v` tags are looked up one by one (a draft's tag is skipped: it has no public release). fn launcher_releases_in(list: &serde_json::Value) -> Vec { + launcher_releases_in_with(list, |url| { + get(&url)?.into_json().map_err(|e| e.to_string()) + }) +} + +fn launcher_releases_in_with( + list: &serde_json::Value, + json: impl Fn(String) -> Result, +) -> Vec { let found = parse_releases(list, LAUNCHER_ASSET, is_launcher_tag); if found.iter().any(|r| r.asset.is_some()) { return found; } - let json = |url: String| -> Result { - get(&url)?.into_json().map_err(|e| e.to_string()) - }; let api = format!("https://api.github.com/repos/{REPO}"); let Ok(refs) = json(format!( "{api}/git/matching-refs/tags/{LAUNCHER_TAG_PREFIX}" @@ -1172,15 +1178,42 @@ pub fn launcher_update(releases: &[Release]) -> Option { .cloned() } -/// One request to GitHub, both kinds of update. -pub fn check_updates() -> Result { - let list = release_list()?; +/// Load the game's release list and both update kinds from the same GitHub response. +/// Publish the game releases before any fallback lookups for older launcher tags, so those +/// lookups cannot hold up the release pages or opening animation. A list error reaches both. +pub fn releases_and_updates( + on_releases: impl FnOnce(Result, String>), +) -> Result { + releases_and_updates_with(release_list, installed, launcher_releases_in, on_releases) +} + +fn releases_and_updates_with( + load: impl FnOnce() -> Result, + installed: impl FnOnce() -> Vec, + launchers: impl FnOnce(&serde_json::Value) -> Vec, + on_releases: impl FnOnce(Result, String>), +) -> Result { + let list = match load() { + Ok(list) => list, + Err(e) => { + on_releases(Err(e.clone())); + return Err(e); + } + }; + let releases = parse_releases(&list, ASSET, is_game_tag); + let horizon = horizon_update(&releases, &installed()); + on_releases(Ok(releases)); Ok(Updates { - horizon: horizon_update(&parse_releases(&list, ASSET, is_game_tag), &installed()), - launcher: launcher_update(&launcher_releases_in(&list)), + horizon, + launcher: launcher_update(&launchers(&list)), }) } +/// A fresh release-list request for both kinds of update (plus older-launcher fallback if needed). +pub fn check_updates() -> Result { + releases_and_updates(|_| {}) +} + /// Whether a version installed as an update becomes the selected one: only when the player was /// on the newest installed version before (or had none). pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) -> bool { @@ -1543,6 +1576,10 @@ impl Settings { } } +#[cfg(test)] +#[path = "backend/release_loading_tests.rs"] +mod release_loading_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/launcher/src/backend/release_loading_tests.rs b/launcher/src/backend/release_loading_tests.rs new file mode 100644 index 000000000..befef2279 --- /dev/null +++ b/launcher/src/backend/release_loading_tests.rs @@ -0,0 +1,240 @@ +use super::*; +use std::cell::RefCell; +use std::hint::black_box; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::{Duration, Instant}; + +fn fixture() -> String { + let mut list: Vec<_> = (1..=99) + .map(|i| { + serde_json::json!({ + "tag_name": format!("v2026.10.14.{i}"), + "name": format!("Build {i}"), "body": "Release notes\r\n".repeat(256), + "published_at": "2026-10-14T12:00:00Z", "draft": i == 99, + "assets": [{"name": ASSET.unwrap_or("unsupported"), + "browser_download_url": "https://example.test/game", "size": 12345}] + }) + }) + .collect(); + list.push(serde_json::json!({ + "tag_name": "launcher-v99.0.0", "name": "Launcher", "body": "Notes", + "assets": [{"name": LAUNCHER_ASSET.unwrap_or("unsupported"), + "browser_download_url": "https://example.test/launcher", "size": 6789}] + })); + serde_json::to_string(&list).unwrap() +} + +fn installed_fixture() -> Vec { + vec!["v2026.10.14.50".into()] +} + +// The former startup paths: each decodes its own response; the update path parses games again. +fn baseline(load: impl Fn() -> Result) -> (Vec, Updates) { + let releases = parse_releases(&load().unwrap(), ASSET, is_game_tag); + let list = load().unwrap(); + let updates = Updates { + horizon: horizon_update( + &parse_releases(&list, ASSET, is_game_tag), + &installed_fixture(), + ), + launcher: launcher_update(&parse_releases(&list, LAUNCHER_ASSET, is_launcher_tag)), + }; + (releases, updates) +} + +fn shared(load: impl FnOnce() -> Result) -> (Vec, Updates) { + let mut releases = None; + let updates = releases_and_updates_with( + load, + installed_fixture, + |list| parse_releases(list, LAUNCHER_ASSET, is_launcher_tag), + |r| releases = Some(r.unwrap()), + ) + .unwrap(); + (releases.unwrap(), updates) +} + +#[test] +fn one_response_preserves_both_startup_results() { + let text = fixture(); + let requests = AtomicUsize::new(0); + let load = || { + requests.fetch_add(1, Ordering::Relaxed); + Ok(serde_json::from_str(&text).unwrap()) + }; + let old = baseline(load); + assert_eq!(requests.swap(0, Ordering::Relaxed), 2); + let new = shared(load); + assert_eq!(requests.load(Ordering::Relaxed), 1); + assert_eq!( + serde_json::to_value(old).unwrap(), + serde_json::to_value(new).unwrap() + ); +} + +#[test] +fn errors_reach_releases_and_updates_without_fallback() { + for error in [ + "No connection: offline", + "GitHub's rate limit was reached.", + "invalid JSON", + ] { + let mut published = None; + let result = releases_and_updates_with( + || Err(error.into()), + || panic!("no installed scan after failure"), + |_| panic!("no fallback after failure"), + |r| published = Some(r), + ); + assert_eq!(published.unwrap().unwrap_err(), error); + assert_eq!(result.unwrap_err(), error); + } +} + +#[test] +fn publish_games_before_older_launcher_fallback() { + let events = RefCell::new(Vec::new()); + let result = releases_and_updates_with( + || Ok(serde_json::json!([{"tag_name": "v2026.10.14", "assets": []}])), + Vec::new, + |list| { + launcher_releases_in_with(list, |url| { + assert_eq!(events.borrow().first(), Some(&"releases")); + events.borrow_mut().push("fallback"); + if url.contains("matching-refs") { + Ok(serde_json::json!([{"ref": "refs/tags/launcher-v99.0.0"}])) + } else { + Ok( + serde_json::json!({"tag_name": "launcher-v99.0.0", "assets": [{ + "name": LAUNCHER_ASSET.unwrap_or("unsupported"), + "browser_download_url": "u", "size": 1 + }]}), + ) + } + }) + }, + |r| { + assert_eq!(r.unwrap()[0].tag, "v2026.10.14"); + events.borrow_mut().push("releases"); + }, + ) + .unwrap(); + assert_eq!(*events.borrow(), ["releases", "fallback", "fallback"]); + assert_eq!(result.launcher.is_some(), LAUNCHER_ASSET.is_some()); +} + +#[test] +fn failed_launcher_fallback_keeps_game_result_and_checks_stay_fresh() { + let requests = AtomicUsize::new(0); + for day in [14, 15] { + let mut published = None; + let updates = releases_and_updates_with( + || { + requests.fetch_add(1, Ordering::Relaxed); + Ok(serde_json::json!([{"tag_name": format!("v2026.10.{day}")}])) + }, + Vec::new, + |list| launcher_releases_in_with(list, |_| Err("offline".into())), + |r| published = Some(r.unwrap()), + ) + .unwrap(); + assert_eq!(published.unwrap()[0].tag, format!("v2026.10.{day}")); + assert!(updates.launcher.is_none()); + } + assert_eq!(requests.load(Ordering::Relaxed), 2); +} + +#[test] +#[ignore = "local release-loading benchmark; run explicitly with --ignored --nocapture"] +fn benchmark_shared_startup_response() { + let text = fixture(); + let requests = AtomicUsize::new(0); + let load = |delay: Duration| { + requests.fetch_add(1, Ordering::Relaxed); + if !delay.is_zero() { + std::thread::sleep(delay); + } + serde_json::from_str(black_box(&text)).map_err(|e| e.to_string()) + }; + let old = || baseline(|| load(Duration::ZERO)); + let new = || shared(|| load(Duration::ZERO)); + assert_eq!( + serde_json::to_value(old()).unwrap(), + serde_json::to_value(new()).unwrap() + ); + let concurrent_old = || { + std::thread::scope(|scope| { + let releases = scope.spawn(|| { + parse_releases(&load(Duration::from_millis(5)).unwrap(), ASSET, is_game_tag) + }); + let updates = scope.spawn(|| { + let list = load(Duration::from_millis(5)).unwrap(); + Updates { + horizon: horizon_update( + &parse_releases(&list, ASSET, is_game_tag), + &installed_fixture(), + ), + launcher: launcher_update(&parse_releases( + &list, + LAUNCHER_ASSET, + is_launcher_tag, + )), + } + }); + (releases.join().unwrap(), updates.join().unwrap()) + }) + }; + let threaded_new = || { + std::thread::scope(|scope| { + scope + .spawn(|| shared(|| load(Duration::from_millis(5)))) + .join() + .unwrap() + }) + }; + assert_eq!( + serde_json::to_value(concurrent_old()).unwrap(), + serde_json::to_value(threaded_new()).unwrap() + ); + fn measure(run: impl Fn() -> T, requests: &AtomicUsize) -> (u128, usize) { + for _ in 0..20 { + black_box(run()); + } + requests.store(0, Ordering::Relaxed); + let mut times: Vec<_> = (0..201) + .map(|_| { + let start = Instant::now(); + black_box(run()); + start.elapsed().as_nanos() + }) + .collect(); + times.sort_unstable(); + (times[100], requests.load(Ordering::Relaxed)) + } + println!( + "fixture={} bytes; 100 releases; 20 warmups, 201 samples; median ns", + text.len() + ); + for (label, before, after) in [ + ( + "serial zero-delay work", + measure(old, &requests), + measure(new, &requests), + ), + ( + "concurrent startup, 5ms/request", + measure(concurrent_old, &requests), + measure(threaded_new, &requests), + ), + ] { + assert_eq!((before.1, after.1), (402, 201)); + println!( + "{label}: before={} after={} ratio={:.3}x requests={}->{}", + before.0, + after.0, + before.0 as f64 / after.0 as f64, + before.1, + after.1 + ); + } +} diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 5a486f6ea..46863931d 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -263,9 +263,8 @@ impl Launcher { let _ = tx.send(Msg::Reused(reused)); } }); - this.fetch_releases(); + this.fetch_startup_releases(); this.fetch_links(); - this.check_updates(); this } @@ -333,6 +332,17 @@ impl Launcher { }); } + fn fetch_startup_releases(&mut self) { + self.checked = Some(Instant::now()); + let tx = self.tx.clone(); + std::thread::spawn(move || { + let updates = backend::releases_and_updates(|releases| { + let _ = tx.send(Msg::Releases(releases)); + }); + let _ = tx.send(Msg::Updates(updates)); + }); + } + fn fetch_links(&self) { let tx = self.tx.clone(); std::thread::spawn(move || { From 8f3f72c7efaaaa4c5537d76723b4bb7474a62b37 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:54:03 +0200 Subject: [PATCH 19/23] Title screen: "RUST EDITION" under the logo The classic title screen's banner now reads "RUST EDITION". It is rebuilt at load time from the player's own textures/gui/title/edition.png: "EDITION" is kept column for column, the "T" is lifted out of it, and R, U and S are Horizon's own glyphs (rectangles in title_edition.rs) drawn the way the texture's letters are built, in shades sampled from it. "RUST" spans "JAVA"'s columns, so the banner stays centred. Only vanilla 26.3's exact texture (pixel fingerprint) is rebuilt: a resource pack's banner is left as drawn. No Mojang pixels are added to the repository. The logo and banner are now blitted as LogoRenderer does: the logo's top 44 of 64 rows and the banner's top 14 of 16 rows at y = 30 + 44 - 7 (the banner was 20 px too low and squeezed 16 rows into 14). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/hud.rs | 9 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/title.rs | 19 +- crates/horizon-client/src/title_edition.rs | 489 +++++++++++++++++++++ docs/media/brand/README.md | 6 + 5 files changed, 513 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/src/title_edition.rs diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 0f105ff28..a2a539914 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -199,6 +199,15 @@ impl HudAtlas { .collect() }); images.extend(atlas_sprites(root, &images)); + // The title screen's "JAVA EDITION" banner reads "RUST EDITION". + if let Some(edition) = images + .iter_mut() + .find(|i| i.0 == crate::title_edition::SPRITE) + && let Some(pixels) = + crate::title_edition::rust_edition(edition.1, edition.2, &edition.3) + { + edition.3 = pixels; + } images.push(("horizon/white".into(), 4, 4, vec![255; 64])); // Map textures (game/maps.rs) are written into these slots at run time. for i in 0..MAP_SLOTS { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index cb8fec3a6..5065386f5 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -144,6 +144,7 @@ pub mod tab_list; pub mod testgen; pub mod text; pub mod title; +pub mod title_edition; pub mod ui; pub mod ui_theme; pub mod vanillagen; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index c526d7905..bf2438ef3 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -652,24 +652,21 @@ impl Title { let (w, h) = (batch.width.ceil(), batch.height.ceil()); match &self.mode { Mode::Main => { - // Logo: minecraft.png is a 1024x256 sheet drawn at 256x64. - batch.sprite_scaled( + // LogoRenderer: the logo's top 44 of 64 rows, then the edition + // banner's top 14 of 16 rows overlapping its bottom by 7. + batch.sprite_region( atlas, "gui/title/minecraft", - (w / 2.0).floor() - 128.0, - 30.0, + [(w / 2.0).floor() - 128.0, 30.0, 256.0, 44.0], 256.0, 64.0, - u32::MAX, ); - batch.sprite_scaled( + batch.sprite_region( atlas, - "gui/title/edition", - (w / 2.0).floor() - 64.0, - 30.0 + 64.0 - 7.0, + crate::title_edition::SPRITE, + [(w / 2.0).floor() - 64.0, 30.0 + 44.0 - 7.0, 128.0, 14.0], 128.0, - 14.0, - u32::MAX, + 16.0, ); let version = "Horizon 26.3 (Rust)"; batch.text(atlas, version, 2.0, h - 10.0, u32::MAX, true); diff --git a/crates/horizon-client/src/title_edition.rs b/crates/horizon-client/src/title_edition.rs new file mode 100644 index 000000000..80c114dcf --- /dev/null +++ b/crates/horizon-client/src/title_edition.rs @@ -0,0 +1,489 @@ +//! "RUST EDITION" under the classic title screen's logo. +//! +//! Vanilla's `textures/gui/title/edition.png` reads "JAVA EDITION". Horizon +//! never ships Mojang's art, so the banner is rebuilt at load time from the +//! player's own texture: "EDITION" is kept column for column, the "T" is lifted +//! out of it, and R, U and S are Horizon's own glyphs (MIT, the rectangles +//! below), drawn the way the texture's letters are built (a face with darker +//! sides and a light bottom edge, a dark extrusion under it, a black outline +//! and a soft rim) in the shades sampled from the texture itself. Only +//! vanilla 26.3's exact texture is rebuilt: a resource pack's edition.png +//! stays as its author drew it. + +use std::collections::{HashMap, VecDeque}; +use std::ops::Range; + +/// The atlas sprite. +pub const SPRITE: &str = "gui/title/edition"; +const WIDTH: usize = 512; +const HEIGHT: usize = 64; +/// FNV-1a over the size and RGBA pixels of 26.3's edition.png. +const VANILLA: u64 = 0x4249_0538_6dfb_181f; +/// "EDITION", outline included, starts at this column; left of it is "JAVA". +const EDITION_START: usize = 204; +/// The columns of the "T"'s body (face and extrusion) inside "EDITION". +const T_BODY: (usize, usize) = (335, 376); +/// Where the texture's letters put their faces, and how deep they are drawn. +const FACE_TOP: usize = 4; +const EXTRUSION: usize = 8; +const OUTLINE: usize = 3; +/// The face-to-face spacing between letters. +const LETTER_GAP: usize = 6; +/// The new glyphs' face width: "RUST" then spans "JAVA"'s columns to within +/// a texel, so "EDITION" stays where it is and the banner stays centred. +const GLYPH_WIDTH: usize = 42; +/// The first face column, as "JAVA"'s. +const FIRST_FACE: usize = 4; + +/// Horizon's R, U and S: face rectangles `[x0, y0, x1, y1)` in texels from the +/// face's top-left, 42 wide and 39 tall, with 11-texel stems, 10-texel bars and +/// 7-texel notches for the rounded corners. +const R: &[[usize; 4]] = &[ + [0, 0, 11, 39], + [0, 0, 35, 10], + [31, 7, 42, 19], + [0, 15, 35, 25], + [31, 25, 42, 39], +]; +const U: &[[usize; 4]] = &[[0, 0, 11, 32], [31, 0, 42, 32], [7, 29, 35, 39]]; +const S: &[[usize; 4]] = &[ + [7, 0, 42, 10], + [0, 7, 11, 19], + [7, 15, 35, 25], + [31, 21, 42, 32], + [0, 29, 35, 39], +]; + +/// The banner rebuilt to read "RUST EDITION", or `None` when the texture is +/// not vanilla's (a resource pack's own). +pub fn rust_edition(width: u32, height: u32, pixels: &[u8]) -> Option> { + (fingerprint(width, height, pixels) == VANILLA).then(|| compose(pixels)) +} + +fn fingerprint(width: u32, height: u32, pixels: &[u8]) -> u64 { + let mut hash = 0xcbf2_9ce4_8422_2325u64; + let bytes = width.to_le_bytes().into_iter().chain(height.to_le_bytes()); + for b in bytes.chain(pixels.iter().copied()) { + hash = (hash ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3); + } + hash +} + +type Rgba = [u8; 4]; + +fn lum(p: Rgba) -> u32 { + (u32::from(p[0]) + u32::from(p[1]) + u32::from(p[2])) / 3 +} + +fn pixel(pixels: &[u8], x: usize, y: usize) -> Rgba { + let i = (y * WIDTH + x) * 4; + [pixels[i], pixels[i + 1], pixels[i + 2], pixels[i + 3]] +} + +/// The texture's shades: the most common colour in each brightness band. +struct Palette { + highlight: Rgba, + face: Rgba, + rim: Rgba, + extrusion: Rgba, + edge: Rgba, + outline: Rgba, + soft: Rgba, +} + +impl Palette { + fn sample(pixels: &[u8]) -> Self { + let mut bands: [HashMap; 7] = Default::default(); + for &p in pixels.as_chunks::<4>().0 { + let band = match (p[3], lum(p)) { + (0, _) => continue, + (255, 215..) => 0, + (255, 170..) => 1, + (255, 100..) => 2, + (255, 45..) => 3, + (255, 20..) => 4, + (255, _) => 5, + _ => 6, + }; + *bands[band].entry(p).or_default() += 1; + } + let mode = |band: &HashMap, fallback: Rgba| { + band.iter() + .max_by_key(|&(p, n)| (*n, std::cmp::Reverse(*p))) + .map_or(fallback, |(p, _)| *p) + }; + let outline = mode(&bands[5], [0, 0, 0, 255]); + let face = mode(&bands[1], [200, 200, 200, 255]); + Self { + highlight: mode(&bands[0], face), + face, + rim: mode(&bands[2], face), + extrusion: mode(&bands[3], outline), + edge: mode(&bands[4], outline), + outline, + soft: mode(&bands[6], outline), + } + } +} + +/// Faces of the new glyphs, positioned in the texture. +fn glyph_faces() -> Vec { + let mut face = vec![false; WIDTH * HEIGHT]; + for (i, glyph) in [R, U, S].into_iter().enumerate() { + let left = FIRST_FACE + i * (GLYPH_WIDTH + LETTER_GAP); + for &[x0, y0, x1, y1] in glyph { + for y in FACE_TOP + y0..FACE_TOP + y1 { + for x in left + x0..left + x1 { + face[y * WIDTH + x] = true; + } + } + } + } + face +} + +/// Where the "T" lifted from "EDITION" goes: one letter gap after the S. +fn t_left() -> usize { + FIRST_FACE + 3 * (GLYPH_WIDTH + LETTER_GAP) +} + +/// Draw faces within `columns` the way the texture's letters are drawn. +fn draw_glyphs(out: &mut [u8], face: &[bool], palette: &Palette, columns: Range) { + let at = |grid: &[bool], x: isize, y: isize| { + (columns.start as isize..columns.end as isize).contains(&x) + && (0..HEIGHT as isize).contains(&y) + && grid[y as usize * WIDTH + x as usize] + }; + let mut body = face.to_vec(); + for y in 0..HEIGHT { + for x in columns.clone() { + let (xi, yi) = (x as isize, y as isize); + body[y * WIDTH + x] |= (1..=EXTRUSION as isize).any(|k| at(face, xi, yi - k)); + } + } + let reach = OUTLINE as isize + 1; + for y in 0..HEIGHT { + for x in columns.clone() { + let (xi, yi) = (x as isize, y as isize); + let colour = if at(face, xi, yi) { + if !at(face, xi, yi + 1) { + palette.highlight + } else if !at(face, xi - 1, yi) || !at(face, xi + 1, yi) { + palette.rim + } else { + palette.face + } + } else if at(&body, xi, yi) { + if at(face, xi, yi - 1) { + palette.rim + } else if !at(&body, xi - 1, yi) || !at(&body, xi + 1, yi) || !at(&body, xi, yi + 1) + { + palette.edge + } else { + palette.extrusion + } + } else { + let distance = (-reach..=reach) + .flat_map(|dy| (-reach..=reach).map(move |dx| (dx, dy))) + .filter(|&(dx, dy)| at(&body, xi + dx, yi + dy)) + .map(|(dx, dy)| dx.abs().max(dy.abs())) + .min(); + match distance { + Some(d) if d <= OUTLINE as isize => palette.outline, + Some(_) => palette.soft, + None => continue, + } + }; + put(out, x, y, colour); + } + } +} + +/// Paint `p` over what is there unless that is more opaque, or as opaque and +/// brighter (a letter's body wins over a neighbour's outline). +fn put(out: &mut [u8], x: usize, y: usize, p: Rgba) { + let old = pixel(out, x, y); + if (p[3], lum(p)) > (old[3], lum(old)) { + out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&p); + } +} + +/// Every pixel of "EDITION"'s "T": its body, and the outline pixels nearer to +/// it than to its neighbours. +fn t_pixels(pixels: &[u8]) -> Vec<(usize, usize)> { + const NONE: u8 = 0; + const T: u8 = 1; + const OTHER: u8 = 2; + let mut owner = vec![NONE; WIDTH * HEIGHT]; + let mut queue = VecDeque::new(); + for y in 0..HEIGHT { + for x in EDITION_START..WIDTH { + let p = pixel(pixels, x, y); + if p[3] == 255 && lum(p) >= 30 { + owner[y * WIDTH + x] = if (T_BODY.0..=T_BODY.1).contains(&x) { + T + } else { + OTHER + }; + queue.push_back((x, y)); + } + } + } + while let Some((x, y)) = queue.pop_front() { + let label = owner[y * WIDTH + x]; + for (dx, dy) in [ + (-1, -1), + (0, -1), + (1, -1), + (-1, 0), + (1, 0), + (-1, 1), + (0, 1), + (1, 1), + ] { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if !(EDITION_START as isize..WIDTH as isize).contains(&nx) + || !(0..HEIGHT as isize).contains(&ny) + { + continue; + } + let (nx, ny) = (nx as usize, ny as usize); + if owner[ny * WIDTH + nx] == NONE && pixel(pixels, nx, ny)[3] > 0 { + owner[ny * WIDTH + nx] = label; + queue.push_back((nx, ny)); + } + } + } + (0..HEIGHT) + .flat_map(|y| (EDITION_START..WIDTH).map(move |x| (x, y))) + .filter(|&(x, y)| owner[y * WIDTH + x] == T) + .collect() +} + +/// Close the pockets left of "EDITION" that no gap reaches from outside, as +/// the texture's letters fill their counters with the outline. +fn fill_counters(out: &mut [u8], outline: Rgba) { + let open = |out: &[u8], x: usize, y: usize| pixel(out, x, y)[3] < 255; + let mut seen = vec![false; WIDTH * HEIGHT]; + let mut queue = VecDeque::new(); + for y in 0..HEIGHT { + for x in 0..EDITION_START { + let border = x == 0 || y == 0 || x == EDITION_START - 1 || y == HEIGHT - 1; + if border && open(out, x, y) { + seen[y * WIDTH + x] = true; + queue.push_back((x, y)); + } + } + } + while let Some((x, y)) = queue.pop_front() { + for (dx, dy) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { + let (nx, ny) = (x as isize + dx, y as isize + dy); + if !(0..EDITION_START as isize).contains(&nx) || !(0..HEIGHT as isize).contains(&ny) { + continue; + } + let (nx, ny) = (nx as usize, ny as usize); + if !seen[ny * WIDTH + nx] && open(out, nx, ny) { + seen[ny * WIDTH + nx] = true; + queue.push_back((nx, ny)); + } + } + } + for y in 0..HEIGHT { + for x in 0..EDITION_START { + if !seen[y * WIDTH + x] && open(out, x, y) { + out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&outline); + } + } + } +} + +/// Give every edge left of "EDITION" the soft rim the texture's outlines have +/// (the "T"'s right side shared its outline with the next letter). +fn soften_edges(out: &mut [u8], soft: Rgba) { + let opaque = |out: &[u8], x: isize, y: isize| { + (0..EDITION_START as isize).contains(&x) + && (0..HEIGHT as isize).contains(&y) + && pixel(out, x as usize, y as usize)[3] == 255 + }; + let mut rim = Vec::new(); + for y in 0..HEIGHT { + for x in 0..EDITION_START { + let (xi, yi) = (x as isize, y as isize); + let near = (-1..=1).any(|dy| (-1..=1).any(|dx| opaque(out, xi + dx, yi + dy))); + if pixel(out, x, y)[3] == 0 && near { + rim.push((x, y)); + } + } + } + for (x, y) in rim { + out[(y * WIDTH + x) * 4..][..4].copy_from_slice(&soft); + } +} + +/// "RUST" in place of "JAVA"; `pixels` is a 512x64 RGBA banner laid out as +/// vanilla's. +fn compose(pixels: &[u8]) -> Vec { + let palette = Palette::sample(pixels); + let mut out = pixels.to_vec(); + for row in out.as_chunks_mut::<{ WIDTH * 4 }>().0 { + row[..EDITION_START * 4].fill(0); + } + draw_glyphs(&mut out, &glyph_faces(), &palette, 0..EDITION_START); + let left = t_left(); + for (x, y) in t_pixels(pixels) { + put(&mut out, x + left - T_BODY.0, y, pixel(pixels, x, y)); + } + fill_counters(&mut out, palette.outline); + soften_edges(&mut out, palette.soft); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const FACE: Rgba = [208, 197, 192, 255]; + + /// A banner laid out as vanilla's, in made-up colours: every letter a + /// solid block over its vanilla columns, with the font's shading. + fn stand_in() -> Vec { + // Vanilla's letter bodies (extrusion edge included) by column. + let runs = [ + (4, 97), + (101, 144), + (147, 190), + (208, 249), + (256, 296), + (303, 330), + (335, 376), + (381, 411), + (413, 507), + ]; + let mut face = vec![false; WIDTH * HEIGHT]; + for (x0, x1) in runs { + for y in FACE_TOP..FACE_TOP + 39 { + for x in x0..=x1 { + face[y * WIDTH + x] = true; + } + } + } + let palette = Palette { + highlight: [226, 216, 213, 255], + face: FACE, + rim: [153, 147, 145, 255], + extrusion: [61, 57, 56, 255], + edge: [45, 42, 42, 255], + outline: [0, 0, 0, 255], + soft: [0, 0, 0, 244], + }; + let mut out = vec![0; WIDTH * HEIGHT * 4]; + draw_glyphs(&mut out, &face, &palette, 0..WIDTH); + // A colour only "JAVA" has, to see it go. + out[(20 * WIDTH + 30) * 4..][..4].copy_from_slice(&[255, 0, 255, 255]); + out + } + + fn columns(pixels: &[u8], range: Range) -> Vec { + pixels + .as_chunks::<{ WIDTH * 4 }>() + .0 + .iter() + .flat_map(|row| row[range.start * 4..range.end * 4].to_vec()) + .collect() + } + + /// Outlines left of "EDITION" keep their soft rim all round. + fn assert_soft_rim(out: &[u8]) { + for y in 1..HEIGHT - 1 { + for x in 1..EDITION_START - 1 { + if pixel(out, x, y)[3] == 255 { + let near = [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]; + assert!( + near.iter().all(|&(nx, ny)| pixel(out, nx, ny)[3] > 0), + "{x},{y}" + ); + } + } + } + } + + #[test] + fn rust_replaces_java_and_edition_is_untouched() { + let source = stand_in(); + let out = compose(&source); + assert_eq!(out.len(), WIDTH * HEIGHT * 4); + assert_eq!( + columns(&out, EDITION_START..WIDTH), + columns(&source, EDITION_START..WIDTH) + ); + assert!(!out.as_chunks::<4>().0.contains(&[255, 0, 255, 255])); + // R, U and S: their strokes are faces, their notches and counters not. + let lit = |x: usize, y: usize| lum(pixel(&out, x, y)) >= 100; + let glyph = |i: usize, x: usize, y: usize| { + lit( + FIRST_FACE + i * (GLYPH_WIDTH + LETTER_GAP) + x, + FACE_TOP + y, + ) + }; + for (i, shape) in [R, U, S].into_iter().enumerate() { + for &[x0, y0, x1, y1] in shape { + assert!(glyph(i, (x0 + x1) / 2, (y0 + y1) / 2), "glyph {i}"); + } + } + assert!(!glyph(0, 38, 21), "R's notch between bowl and leg"); + assert!(!glyph(0, 20, 30), "R's open bottom"); + assert!(!glyph(1, 20, 5), "U's open top"); + assert!(!glyph(1, 2, 36), "U's rounded corner"); + assert!(!glyph(2, 2, 22), "S's lower-left notch"); + assert!(!glyph(2, 38, 17), "S's upper-right notch"); + // The T is EDITION's, moved. + let shift = T_BODY.0 - t_left(); + for y in 0..HEIGHT { + for x in T_BODY.0..=T_BODY.1 { + let p = pixel(&source, x, y); + if p[3] == 255 && lum(p) >= 30 { + assert_eq!(pixel(&out, x - shift, y), p, "T at {x},{y}"); + } + } + } + assert_soft_rim(&out); + // Nothing below the 14 GUI rows vanilla draws, and the word gap stays open. + assert!(out[WIDTH * 55 * 4..].iter().all(|&b| b == 0)); + let gap = columns(&out, 195..EDITION_START); + assert!(gap.as_chunks::<4>().0.iter().all(|p| p[3] == 0)); + // Centred: "RUST" spans "JAVA"'s columns to within a texel. + let used = |x: usize| (0..HEIGHT).any(|y| pixel(&out, x, y)[3] > 0); + let last = (0..EDITION_START).rev().find(|&x| used(x)).unwrap(); + assert!( + used(0) && (193..=195).contains(&last), + "RUST ends at {last}" + ); + } + + #[test] + fn only_vanilla_is_rebuilt() { + let source = stand_in(); + assert!(rust_edition(512, 64, &source).is_none()); + } + + /// Against the prepared vanilla resources when they are present. + #[test] + fn prepared_vanilla_edition() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../../.local/horizon-client/26.3/assets/minecraft/textures/gui/title/edition.png", + ); + let Ok((w, h, pixels)) = crate::hud::decode(&path) else { + return; + }; + let out = rust_edition(w, h, &pixels).expect("vanilla 26.3's edition.png"); + assert_eq!( + columns(&out, EDITION_START..WIDTH), + columns(&pixels, EDITION_START..WIDTH) + ); + assert_eq!(Palette::sample(&pixels).face, FACE); + assert_soft_rim(&out); + let mut edited = pixels.clone(); + edited[3] ^= 1; + assert!(rust_edition(w, h, &edited).is_none()); + } +} diff --git a/docs/media/brand/README.md b/docs/media/brand/README.md index c038126cb..2b8d4e1e8 100644 --- a/docs/media/brand/README.md +++ b/docs/media/brand/README.md @@ -41,6 +41,12 @@ cd website && npm install node -e 'const {chromium}=require("playwright");(async()=>{const b=await chromium.launch();for(const[f,w,h,o]of[["card",1280,640,"github-social-1280x640"],["banner",960,540,"discord-banner-960x540"]]){const p=await b.newPage({viewport:{width:w,height:h}});await p.goto("file://"+require("path").resolve("../docs/media/brand/social/"+f+".html"));await p.waitForTimeout(300);await p.screenshot({path:"../docs/media/brand/social/"+o+".png"})}await b.close()})()' ``` +## Drawn in code + +| Where | What | +|-------|------| +| `crates/horizon-client/src/title_edition.rs` | the R, U and S of "RUST EDITION" under the classic title screen's logo: Horizon's own glyphs (MIT), rectangles in that file. The banner is rebuilt at load time from the player's own `textures/gui/title/edition.png` (its "EDITION" and "T" carried over, its shades sampled), so no Mojang pixels are in the repository; a resource pack's banner is left as drawn | + ## Uploading (the accounts are Ludovic's) - **GitHub avatar**: github.com/settings/profile (or the organisation's settings), *Edit* the From 86e0e122f4f4c7f864ad2e8206374dafc824371d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:01:26 +0200 Subject: [PATCH 20/23] Release train: ship every settled player-facing change, no 3-hour gap Ludovic wants releases as often as changes land. A kind now releases when player-facing pull requests merged since its last release and the newest of them merged 15 minutes ago (a burst of merges becomes one release), or the oldest an hour ago when merges never pause; release-now still ships at once. There is no minimum time between releases. The scheduled checks run every 10 minutes (game at :02, launcher at :07) so a settled release goes out without another merge. Release titles keep proper nouns (Horizon's mark, Microsoft, LAN, ...) when they lowercase the clauses after the first. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 7 ++++--- .github/workflows/release.yml | 13 +++++++------ docs/release-flow.md | 14 ++++++++------ tests/test_release_train.py | 32 ++++++++++++++++++------------- tools/release_train.py | 35 ++++++++++++++++++++-------------- 5 files changed, 59 insertions(+), 42 deletions(-) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index d41b38092..60d0ba5c1 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,7 +1,8 @@ name: launcher # Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a # push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme), -# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game. +# every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as +# for the game. # A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull # request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits. # Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases. @@ -17,7 +18,7 @@ on: - 'crates/horizon-theme/**' - '.github/workflows/launcher.yml' schedule: - - cron: '47 * * * *' + - cron: '7-59/10 * * * *' workflow_dispatch: inputs: dry_run: @@ -25,7 +26,7 @@ on: type: boolean default: true force: - description: Release even without launcher changes, within the cooldown or while paused + description: Release even without launcher changes, before merges settle or while paused type: boolean default: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4b8444176..0ffa29d26 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,9 @@ name: release -# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release -# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release -# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at -# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them. +# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a +# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: +# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes +# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now. +# RELEASES_PAUSED=1 (repository variable) stops them. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then # publishes vYYYY.MM.DD[.N] with notes from the merged pull requests. @@ -14,7 +15,7 @@ on: types: [completed] branches: [main] schedule: - - cron: '17 * * * *' + - cron: '2-59/10 * * * *' workflow_dispatch: inputs: dry_run: @@ -22,7 +23,7 @@ on: type: boolean default: true force: - description: Release even without player-facing changes, within the cooldown or while paused + description: Release even without player-facing changes, before merges settle or while paused type: boolean default: false permissions: diff --git a/docs/release-flow.md b/docs/release-flow.md index a9bfc166d..4a8951296 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -73,7 +73,7 @@ blocks a fork's pull request; the maintainer decides whether to run it. ## Game releases `.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` run of a push -to main, every hour at :17 (so a release the cooldown held goes out without another merge), and by hand. +to main, every 10 minutes (so a release waiting for merges to settle goes out without another merge), and by hand. ```mermaid flowchart LR @@ -83,7 +83,7 @@ flowchart LR main --> mainchecks{"checks on main"} mainchecks -- green --> decide{"decide
tools/release_train.py"} cron(["every hour :17"]) --> decide - decide -- "player-facing PRs, 3 h since the last release,
or release-now" --> build + decide -- "player-facing PRs settled 15 min
(or waiting 1 h), or release-now" --> build decide -- otherwise --> wait(["wait"]) subgraph build["build, in parallel"] linux["Linux x86_64
GitHub ubuntu-22.04"] @@ -104,8 +104,10 @@ commits) since the last **published** game release: `xtask/`, `packaging/`, `Cargo.toml`, `Cargo.lock`, `research-lock.json`, or an exporter `horizon-prepare` compiles (the `mods/horizon/src/test/java/dev/horizonlab/parity/*.java` files its sources name). Markdown never counts. -- It releases when at least one pull request counts and the last game release is at least 3 hours old. -- A pull request labelled `release-now` (a crash or a blocker) releases at once, cooldown or not. +- It releases when at least one pull request counts and the newest of them merged at least 15 minutes ago, so a burst + of merges becomes one release; if merges never pause, it releases once the oldest has waited an hour. There is no + minimum time between releases: every settled player-facing change ships. +- A pull request labelled `release-now` (a crash or a blocker) releases at once. - A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. - One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing. - A scheduled or hand-started run releases main's newest commit whose `checks` passed; after `checks`, the commit @@ -116,7 +118,7 @@ commits) since the last **published** game release: | Label | Effect | | --- | --- | | `feature` | Listed under **New** (Kira pings the releases role); makes the next launcher release a minor one | -| `release-now` | Releases as soon as main's checks pass, without the cooldown | +| `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle | | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | @@ -193,7 +195,7 @@ and by hand; pushes to `launcher` and `launcher-*` branches only build. - `tools/release_train.py decide --kind launcher` counts the pull requests merged since the last published launcher release that changed those paths (not `launcher/links.json`, which the launcher reads from main, nor - tests or Markdown), with the same 3-hour cooldown, `release-now`, `skip-release` and `RELEASES_PAUSED`. + tests or Markdown), with the same settling rule (15 minutes, at most an hour), `release-now`, `skip-release` and `RELEASES_PAUSED`. - The tag is `launcher-vX.Y.Z`: the patch after the last launcher tag, or the next minor (`X.Y+1.0`) when one of those pull requests is labelled `feature`. - No version-bump commits: the build gets the version in `HORIZON_LAUNCHER_VERSION`, which diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 17414abbd..fef887f3c 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -8,9 +8,10 @@ from tools import release_train as train NOW = dt.datetime(2026, 10, 15, 12, 0, tzinfo=dt.timezone.utc) -def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111"): +def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111", + merged=dt.timedelta(hours=9)): return {"number": number, "title": title, "labels": list(labels), "paths": list(paths), "issues": list(issues), - "author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}"} + "author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}", "merged_at": NOW - merged} class ReleaseTrainTests(unittest.TestCase): @@ -47,17 +48,19 @@ class ReleaseTrainTests(unittest.TestCase): self.assertEqual(train.next_launcher_tag(tags, minor=True), "launcher-v0.2.0") def test_decision(self): - hour = dt.timedelta(hours=1) - decide = lambda prs, age, **kw: train.decision("game", prs, NOW - age, NOW, **kw)[0] - self.assertTrue(decide([pr(1)], 4 * hour)) - self.assertFalse(decide([pr(1)], 2 * hour), "within the cooldown") - self.assertTrue(decide([pr(1, labels=["release-now"])], 0.1 * hour)) - self.assertFalse(decide([pr(1, paths=[])], 9 * hour), "nothing players run") - self.assertFalse(decide([pr(1, labels=["skip-release"])], 9 * hour)) - self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])], 9 * hour)) - self.assertFalse(decide([pr(1)], 9 * hour, paused=True)) - self.assertTrue(decide([], 0.1 * hour, paused=True, force=True)) - self.assertTrue(train.decision("game", [pr(1)], None, NOW)[0], "the first release") + minute = dt.timedelta(minutes=1) + decide = lambda prs, **kw: train.decision("game", prs, NOW, **kw)[0] + self.assertTrue(decide([pr(1, merged=16 * minute)]), "settled for the debounce") + self.assertFalse(decide([pr(1, merged=5 * minute)]), "merged moments ago") + self.assertFalse(decide([pr(1, merged=40 * minute), pr(2, merged=5 * minute)]), "a burst still merging") + self.assertTrue(decide([pr(1, merged=61 * minute), pr(2, merged=2 * minute)]), "merges that never pause still ship") + self.assertTrue(decide([pr(1, labels=["release-now"], merged=minute)])) + self.assertFalse(decide([pr(1, paths=[])]), "nothing players run") + self.assertFalse(decide([pr(1, labels=["skip-release"])])) + self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])])) + self.assertFalse(decide([pr(1, merged=5 * minute), pr(2, labels=["skip-release"], merged=minute)]), "the settled one waits for nothing") + self.assertFalse(decide([pr(1)], paused=True)) + self.assertTrue(decide([], paused=True, force=True)) def test_notes(self): prs = [pr(5, "Nether portals: vanilla timing and linking (fixes #94)", issues=[94]), @@ -73,6 +76,9 @@ class ReleaseTrainTests(unittest.TestCase): self.assertNotIn("#8", body) self.assertIn("Thanks to @cosmic.", body) self.assertLess(body.index("### New"), body.index("### Fixed")) + title, _ = train.notes("game", "v2026.10.15.2", [pr(9, "Horizon's mark", labels=["feature"]), + pr(10, "Game menus", labels=["feature"])], []) + self.assertEqual(title, "Horizon 2026.10.15.2: Game menus, Horizon's mark", "proper nouns keep their capital") def test_a_long_release_is_named_after_its_first_titles(self): prs = [pr(n, f"Change number {n} with a fairly long title") for n in range(1, 10)] diff --git a/tools/release_train.py b/tools/release_train.py index cf3219fde..b881265f9 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -6,8 +6,9 @@ python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes A kind releases when a pull request merged into main since its last published release changed one of its -player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and that release is at least COOLDOWN old, or when one of those -pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count +player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst +of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that never pause still ship), or when one +of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases. Game releases are tagged vYYYY.MM.DD, then .1, .2 the same UTC day; launcher releases launcher-vX.Y.Z, the @@ -29,7 +30,11 @@ import sys ROOT = Path(__file__).resolve().parents[1] REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -COOLDOWN = dt.timedelta(hours=3) +DEBOUNCE = dt.timedelta(minutes=15) +MAX_WAIT = dt.timedelta(hours=1) +# Kept as typed in release titles, where the clauses after the first are lowercased. +PROPER = {"Horizon", "Horizon's", "Minecraft", "Mojang", "Microsoft", "Java", "Xbox", "PlayStation", "Steam", "Windows", + "Linux", "LAN", "Kira", "Discord", "Wayland", "Hyprland", "F3", "GUI", "UI"} EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/" # What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count. @@ -119,7 +124,7 @@ def changed_paths(commit): def pull_request(number): data = gh_json("pr", "view", str(number), "--repo", REPO, "--json", - "number,title,url,labels,closingIssuesReferences,author") + "number,title,url,labels,closingIssuesReferences,author,mergedAt") return { "number": data["number"], "title": data["title"].strip(), @@ -127,6 +132,7 @@ def pull_request(number): "labels": sorted(label["name"] for label in data["labels"]), "issues": sorted(issue["number"] for issue in data.get("closingIssuesReferences") or []), "author": (data.get("author") or {}).get("login", ""), + "merged_at": dt.datetime.fromisoformat(data["mergedAt"].replace("Z", "+00:00")) if data.get("mergedAt") else None, } @@ -143,12 +149,12 @@ def last_release(releases, kind): return max(ours, key=lambda release: tag_key(release["tag_name"]), default=None) -def decision(kind, prs, last_published, now, paused=False, force=False): +def decision(kind, prs, now, paused=False, force=False): """Whether to release now, and why. prs: the merged pull requests since the last release, each with the - files it changed under "paths" (player-facing ones only).""" + files it changed under "paths" (player-facing ones only) and when it merged ("merged_at").""" counted = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] urgent = [pr for pr in counted if "release-now" in pr["labels"]] - age = now - last_published if last_published else None + merged = [pr["merged_at"] for pr in counted if pr.get("merged_at")] if force: return True, "started by hand with force" if paused: @@ -157,9 +163,9 @@ def decision(kind, prs, last_published, now, paused=False, force=False): return False, "no merged pull request changed what players run" if urgent: return True, "release-now: " + ", ".join(f"#{pr['number']}" for pr in urgent) - if age is not None and age < COOLDOWN: - wait = COOLDOWN - age - return False, f"{len(counted)} pull requests wait for the cooldown ({wait.seconds // 60} more minutes)" + if merged and now - max(merged) < DEBOUNCE and now - min(merged) < MAX_WAIT: + wait = DEBOUNCE - (now - max(merged)) + return False, f"{len(counted)} pull requests: waiting {wait.seconds // 60 + 1} more minutes for merges to settle" return True, f"{len(counted)} pull requests changed what players run" @@ -178,7 +184,9 @@ def summary(new, fixed, limit=72): titles.append(title) shown, text = [], "" for title in titles: - title = title if not shown or not title[1:2].islower() else title[0].lower() + title[1:] + first = title.split(" ", 1)[0] + if shown and title[1:2].islower() and first not in PROPER: + title = title[0].lower() + title[1:] candidate = ", ".join(shown + [title]) if shown and len(candidate) > limit - 20: break @@ -265,7 +273,7 @@ def main(): parser.add_argument("--kind", choices=["game", "launcher"], required=True) parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)") parser.add_argument("--tag", help="notes: the release's tag") - parser.add_argument("--force", action="store_true", help="release even without player-facing changes or within the cooldown") + parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused") parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") args = parser.parse_args() @@ -289,8 +297,7 @@ def main(): print(title + "\n\n" + body) return 0 - published = dt.datetime.fromisoformat(last["published_at"].replace("Z", "+00:00")) if last else None - release, reason = decision(args.kind, prs, published, now, os.environ.get("RELEASES_PAUSED") == "1", args.force) + release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force) tags = run("git", "tag", "--list").split() minor = any("feature" in pr["labels"] for pr in prs if pr["paths"]) tag = next_game_tag(tags, now.date()) if args.kind == "game" else next_launcher_tag(tags, minor) From 7a07251acfa3ecf27aab252d3c1c2e98e9eb1d7a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:05:59 +0200 Subject: [PATCH 21/23] CI disk: short artifact retention, runner cleanup, sccache on the Mac runners Releases now ship as often as changes land, so nothing they leave behind may grow without bound. Workflow uploads keep 3 days (nightly parity logs 7); the releases carry their own assets. tools/ci/runner-gc.sh, run every 6 hours by launchd on the Mac mini from a copy of main, skips a runner in a job, removes a checkout's cargo build folders past 12 GB and harness work folders under .local/ untouched for 3 days, and keeps the 2 newest shared preparations while no runner works. The runners build through the machine's sccache, so what it removes comes back from the cache. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 ++ .github/workflows/launcher.yml | 3 +- .github/workflows/nightly.yml | 2 +- .github/workflows/release.yml | 3 +- docs/release-flow.md | 13 +++++++++ tools/ci/runner-env.sh | 5 ++++ tools/ci/runner-gc.sh | 53 ++++++++++++++++++++++++++++++++++ 7 files changed, 78 insertions(+), 3 deletions(-) create mode 100755 tools/ci/runner-gc.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd9cde557..57b7842b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,6 +80,7 @@ jobs: name: parity-logs path: .local/parity-runner/logs/ if-no-files-found: ignore + retention-days: 3 # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in @@ -541,3 +542,4 @@ jobs: dist/client-graphics-smoke.json dist/client-graphics-macos-title.json dist/client-graphics-macos-world.json + retention-days: 3 diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 60d0ba5c1..f0ac59a2b 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -209,7 +209,7 @@ jobs: with: name: ${{ matrix.asset }} path: launcher/out/* - retention-days: 7 + retention-days: 3 release: needs: [decide, build] @@ -250,3 +250,4 @@ jobs: with: name: launcher-release-notes path: notes/ + retention-days: 3 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 59560e262..689cdae59 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -76,4 +76,4 @@ jobs: name: nightly-parity-logs path: .local/parity-runner/logs/ if-no-files-found: ignore - retention-days: 14 + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0ffa29d26..3162b6f1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,7 +181,7 @@ jobs: name: ${{ matrix.asset }} path: dist/${{ matrix.asset }} if-no-files-found: error - retention-days: 7 + retention-days: 3 publish: needs: [decide, build] @@ -222,3 +222,4 @@ jobs: with: name: release-notes path: notes/ + retention-days: 3 diff --git a/docs/release-flow.md b/docs/release-flow.md index 4a8951296..f494bf538 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -229,3 +229,16 @@ time, on the Mac mini's runner, after preparing the resources again if the prepa The bugs session picks the issues up. The audit's logs are the run's `nightly-parity-logs` artifact; harnesses listed `linux_only` are skipped there (see above). By hand: `gh workflow run "nightly audit"` (add `-f dry_run=true` to leave issues alone). + +## Disk + +Releases ship often, so nothing they leave behind may grow without bound. + +- **Artifacts:** every upload keeps 3 days (nightly parity logs 7); a release's assets live on the release itself. +- **Mac runners:** `tools/ci/runner-gc.sh` runs every 6 hours from launchd on the Mac mini, as a copy taken from main + (`~/.actions-runners/runner-gc.sh`, plist `dev.horizon.runner-gc`), never from a pull request's checkout. It skips a + runner in a job, removes a checkout's cargo build folders past 12 GB (`MAX_TARGET_GB`) and harness work folders + under `.local/` untouched for 3 days (`STALE_DAYS`), and keeps the 2 newest shared preparations (`KEEP_PREPARED`) + while no runner works. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes + comes back from the cache. Update the copy after changing the script: + `ssh macmini 'curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/tools/ci/runner-gc.sh -o ~/.actions-runners/runner-gc.sh'`. diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh index b4c5094bd..49158ac91 100755 --- a/tools/ci/runner-env.sh +++ b/tools/ci/runner-env.sh @@ -12,5 +12,10 @@ if [ "$(uname)" = Darwin ]; then java_home=$(/usr/libexec/java_home -v "$java_major") { echo "$bin"; echo "$java_home/bin"; echo /opt/homebrew/bin; } >> "$GITHUB_PATH" 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 + { echo "RUSTC_WRAPPER=/opt/homebrew/bin/sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV" + fi fi echo "HORIZON_NO_AUDIO=1" >> "$GITHUB_ENV" diff --git a/tools/ci/runner-gc.sh b/tools/ci/runner-gc.sh new file mode 100755 index 000000000..0f4f1e4c2 --- /dev/null +++ b/tools/ci/runner-gc.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Keeps the Mac mini's Horizon runners from filling its disk. launchd runs a copy taken from main +# (~/.actions-runners/runner-gc.sh, never a pull request's checkout) every 6 hours; see docs/release-flow.md. +# - A runner in the middle of a job is left alone. +# - A checkout whose cargo build folders (target/ and the harness probes' targets under .local/, the +# directories holding a CACHEDIR.TAG) pass MAX_TARGET_GB loses them: sccache (tools/ci/runner-env.sh) +# makes the next build cheap. Symlinks into the shared vanilla data are never followed. +# - Harness work folders under .local/ (vanilla exports, probe outputs: real directories, not the links into +# the shared vanilla data) that nothing touched for STALE_DAYS go; a harness that runs again rebuilds its own. +# .local/parity-runner (run state, oracle cache) stays. +# - The shared prepared resources keep their KEEP_PREPARED newest preparations, only while no runner works. +set -euo pipefail +root=${RUNNERS:-$HOME/.actions-runners} +max_kb=$(( ${MAX_TARGET_GB:-12} * 1024 * 1024 )) +keep=${KEEP_PREPARED:-2} +stale_min=$(( ${STALE_DAYS:-3} * 24 * 60 )) +busy() { pgrep -f "$1/bin/Runner.Worker" > /dev/null; } + +any_busy=0 +for runner in "$root"/horizon "$root"/horizon-[0-9]*; do + [ -d "$runner/_work" ] || continue + if busy "$runner"; then echo "$(basename "$runner"): in a job, skipped"; any_busy=1; continue; fi + rm -rf "${runner:?}/_work/_temp/"* 2>/dev/null || true + checkout="$runner/_work/horizon/horizon" + [ -d "$checkout" ] || continue + stale=0 + for dir in "$checkout"/.local/*/; do + dir=${dir%/} + [ -L "$dir" ] || [ "$(basename "$dir")" = parity-runner ] && continue + if [ -z "$(find "$dir" -mmin -"$stale_min" -print -quit 2>/dev/null)" ]; then rm -rf "$dir"; stale=$((stale + 1)); fi + done + [ "$stale" = 0 ] || echo "$(basename "$runner"): removed $stale harness folders untouched for ${STALE_DAYS:-3} days" + targets=() + [ -f "$checkout/target/CACHEDIR.TAG" ] && targets+=("$checkout/target") + while IFS= read -r tag; do targets+=("$(dirname "$tag")"); done < <( + find "$checkout/.local" -mindepth 2 -maxdepth 2 -name CACHEDIR.TAG -type f 2>/dev/null) + [ ${#targets[@]} -gt 0 ] || continue + size=$(du -sk "${targets[@]}" | awk '{s += $1} END {print s}') + if [ "$size" -gt "$max_kb" ]; then + rm -rf "${targets[@]}" + echo "$(basename "$runner"): removed ${#targets[@]} build folders ($(( size / 1024 / 1024 )) GB)" + fi +done + +prepared="$root/horizon/_work/horizon/shared-local/prepared" +if [ "$any_busy" = 0 ] && [ -d "$prepared" ] && mkdir "$prepared/.lock" 2>/dev/null; then + trap 'rmdir "$prepared/.lock" 2>/dev/null || true' EXIT + ls -1t "$prepared" | tail -n +"$(( keep + 1 ))" | while read -r old; do + rm -rf "${prepared:?}/$old" + echo "prepared resources $old removed" + done +fi +df -h "$root" | tail -1 From 2ce2ddcd4dd9b0cd0b429e5133c98fa6eb056901 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:07:48 +0200 Subject: [PATCH 22/23] Explorer, treasure and abandoned camp maps work (#147) Vanilla 26.3 has a MapItem per explorer map (buried_treasure_map, abandoned_camp_map, woodland_mansion_map...) and treats any stack with a map_id as a map. Its ExplorationMapFunction finds the nearest structure of the tag, makes an unlimited tracking map centred on it, draws the biome preview (MapItem.renderBiomePreviewMap) and adds the target decoration (MAP_DECORATIONS, drawn by tickCarriedBy). Horizon only recognised filled_map, turned trade maps into filled_map, cleared every decoration but the player's each tick, and chest loot only flagged the map as found: the treasure maps of shipwrecks and underwater ruins and the maps of 26.3's abandoned camps had no map id, no target and no picture. - map_id: any stack with the component. - tick_maps: the item's map_decorations (red X, mansion, camp...) are drawn as addDecoration places them (off the map only when unlimited). - render_biome_preview: vanilla's water outline picture from the noise biomes at sea level (new generator query noise_biomes, fuzzed through BiomeManager's zoom) and #water_on_map_outlines. - Chest loot (rolled with the chunk here) keeps the function's search in minecraft:custom_data; opening the chest runs it from the chest (vanilla runs it when the chest is unpacked on first open), else reaching the inventory runs it from the player. Nothing found drops the item, as the tables' filtered map_id check does. - Trades keep their map item. Fixes #147 Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_death_loot_fixture.rs | 1 + crates/horizon-client/src/game.rs | 6 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/maps.rs | 357 +++++++++++++++++- crates/horizon-client/src/game/trading.rs | 2 +- crates/horizon-client/src/merchant.rs | 23 +- crates/horizon-client/src/mobs/drops.rs | 1 + crates/horizon-client/src/structure_blocks.rs | 152 +++++++- crates/horizon-client/src/vanillagen.rs | 7 + crates/horizon-world/src/loot.rs | 46 ++- .../horizon-world/src/worldgen/generator.rs | 20 + 11 files changed, 572 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs index 1c9d06440..a8eceb8ca 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -21,6 +21,7 @@ fn stack(spec: &str) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, }; for e in parts { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 146e5c8f0..8ce46d5b7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1895,6 +1895,12 @@ impl Game<'_> { // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); + let centre = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + self.resolve_container_maps(key, centre); self.container = Some(key); self.container_opener_event(key, true); self.post_block_game_event( diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 9d7bc79d6..7291931bc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2861,6 +2861,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { .collect(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index f11b96408..3da532a31 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -138,12 +138,116 @@ fn packed_rgba(packed: u8) -> [u8; 4] { let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8; [ch(16), ch(8), ch(0), 255] } +/// `has(DataComponents.MAP_ID)`: filled maps and the explorer map items +/// (`buried_treasure_map`, `woodland_mansion_map`, ..., all `MapItem`s). pub(super) fn map_id(stack: &ItemStack) -> Option { - if &*stack.item != "minecraft:filled_map" { - return None; - } stack.data().and_then(|d| d.map_id) } +/// `MapDecorationTypes`: the sprite of a decoration type that a +/// `minecraft:map_decorations` entry can name. +fn decoration_sprite(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("minecraft:").unwrap_or(id) { + "player" => "map/decorations/player", + "frame" => "map/decorations/frame", + "red_marker" => "map/decorations/red_marker", + "blue_marker" => "map/decorations/blue_marker", + "target_x" => "map/decorations/target_x", + "target_point" => "map/decorations/target_point", + "player_off_map" => "map/decorations/player_off_map", + "player_off_limits" => "map/decorations/player_off_limits", + "mansion" => "map/decorations/woodland_mansion", + "monument" => "map/decorations/ocean_monument", + "red_x" => "map/decorations/red_x", + "village_desert" => "map/decorations/desert_village", + "village_plains" => "map/decorations/plains_village", + "village_savanna" => "map/decorations/savanna_village", + "village_snowy" => "map/decorations/snowy_village", + "village_taiga" => "map/decorations/taiga_village", + "jungle_temple" => "map/decorations/jungle_temple", + "swamp_hut" => "map/decorations/swamp_hut", + "trial_chambers" => "map/decorations/trial_chambers", + "abandoned_camp" => "map/decorations/abandoned_camp", + "ancient_city" => "map/decorations/ancient_city", + "desert_pyramid" => "map/decorations/desert_pyramid", + "mineshaft" => "map/decorations/mineshaft", + "ocean_ruin_warm" => "map/decorations/warm_ocean_ruins", + _ => return None, + }) +} +/// `minecraft:map_decorations` of a map item: (sprite, x, z, rotation), in +/// the component's order. +fn static_decorations(stack: &ItemStack) -> Vec<(&'static str, f64, f64, f32)> { + let Some(Tag::Compound(entries)) = stack.data().and_then(|d| { + d.other + .iter() + .find(|(k, _)| k == "minecraft:map_decorations") + .map(|(_, t)| t) + }) else { + return Vec::new(); + }; + let number = |t: Option<&Tag>| match t { + Some(Tag::Double(b)) => Some(f64::from_bits(*b)), + Some(Tag::Float(b)) => Some(f64::from(f32::from_bits(*b))), + Some(Tag::Int(v)) => Some(f64::from(*v)), + _ => None, + }; + entries + .values() + .filter_map(|e| { + let sprite = match e.get("type") { + Some(Tag::String(s)) => decoration_sprite(&s.to_string_lossy())?, + _ => return None, + }; + Some(( + sprite, + number(e.get("x"))?, + number(e.get("z"))?, + number(e.get("rotation")).unwrap_or(0.0) as f32, + )) + }) + .collect() +} +/// `MapItemSavedData.addTargetDecoration`: the `"+"` entry of +/// `minecraft:map_decorations`, rotation 180. +fn target_decoration(decoration: &str, at: [i32; 3]) -> Tag { + Tag::compound([( + "+", + Tag::compound([ + ("type", Tag::String(decoration.into())), + ("x", Tag::Double(f64::from(at[0]).to_bits())), + ("z", Tag::Double(f64::from(at[2]).to_bits())), + ("rotation", Tag::Float(180.0f32.to_bits())), + ]), + )]) +} +/// `MapItemSavedData.clampMapCoordinate`. +fn clamp_map_coordinate(d: f32) -> i8 { + if d <= -63.0 { + -128 + } else if d >= 63.0 { + 127 + } else { + (d * 2.0 + 0.5) as i8 + } +} +/// `MapItemSavedData.calculateRotation`: spinning in the Nether. +fn decoration_rotation(nether: bool, game_time: i64, y_rot: f64) -> u8 { + if nether { + let s = (game_time / 10) as i32; + (s.wrapping_mul(s) + .wrapping_mul(34_187_121) + .wrapping_add(s.wrapping_mul(121)) + >> 15 + & 15) as u8 + } else { + let adjusted = if y_rot < 0.0 { + y_rot - 8.0 + } else { + y_rot + 8.0 + }; + ((adjusted * 16.0 / 360.0) as i32 & 15) as u8 + } +} impl Game<'_> { fn dimension_id(&self) -> &'static str { match self.dim { @@ -199,6 +303,161 @@ impl Game<'_> { self.maps.data.insert(id, data); let last = self.maps.last_id.unwrap_or(-1).max(id); self.maps.last_id = Some(last); + self.render_biome_preview(id); + } + } + /// `ExplorationMapFunction.run` for an item a generated chest still holds + /// unsearched (`structure_blocks::take_pending_map`): the nearest + /// structure of the tag around `origin`, a new map centred on it with its + /// biome preview and target decoration. False when nothing is found: the + /// loot table's `filtered` map_id check would have discarded the item. + pub(super) fn resolve_pending_map(&mut self, item: &mut ItemStack, origin: [f64; 3]) -> bool { + let Some(map) = horizon_client::structure_blocks::take_pending_map(item) else { + return true; + }; + let names = self.structure_tag(&map.destination); + let from = origin.map(|v| v.floor() as i32); + let found = self + .end + .locator() + .filter(|_| !names.is_empty()) + .and_then(|t| t.locate(&names, from, map.search_radius)); + let Some((_, at)) = found else { + return false; + }; + let mut data = MapData::fresh( + f64::from(at[0]), + f64::from(at[2]), + map.zoom, + self.dimension_id(), + ); + data.unlimited = true; + let id = self.new_map_id(data); + self.render_biome_preview(id); + let d = item.data_mut(); + d.map_id = Some(id); + d.other.retain(|(k, _)| k != "minecraft:map_decorations"); + d.other.push(( + "minecraft:map_decorations".into(), + target_decoration(&map.decoration, at), + )); + true + } + /// The unsearched exploration maps of a container being opened + /// (`RandomizableContainer.unpackLootTable` runs the function then). + pub(super) fn resolve_container_maps(&mut self, key: (i32, i32, i32), origin: [f64; 3]) { + use horizon_client::containers::BlockEntity; + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get(&key) else { + return; + }; + let pending: Vec = slots + .iter() + .enumerate() + .filter(|(_, s)| { + s.as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + }) + .map(|(i, _)| i) + .collect(); + for i in pending { + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let Some(mut item) = slots[i].take() else { + continue; + }; + let keep = self.resolve_pending_map(&mut item, origin); + if let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) { + slots[i] = keep.then_some(item); + } + } + } + /// `MapItem.renderBiomePreviewMap`: the map's biomes at sea level, water + /// outlines (`#water_on_map_outlines`) drawn in orange and brown. + pub(super) fn render_biome_preview(&mut self, id: i32) { + let Some(terrain) = self.end.locator() else { + return; + }; + let dim = self.dimension_id(); + let zoom = self.streaming.biome_zoom; + let watery_biomes: std::collections::HashSet = self + .tag_entries("worldgen/biome", "minecraft:water_on_map_outlines") + .into_iter() + .collect(); + let Some(m) = self.maps.data.get(&id) else { + return; + }; + if m.dimension != dim { + return; + } + let scale = 1i32 << m.scale; + let start_x = m.center[0] / scale - 64; + let start_z = m.center[1] / scale - 64; + let sea_level = 63; + let quarts: Vec<[i32; 3]> = (0..128) + .flat_map(|row| { + (0..128).map(move |column| { + zoom.quart_at_block(horizon_core::position::BlockPos::new( + (start_x + column) * scale, + sea_level, + (start_z + row) * scale, + )) + }) + }) + .collect(); + let watery: Vec = terrain + .noise_biomes(&quarts) + .into_iter() + .map(|b| b.is_some_and(|b| watery_biomes.contains(&b))) + .collect(); + let is_watery = |x: i32, z: i32| watery[(z * 128 + x) as usize]; + // MapColor ids and MapColor.Brightness ids. + const ORANGE: u8 = 15; + const BROWN: u8 = 26; + const LOW: u8 = 0; + const NORMAL: u8 = 1; + const HIGH: u8 = 2; + const LOWEST: u8 = 3; + let Some(m) = self.maps.data.get_mut(&id) else { + return; + }; + for mx in 1..127 { + for mz in 1..127 { + let mut water_count = 0; + for dx in -1..2 { + for dz in -1..2 { + if (dx != 0 || dz != 0) && is_watery(mx + dx, mz + dz) { + water_count += 1; + } + } + } + let mut brightness = LOWEST; + let mut color = 0; + if is_watery(mx, mz) { + color = ORANGE; + if water_count > 7 && mz % 2 == 0 { + let sin = horizon_core::geometry::trig::sin(f64::from(mz as f32 + 0.0)); + match (mx + (sin * 7.0) as i32) / 8 % 5 { + 0 | 4 => brightness = LOW, + 1 | 3 => brightness = NORMAL, + 2 => brightness = HIGH, + _ => {} + } + } else if water_count > 7 { + color = 0; + } else if water_count > 5 { + brightness = NORMAL; + } else if water_count > 1 { + brightness = LOW; + } + } else if water_count > 0 { + color = BROWN; + brightness = if water_count > 3 { NORMAL } else { LOWEST }; + } + if color != 0 { + m.update_color(mx, mz, color << 2 | brightness); + } + } } } /// Registers `data` under a free map id. @@ -250,20 +509,33 @@ impl Game<'_> { let Some(p) = self.player.as_ref().map(|p| p.position) else { return; }; + // A generated exploration map that reached the inventory unsearched + // (moved out of its chest by a hopper): searched from here. + for i in 0..self.inventory.len() { + if self.inventory[i] + .as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + && let Some(mut item) = self.inventory[i].take() + { + let keep = self.resolve_pending_map(&mut item, [p.x, p.y, p.z]); + self.inventory[i] = keep.then_some(item); + } + } let held: Vec = [Some(self.selected), Some(super::shield::OFFHAND_SLOT)] .into_iter() .flatten() .filter_map(|i| self.stack_in(i).and_then(map_id)) .collect(); - let carried: Vec = self + let carried: Vec<(i32, Vec<(&'static str, f64, f64, f32)>)> = self .inventory .iter() .chain(std::iter::once(&self.offhand)) .flatten() - .filter_map(map_id) + .filter_map(|s| Some((map_id(s)?, static_decorations(s)))) .collect(); let (yaw, dim) = (self.yaw, self.dimension_id()); - for id in carried { + let (nether, game_time) = (self.dim == super::Dim::Nether, self.world.game_time); + for (id, targets) in carried { let Some(m) = self.map(id) else { continue }; // tickCarriedBy: the player marker while tracking in this dimension. m.decorations.clear(); @@ -302,6 +574,26 @@ impl Game<'_> { }); } } + // The item's MAP_DECORATIONS (an explorer map's target), added + // after the players as addDecoration would. + let s = (1 << m.scale) as f32; + for (sprite, x, z, rotation) in targets { + let dx = (x - f64::from(m.center[0])) as f32 / s; + let dz = (z - f64::from(m.center[1])) as f32 / s; + let inside = (-63.0..=63.0).contains(&dx) && (-63.0..=63.0).contains(&dz); + if !inside && !m.unlimited { + continue; + } + let d = Decoration { + sprite, + x: clamp_map_coordinate(dx), + y: clamp_map_coordinate(dz), + rot: decoration_rotation(nether, game_time, f64::from(rotation)), + }; + if !m.decorations.contains(&d) { + m.decorations.push(d); + } + } } for id in held { self.update_map(id); @@ -663,3 +955,56 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_target_decoration_type_has_its_sprite() { + // MapDecorationTypes: (name, asset). + for (name, asset) in [ + ("mansion", "woodland_mansion"), + ("monument", "ocean_monument"), + ("red_x", "red_x"), + ("village_desert", "desert_village"), + ("village_plains", "plains_village"), + ("village_savanna", "savanna_village"), + ("village_snowy", "snowy_village"), + ("village_taiga", "taiga_village"), + ("jungle_temple", "jungle_temple"), + ("swamp_hut", "swamp_hut"), + ("trial_chambers", "trial_chambers"), + ("abandoned_camp", "abandoned_camp"), + ("ancient_city", "ancient_city"), + ("desert_pyramid", "desert_pyramid"), + ("mineshaft", "mineshaft"), + ("ocean_ruin_warm", "warm_ocean_ruins"), + ] { + assert_eq!( + decoration_sprite(&format!("minecraft:{name}")), + Some(format!("map/decorations/{asset}").as_str()), + "{name}" + ); + } + assert_eq!(decoration_sprite("minecraft:nothing"), None); + } + + #[test] + fn target_decorations_read_back_with_vanilla_rotation() { + let mut stack = ItemStack::new("minecraft:buried_treasure_map", 1); + stack.data_mut().map_id = Some(3); + stack.data_mut().other.push(( + "minecraft:map_decorations".into(), + target_decoration("minecraft:red_x", [120, 40, -300]), + )); + assert_eq!(map_id(&stack), Some(3)); + let found = static_decorations(&stack); + assert_eq!(found, vec![("map/decorations/red_x", 120.0, -300.0, 180.0)]); + // calculateRotation(180): (byte) (188 * 16 / 360) = 8. + assert_eq!(decoration_rotation(false, 0, 180.0), 8); + assert_eq!(decoration_rotation(false, 0, -90.0), 12); + assert_eq!(clamp_map_coordinate(-70.0), -128); + assert_eq!(clamp_map_coordinate(10.25), 21); + } +} diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 70ba4ab6a..738e3965b 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -89,8 +89,8 @@ impl merchant::MapMaker for GameMaps<'_> { self.made .borrow_mut() .push((id, at, map.zoom, map.decoration.clone())); + // The trade's own map item (woodland_mansion_map, ...) keeps its id. let mut out = stack; - out.item = std::sync::Arc::from("minecraft:filled_map"); let d = out.data_mut(); d.map_id = Some(id); d.other.push(( diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index 32f7512dc..81e2dab01 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -643,13 +643,7 @@ pub trait MapMaker { ) -> ItemStack; } /// An `exploration_map` function's settings. -pub struct ExplorationMap { - pub destination: String, - pub decoration: String, - pub zoom: u8, - pub search_radius: i32, - pub skip_existing_chunks: bool, -} +pub use horizon_world::loot::ExplorationMap; fn int_provider(v: &Value, random: &mut R) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -953,20 +947,7 @@ impl Trades { let Some(maps) = ctx.maps else { return Some((stack, 0)); }; - let map = ExplorationMap { - destination: m["destination"] - .as_str() - .unwrap_or("#minecraft:on_treasure_maps") - .trim_start_matches('#') - .to_owned(), - decoration: m["decoration"] - .as_str() - .unwrap_or("minecraft:mansion") - .to_owned(), - zoom: m["zoom"].as_u64().unwrap_or(2) as u8, - search_radius: m["search_radius"].as_i64().unwrap_or(50) as i32, - skip_existing_chunks: m["skip_existing_chunks"].as_bool().unwrap_or(true), - }; + let map = ExplorationMap::from_json(m); Some((maps.exploration_map(stack, &map, ctx.origin), 0)) } _ => Some((stack, 0)), diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 102a5a5b6..3ebcc71f5 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -301,6 +301,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 86d83f4ed..ea399937e 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -12,6 +12,81 @@ use std::{ sync::{Arc, OnceLock}, }; +/// The `custom_data` key holding an exploration map's search until the game +/// runs it (vanilla runs `ExplorationMapFunction` when the chest is unpacked, +/// on first open; here loot is rolled with the chunk). +const PENDING_MAP: &str = "horizon:exploration_map"; +const CUSTOM_DATA: &str = "minecraft:custom_data"; + +/// A generated chest's item, with its exploration map search kept in +/// `minecraft:custom_data` (which vanilla loads as is). +fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(s.item.as_str()), + count: s.count.max(0) as u32, + damage: s.damage.max(0) as u32, + extra: None, + }; + if let Some(map) = &s.exploration { + let search = Tag::compound([ + ("destination", Tag::String(map.destination.as_str().into())), + ("decoration", Tag::String(map.decoration.as_str().into())), + ("zoom", Tag::Byte(map.zoom as i8)), + ("search_radius", Tag::Int(map.search_radius)), + ( + "skip_existing_chunks", + Tag::Byte(i8::from(map.skip_existing_chunks)), + ), + ]); + item.data_mut() + .other + .push((CUSTOM_DATA.into(), Tag::compound([(PENDING_MAP, search)]))); + } + item +} + +/// The exploration map search an item still waits for, removed from it. +pub fn take_pending_map(item: &mut ItemStack) -> Option { + let data = item.extra.as_deref_mut()?; + let i = data + .other + .iter() + .position(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some())?; + let (_, mut custom) = data.other.remove(i); + let search = match &mut custom { + Tag::Compound(c) => c.remove(&JavaString::from(PENDING_MAP))?, + _ => return None, + }; + if matches!(&custom, Tag::Compound(c) if !c.is_empty()) { + data.other.insert(i, (CUSTOM_DATA.into(), custom)); + } + let text = |k: &str| match search.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let int = |k: &str| match search.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + _ => None, + }; + Some(horizon_world::loot::ExplorationMap { + destination: text("destination")?, + decoration: text("decoration")?, + zoom: int("zoom").unwrap_or(2).clamp(0, 4) as u8, + search_radius: int("search_radius").unwrap_or(50), + skip_existing_chunks: int("skip_existing_chunks").unwrap_or(1) != 0, + }) +} + +/// Whether an item still waits for its exploration map search. +pub fn has_pending_map(item: &ItemStack) -> bool { + item.data().is_some_and(|d| { + d.other + .iter() + .any(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some()) + }) +} + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { static LOOT: OnceLock>> = OnceLock::new(); @@ -64,12 +139,7 @@ pub fn block_entities( .zip(loot.fill(&table, seed, 27, Some(biome))) { *slot = stack.map(|s| { - let mut item = ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }; + let mut item = loot_item(&s); // An ominous bottle's level (the default, 0, is no component). if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); @@ -114,17 +184,71 @@ pub fn unpack_entity_loot( let slots: Vec> = loot .fill(&table, seed, 27, Some(biome)) .into_iter() - .map(|s| { - s.map(|s| ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }) - }) + .map(|s| s.map(|s| loot_item(&s))) .collect(); nbt.remove(&JavaString::from("LootTable")); nbt.remove(&JavaString::from("LootTableSeed")); nbt.insert("Items".into(), crate::save::encode_items(&slots)); nbt } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_world::loot::{ExplorationMap, LootStack}; + + #[test] + fn exploration_maps_wait_in_custom_data_until_searched() { + let mut stack = LootStack { + item: "minecraft:buried_treasure_map".into(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: true, + exploration: Some(Box::new(ExplorationMap::from_json(&serde_json::json!({ + "decoration": "minecraft:red_x", + "destination": "#minecraft:on_treasure_maps", + "skip_existing_chunks": false, + "zoom": 1 + })))), + ominous_amplifier: None, + }; + let mut item = loot_item(&stack); + assert!(has_pending_map(&item)); + // The rest of custom_data stays. + if let Some(Tag::Compound(c)) = item + .data_mut() + .other + .iter_mut() + .find(|(k, _)| k == CUSTOM_DATA) + .map(|(_, t)| t) + { + c.insert("note".into(), Tag::Int(7)); + } + let map = take_pending_map(&mut item).unwrap(); + assert_eq!( + map, + ExplorationMap { + destination: "minecraft:on_treasure_maps".into(), + decoration: "minecraft:red_x".into(), + zoom: 1, + search_radius: 50, + skip_existing_chunks: false, + } + ); + assert!(!has_pending_map(&item)); + assert!(take_pending_map(&mut item).is_none()); + let custom = &item.data().unwrap().other; + assert_eq!(custom.len(), 1); + assert_eq!(custom[0].1.get("note"), Some(&Tag::Int(7))); + // Only the search: the component goes away with it. + stack.item = "minecraft:abandoned_camp_map".into(); + let mut item = loot_item(&stack); + take_pending_map(&mut item).unwrap(); + assert!(item.data().unwrap().other.is_empty()); + // A plain item has nothing pending. + stack.exploration = None; + assert!(!has_pending_map(&loot_item(&stack))); + } +} diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 04716b99d..9b58cdd38 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -117,6 +117,13 @@ impl VanillaTerrain { let worker = worker.get_or_insert_with(|| self.generator.worker()); worker.find_closest_biome(search) } + /// `BiomeSource.getNoiseBiome` at quart positions, for places that may not + /// be generated yet (`MapItem.renderBiomePreviewMap`). + pub fn noise_biomes(&self, quarts: &[[i32; 3]]) -> Vec> { + let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner()); + let worker = worker.get_or_insert_with(|| self.generator.worker()); + worker.noise_biomes(quarts) + } /// `/place jigsaw`: `JigsawPlacement.addPieces`. pub fn jigsaw_pieces( &self, diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index fccfa4c77..b0a885ba2 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -26,9 +26,43 @@ pub struct LootStack { pub potion: Option, /// Set by exploration_map (the map_id component of a found map). pub map: bool, + /// The search an exploration_map function asked for, left to the game + /// (it needs the level's structures and maps). + pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, } +/// `ExplorationMapFunction`'s settings. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExplorationMap { + /// A structure tag, without `#`. + pub destination: String, + pub decoration: String, + pub zoom: u8, + pub search_radius: i32, + pub skip_existing_chunks: bool, +} +impl ExplorationMap { + /// The function's fields with their codec defaults (`DEFAULT_DESTINATION` + /// on_treasure_maps, `DEFAULT_DECORATION` mansion, zoom 2, radius 50, + /// skipping known structures). + pub fn from_json(f: &Value) -> Self { + Self { + destination: f["destination"] + .as_str() + .unwrap_or("#minecraft:on_treasure_maps") + .trim_start_matches('#') + .to_owned(), + decoration: f["decoration"] + .as_str() + .unwrap_or("minecraft:mansion") + .to_owned(), + zoom: f["zoom"].as_u64().unwrap_or(2) as u8, + search_radius: f["search_radius"].as_i64().unwrap_or(50) as i32, + skip_existing_chunks: f["skip_existing_chunks"].as_bool().unwrap_or(true), + } + } +} impl LootStack { fn new(item: &str) -> Self { Self { @@ -38,6 +72,7 @@ impl LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } @@ -1045,8 +1080,15 @@ impl Context<'_, R> { } } // ExplorationMapFunction needs an origin; with one, the map is - // taken as found (the structure search itself is not run). - "minecraft:exploration_map" => stack.map = self.biome.is_some(), + // taken as found here and the game runs the structure search + // (it drops the map when nothing is found, as the filtered + // map_id check after it would). + "minecraft:exploration_map" => { + stack.map = self.biome.is_some(); + if stack.map { + stack.exploration = Some(Box::new(ExplorationMap::from_json(f))); + } + } "minecraft:filtered" => { let pass = self.item_matches(&f["item_filter"], &stack); let branch = if pass { &f["on_pass"] } else { &f["on_fail"] }; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7adcb33b5..7e06f2013 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1403,6 +1403,8 @@ trait SeededPipeline: Send + Sync { worker: &mut WorkerState, search: &BiomeSearch<'_>, ) -> Option<(String, [i32; 3])>; + /// `BiomeSource.getNoiseBiome` at each quart position (unloaded chunks). + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec>; fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1562,6 +1564,21 @@ where } None } + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec> { + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + quarts + .iter() + .map(|&quart| { + resolver + .sample(&mut worker.carver_context, quart) + .ok() + .map(str::to_owned) + }) + .collect() + } fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1841,6 +1858,9 @@ impl GeneratorWorker { } /// `BiomeSource.findClosestBiome3d`: the first sampled position whose /// noise biome passes `allowed`, spiralling out from the origin. + pub fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec> { + self.pipeline.noise_biomes(&mut self.state, quarts) + } pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> { self.pipeline.find_closest_biome(&mut self.state, search) } From 4d7ca0fc937da36c8246c3649ff7237058126eb6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:01:05 +0200 Subject: [PATCH 23/23] Horizon menus: delete singleplayer worlds The Horizon-style Singleplayer page had no way to delete a save. A Delete (danger) button now shows beside Play when a world is selected and opens a confirmation page in the design language: the world's name and last-played date in a notice led by the danger dot, "It will be lost forever. This can't be undone.", then Delete world / Cancel. After deleting, the list refreshes and the selection moves to the world that took the deleted row (or the new last one). A failure shows a Horizon error page whose Back returns to the question. Both menu styles share world_management::delete, now a port of LevelStorageAccess.deleteLevel: it takes the world's session lock first, so a world open in this or another instance is refused, deletes everything but the lock (retrying five times, 500 ms apart), then releases and removes the lock and the folder. Only a single plain folder name directly in saves is accepted, and links inside the world are removed, never followed. Leaving a world now flushes the region writer and releases the session lock (vanilla closes the storage access), so the world just played can be deleted from the title. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 283 +++++++++++++++--- crates/horizon-client/src/game.rs | 4 + crates/horizon-client/src/title.rs | 36 ++- crates/horizon-client/src/title/tests.rs | 28 ++ .../src/title/world_management.rs | 45 ++- 5 files changed, 349 insertions(+), 47 deletions(-) diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index b4a225030..64a27d5ac 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -24,6 +24,8 @@ const BACK: u64 = id("front.back", 0); const PLAY_WORLD: u64 = id("worlds.play", 0); const CREATE: u64 = id("worlds.create", 0); const WORLD: u64 = id("worlds.row", 0); +const DELETE_WORLD: u64 = id("worlds.delete", 0); +const CONFIRM_DELETE: u64 = id("delete.confirm", 0); const NAME: u64 = id("create.name", 0); const SEED: u64 = id("create.seed", 0); const MODE: u64 = id("create.mode", 0); @@ -91,15 +93,21 @@ fn page(mode: &Mode) -> usize { } } const PAGES: [&str; 4] = ["Home", "Singleplayer", "Multiplayer", "Options"]; +/// World editing and backups still use the classic screens, and so do their +/// errors; the rest of the singleplayer flow has Horizon pages. +fn classic(mode: &Mode) -> bool { + match mode { + Mode::Edit { .. } | Mode::Backup { .. } => true, + Mode::Error { return_to, .. } => classic(return_to), + _ => false, + } +} impl Title { /// Horizon's layout for every title mode. `backdrop` is how much of the /// live backdrop is visible (0 shows the plain cold background). pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) { - if matches!( - self.mode, - Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } - ) { + if classic(&self.mode) { self.draw(ui.atlas, ui.batch, ui.cursor); return; } @@ -149,11 +157,15 @@ impl Title { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); create_page(ui, x, w, name, seed, *creative, *focus, caret); } + Mode::Delete { world } => delete_page(ui, x, w, world), + Mode::Error { message, .. } => error_page(ui, x, w, message), Mode::Multiplayer(screen) => { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); multiplayer_page(ui, x, w, screen, caret); } - _ => unreachable!("World-management screens use the classic layout"), + Mode::Edit { .. } | Mode::Backup { .. } => { + unreachable!("World editing uses the classic layout") + } } } ui.opacity = 1.0; @@ -307,10 +319,7 @@ impl Title { if self.skip_opening() { return Action::None; } - if matches!( - self.mode, - Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } - ) { + if classic(&self.mode) { return self.click(x, y, (batch.width, batch.height)).0; } let hit = { @@ -377,6 +386,11 @@ impl Title { focus: 0, } } + DELETE_WORLD => { + if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() { + self.mode = Mode::Delete { world }; + } + } h if (WORLD..WORLD + 10_000).contains(&h) => { let i = (h - WORLD) as usize; if *selected == Some(i) { @@ -398,7 +412,25 @@ impl Title { MAKE => return self.create_action(), _ => {} }, - Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } => {} + Mode::Delete { .. } => match hit { + // The selection stays in place: on the world that moved up + // into the deleted one's row, or the new last one. + CONFIRM_DELETE => { + if let Some(row) = self.confirm_delete() + && let Mode::Select { worlds, selected } = &mut self.mode + { + *selected = worlds.len().checked_sub(1).map(|last| row.min(last)); + } + } + BACK => self.escape(), + _ => {} + }, + Mode::Error { return_to, .. } => { + if hit == BACK { + self.mode = *return_to.clone(); + } + } + Mode::Edit { .. } | Mode::Backup { .. } => {} Mode::Multiplayer(screen) => { let id = match hit { JOIN => Some(40), @@ -564,15 +596,14 @@ fn worlds_page( n => format!("{n} worlds in the saves folder."), }; let mut y = header(ui, x, "Singleplayer", &count); - actions_right( - ui, - x + w, - y - 24.0 - 58.0, - &[ - (PLAY_WORLD, "Play", Kind::Primary, selected.is_some()), - (CREATE, "Create world", Kind::Secondary, true), - ], - ); + let mut items = vec![ + (PLAY_WORLD, "Play", Kind::Primary, selected.is_some()), + (CREATE, "Create world", Kind::Secondary, true), + ]; + if selected.is_some() { + items.push((DELETE_WORLD, "Delete", Kind::Danger, true)); + } + actions_right(ui, x + w, y - 24.0 - 58.0, &items); ui.divider(x, y, w); if worlds.is_empty() { empty(ui, x, y, "A blank map.", "Create a world to begin."); @@ -608,6 +639,100 @@ fn worlds_page( } } +/// The launcher's notice: a plate led by a danger dot, the first line in +/// medium type, wrapped lines under it. Returns its height. +fn notice(ui: &mut Ui, x: f32, y: f32, w: f32, title: Option<&str>, text: &str) -> f32 { + let lines = wrap(ui, text, w - 48.0); + let title_h = if title.is_some() { 26.0 } else { 0.0 }; + let h = 32.0 + title_h + lines.len() as f32 * 19.0; + ui.rounded(x, y, w, h, t::RADIUS_PLATE, color::RAISED); + ui.rounded(x + 16.0, y + 22.0, 6.0, 6.0, 3.0, color::DANGER); + let mut ty = y + 16.0; + if let Some(title) = title { + let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 48.0); + ui.text_line( + Face::Medium, + t::LARGE + 2.0, + 19.0, + x + 32.0, + ty, + color::TEXT, + &title, + ); + ty += title_h; + } + for (i, line) in lines.iter().enumerate() { + let tint = if title.is_some() { + color::MUTED + } else { + color::TEXT + }; + ui.text_line( + Face::Regular, + BODY, + 19.0, + x + 32.0, + ty + i as f32 * 19.0, + tint, + line, + ); + } + h +} + +/// `ConfirmScreen` for a world: what goes, that it can't come back, then +/// Delete (danger) and Cancel under it. +fn delete_page(ui: &mut Ui, x: f32, w: f32, world: &crate::title::WorldEntry) { + let mut y = header( + ui, + x, + "Delete this world?", + "It will be lost forever. This can't be undone.", + ); + ui.divider(x, y, w); + y += 16.0; + let secs = world + .modified + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_secs()); + let text = format!( + "Last played {}. The folder saves/{} and everything built in it will be removed.", + crate::title::date_label(secs), + world.folder + ); + y += notice(ui, x, y, w, Some(&world.name), &text) + 16.0; + let dw = ui.button_width("Delete world", false); + ui.button( + CONFIRM_DELETE, + [x, y, dw, CONTROL], + "Delete world", + Kind::Danger, + true, + ); + let cw = ui.button_width("Cancel", false); + ui.button( + BACK, + [x + dw + 8.0, y, cw, CONTROL], + "Cancel", + Kind::Ghost, + true, + ); +} + +fn error_page(ui: &mut Ui, x: f32, w: f32, message: &str) { + let mut y = header( + ui, + x, + "Something went wrong", + "Horizon couldn't finish that.", + ); + ui.divider(x, y, w); + y += 16.0; + y += notice(ui, x, y, w, None, message) + 16.0; + let bw = ui.button_width("Back", false); + ui.button(BACK, [x, y, bw, CONTROL], "Back", Kind::Secondary, true); +} + #[allow(clippy::too_many_arguments)] fn create_page( ui: &mut Ui, @@ -839,23 +964,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { ); ui.divider(x, y, w); y += 16.0; - // The launcher's error note: a danger dot beside the message. - let lines = wrap(ui, reason, w - 40.0); - let box_h = 24.0 + lines.len() as f32 * 19.0; - ui.rounded(x, y, w, box_h, t::RADIUS_PLATE, color::RAISED); - ui.rounded(x + 12.0, y + 18.0, 6.0, 6.0, 3.0, color::DANGER); - for (i, line) in lines.iter().enumerate() { - ui.text_line( - Face::Regular, - BODY, - 19.0, - x + 28.0, - y + 12.0 + i as f32 * 19.0, - color::TEXT, - line, - ); - } - y += box_h + 16.0; + y += notice(ui, x, y, w, None, reason) + 16.0; if let Some(r) = retry { // Auto-reconnect's countdown, with a way out. let text = r.text(std::time::Instant::now()); @@ -1006,3 +1115,105 @@ pub mod pause { } } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_world::nbt::Tag; + + fn world(saves: &std::path::Path, folder: &str, last_played: i64) { + crate::save::write_dat( + &saves.join(folder).join("level.dat"), + Tag::compound([( + "Data", + Tag::compound([ + ("LevelName", Tag::String(folder.into())), + ("GameType", Tag::Int(0)), + ("LastPlayed", Tag::Long(last_played)), + ("WorldGenSettings", Tag::compound([("seed", Tag::Long(1))])), + ]), + )]), + ) + .unwrap(); + } + /// Clicks the middle of button `bid` as the game would; panics if the + /// page does not show it. + fn press(title: &mut Title, atlas: &HudAtlas, bid: u64) -> Action { + let mut batch = HudBatch::new([1280, 720]); + let (rect, density) = { + let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0)); + title.draw_horizon(&mut ui, 1.0); + let hit = ui.hits.iter().rev().find(|h| h.id == bid); + (hit.expect("button on the page").rect, ui.density) + }; + let k = density / batch.scale; + let (x, y) = ((rect[0] + rect[2]) / 2.0 * k, (rect[1] + rect[3]) / 2.0 * k); + title.click_horizon(atlas, &mut batch, x, y) + } + fn shows(title: &Title, atlas: &HudAtlas, bid: u64) -> bool { + let mut batch = HudBatch::new([1280, 720]); + let mut ui = Ui::dry(atlas, &mut batch, (0.0, 0.0)); + title.draw_horizon(&mut ui, 1.0); + ui.hits.iter().any(|h| h.id == bid) + } + fn selected(title: &Title) -> Option { + match &title.mode { + Mode::Select { worlds, selected } => selected.map(|i| worlds[i].folder.clone()), + _ => panic!("not on the world list"), + } + } + + #[test] + fn horizon_world_delete_confirms_and_keeps_the_selection_in_place() { + let atlas = + HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let root = + std::env::temp_dir().join(format!("horizon-front-delete-{}", std::process::id())); + let saves = root.join("saves"); + for (i, folder) in ["C", "B", "A"].iter().enumerate() { + world(&saves, folder, 1000 * (i as i64 + 1)); + } + let mut title = Title::new(saves.clone()); + title.mode = Mode::Select { + worlds: list_worlds(&saves), + selected: None, + }; + assert!(!shows(&title, &atlas, DELETE_WORLD)); + press(&mut title, &atlas, WORLD + 1); + assert_eq!(selected(&title).as_deref(), Some("B")); + + // Cancel leaves the world and its selection. + press(&mut title, &atlas, DELETE_WORLD); + assert!(matches!(&title.mode, Mode::Delete { world } if world.folder == "B")); + press(&mut title, &atlas, BACK); + assert_eq!(selected(&title).as_deref(), Some("B")); + assert!(saves.join("B/level.dat").is_file()); + + // Deleting selects the world that moved up into the row. + press(&mut title, &atlas, DELETE_WORLD); + press(&mut title, &atlas, CONFIRM_DELETE); + assert!(!saves.join("B").exists()); + assert_eq!(selected(&title).as_deref(), Some("C")); + + // A world open elsewhere is refused on a Horizon page; Back returns + // to the question. + let open = crate::save::SessionLock::acquire(&saves.join("C")).unwrap(); + press(&mut title, &atlas, DELETE_WORLD); + press(&mut title, &atlas, CONFIRM_DELETE); + assert!(matches!(title.mode, Mode::Error { .. })); + assert!(!classic(&title.mode)); + press(&mut title, &atlas, BACK); + assert!(matches!(title.mode, Mode::Delete { .. })); + drop(open); + + // The last row: the selection moves to the new last world. + press(&mut title, &atlas, CONFIRM_DELETE); + assert_eq!(selected(&title).as_deref(), Some("A")); + press(&mut title, &atlas, DELETE_WORLD); + press(&mut title, &atlas, CONFIRM_DELETE); + assert!( + matches!(&title.mode, Mode::Select { worlds, selected: None } if worlds.is_empty()) + ); + let _ = std::fs::remove_dir_all(root); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7f0221119..2b9a79f2b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6024,6 +6024,10 @@ impl Game<'_> { self.stats.custom("leave_game", 1); self.save_game()?; self.lan_close(false); + // Closing the level storage: once the last writes are on disk the + // session lock goes, so the title can delete or back up this world. + self.save.flush(); + self.session_lock = None; horizon_client::crash::clear_detail("World"); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index c526d7905..762348d20 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -245,6 +245,26 @@ impl Title { self.mode = Mode::Select { worlds, selected }; *self.recent.borrow_mut() = None; } + /// Deletes the world `Mode::Delete` asks about and goes back to the + /// refreshed list; a failure (the world is open elsewhere, say) shows the + /// error instead and leaves the world. Returns the deleted world's row in + /// the list before it went, for a layout that moves the selection there. + pub(crate) fn confirm_delete(&mut self) -> Option { + let Mode::Delete { world } = &self.mode else { + return None; + }; + let folder = world.folder.clone(); + let row = list_worlds(&self.saves) + .iter() + .position(|w| w.folder == folder); + if let Err(error) = world_management::delete(&self.saves, &folder) { + self.failed(error); + return None; + } + self.return_to_list(None); + self.icons.borrow_mut().clear(); + row + } fn cancel_create(&mut self) { if self.create_return_to_main { self.mode = Mode::Main; @@ -1176,16 +1196,12 @@ impl Title { && (x - (w / 2.0).floor()).abs() < 100.0; Action::None } - (Mode::Delete { world }, Some(id @ (37 | 38))) => { - let folder = world.folder.clone(); - if id == 37 - && let Err(error) = world_management::delete(&self.saves, &folder) - { - self.failed(error); - return Action::None; - } - self.return_to_list(Some(&folder)); - self.icons.borrow_mut().clear(); + (Mode::Delete { .. }, Some(37)) => { + self.confirm_delete(); + Action::None + } + (Mode::Delete { .. }, Some(38)) => { + self.escape(); Action::None } (Mode::Error { return_to, .. }, Some(39)) => { diff --git a/crates/horizon-client/src/title/tests.rs b/crates/horizon-client/src/title/tests.rs index c0f515f1d..15d0f4d5b 100644 --- a/crates/horizon-client/src/title/tests.rs +++ b/crates/horizon-client/src/title/tests.rs @@ -533,3 +533,31 @@ fn failed_world_operation_back_button_plays_the_click_sound() { assert_eq!(f.click_with_sound("Back"), (Action::None, true)); assert!(matches!(f.title.mode, Mode::Edit { .. })); } + +#[test] +fn delete_refuses_an_open_world_then_removes_it_with_its_lock() { + let f = Fixture::new(); + f.world("World", "World"); + let open = crate::save::SessionLock::acquire(&f.title.saves.join("World")).unwrap(); + assert!(world_management::delete(&f.title.saves, "World").is_err()); + assert!(f.title.saves.join("World/level.dat").is_file()); + drop(open); + world_management::delete(&f.title.saves, "World").unwrap(); + assert!(!f.title.saves.join("World").exists()); +} + +#[cfg(unix)] +#[test] +fn delete_removes_links_without_following_them() { + let f = Fixture::new(); + f.world("World", "World"); + let outside = f.root.join("outside"); + fs::create_dir_all(&outside).unwrap(); + fs::write(outside.join("keep.txt"), "keep").unwrap(); + std::os::unix::fs::symlink(&outside, f.title.saves.join("World/link")).unwrap(); + std::os::unix::fs::symlink(&outside, f.title.saves.join("Linked")).unwrap(); + assert!(world_management::delete(&f.title.saves, "Linked").is_err()); + world_management::delete(&f.title.saves, "World").unwrap(); + assert!(!f.title.saves.join("World").exists()); + assert!(outside.join("keep.txt").is_file()); +} diff --git a/crates/horizon-client/src/title/world_management.rs b/crates/horizon-client/src/title/world_management.rs index 38dcb19e6..5884a1d88 100644 --- a/crates/horizon-client/src/title/world_management.rs +++ b/crates/horizon-client/src/title/world_management.rs @@ -38,8 +38,51 @@ pub(super) fn reset_icon(saves: &Path, folder: &str) -> crate::Result<()> { Ok(()) } +/// `LevelStorageAccess.deleteLevel`, shared by both menu styles. The world's +/// session lock is taken first, so a world open in this or another instance is +/// refused rather than pulled from under it; everything but the lock goes, +/// then the lock is released and removed with the folder. A failed pass (a +/// file briefly held by a virus scanner, say) is retried up to five times, +/// half a second apart, as vanilla does. Only the named folder directly in +/// `saves` is touched: symbolic links inside it are removed, never followed. pub(super) fn delete(saves: &Path, folder: &str) -> crate::Result<()> { - fs::remove_dir_all(world_path(saves, folder)?)?; + let world = world_path(saves, folder)?; + let lock = crate::save::SessionLock::acquire(&world)?; + let lock_path = world.join("session.lock"); + log::info!("Deleting level {folder}"); + for attempt in 1.. { + match remove_contents(&world, &lock_path) { + Ok(()) => break, + Err(e) if attempt >= 5 => return Err(e.into()), + Err(e) => { + log::warn!("Failed to delete {}: {e}", world.display()); + std::thread::sleep(std::time::Duration::from_millis(500)); + } + } + } + drop(lock); + match fs::remove_file(&lock_path) { + Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e.into()), + _ => {} + } + fs::remove_dir(&world)?; + Ok(()) +} + +fn remove_contents(world: &Path, lock: &Path) -> io::Result<()> { + for entry in fs::read_dir(world)? { + let entry = entry?; + let path = entry.path(); + if path == lock { + continue; + } + // `file_type` does not follow links, and `remove_dir_all` never does. + if entry.file_type()?.is_dir() { + fs::remove_dir_all(&path)?; + } else { + fs::remove_file(&path)?; + } + } Ok(()) }