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