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()