diff --git a/crates/horizon-client/examples/probe/entity_anim_fixture.rs b/crates/horizon-client/examples/probe/entity_anim_fixture.rs index 0a2e2951f..0a3df9e0d 100644 --- a/crates/horizon-client/examples/probe/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/probe/entity_anim_fixture.rs @@ -9,7 +9,7 @@ use horizon_client::mesher::Vertex; use horizon_client::mobs::{ Mob, MobData, MobTypes, Part, Species, allay, anim::{self, Poses, State}, - aquatic, body_anim as b_anim, equine, guardian, + aquatic, bat, body_anim as b_anim, equine, guardian, keyframes::AnimationState, render, shulker, sniffer, species, tame, }; @@ -108,6 +108,22 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) { let flag = |k: &str| case[k].as_bool().unwrap_or(false); let num = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32; match species { + Species::Bat => { + mob.extra.flag = flag("isResting"); + mob.anim.states[0].started = case["flyAnimationState"].as_f64().map(|v| v as f32); + mob.anim.states[1].started = case["restAnimationState"].as_f64().map(|v| v as f32); + if let Some(ticks) = case["@batTicks"].as_array() { + for (i, flags) in ticks.iter().enumerate() { + mob.age = i as u32 + 1; + bat::set_resting(mob, flags.as_i64().unwrap_or(0) & 1 != 0); + if flag("@batInFrame") { + bat::tick(mob); + } else { + bat::setup_animation_states(mob); + } + } + } + } Species::Sheep => mob.extra.anim_ticks = num("eatTick") as i32, Species::Guardian | Species::ElderGuardian => { mob.anim.v[guardian::TAIL] = num("tailAnimation"); @@ -456,14 +472,6 @@ pub fn main() -> horizon_client::Result<()> { roll_amount: num("rollAmount"), }, ), - Species::Bat => b_anim::bat( - p, - s, - flag("isResting"), - &started("flyAnimationState"), - &started("restAnimationState"), - &animations, - ), Species::Armadillo => b_anim::armadillo( p, s, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 47be8e1e3..ec243e5fe 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -194,6 +194,13 @@ fn mob_meta( let e = &m.extra; let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}")); match kind { + // Bat.DATA_ID_FLAGS: resting in bit 0, flying by default. + "minecraft:bat" => { + if e.flag { + meta.push((16, serializer::BYTE, Value::Byte(1))); + } + defaults.push((16, serializer::BYTE, Value::Byte(0))); + } // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 when sheared. "minecraft:sheep" => { let value = (e.color & 15) | if e.sheared { 16 } else { 0 }; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a951d299a..d48452b4d 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3492,6 +3492,9 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Rabbit { horizon_client::mobs::rabbit::post_tick(m); } + if m.species() == horizon_client::mobs::Species::Bat { + horizon_client::mobs::bat::setup_animation_states(m); + } } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index fbfc5a4fb..5ea772307 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,7 +4,7 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, tame}; +use horizon_client::mobs::{Mob, Species, bat, tame}; use horizon_protocol::entity_data::Value; use horizon_protocol::registry::Builtin; @@ -46,6 +46,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) { _ => {} } match (species, *index, value) { + // Bat.DATA_ID_FLAGS: resting in bit 0. + (Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0), // Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared. (Species::Sheep, 18, Value::Byte(wool)) => { m.extra.color = (*wool & 15) as u8; @@ -126,6 +128,10 @@ pub(super) fn client_defaults(m: &mut Mob) { if matches!(m.species(), Species::Wolf | Species::Cat) { m.extra.color = tame::RED; } + if m.species() == Species::Bat { + // Bat's constructor sets resting only on the server; the data default is 0. + bat::set_resting(m, false); + } } #[cfg(test)] @@ -174,6 +180,69 @@ mod tests { assert!(!calf.is_baby()); } + #[test] + fn bat_flags_select_continuous_client_clocks_without_changing_motion() { + use horizon_client::mobs::{MobTypes, anim, keyframes::Animation}; + use horizon_core::geometry::Vec3; + use serde_json::json; + use std::{collections::HashMap, fs, sync::Arc}; + + // Original minimal resources keep this regression runnable without vanilla data. + let root = + std::env::temp_dir().join(format!("horizon-bat-animation-{}", std::process::id())); + fs::create_dir(&root).unwrap(); + fs::write(root.join("entity-types.json"), r#"{"minecraft:bat": {}}"#).unwrap(); + fs::write( + root.join("entity-models.json"), + r#"{"minecraft:bat#main": {"children": {"right_wing": {}, "head": {}}}}"#, + ) + .unwrap(); + let mut types = MobTypes::load(&root).unwrap(); + fs::remove_dir_all(root).unwrap(); + let position = Vec3::new(1.0, 2.25, 3.0); + let velocity = Vec3::new(0.2, 0.3, 0.4); + let mut m = Mob::new( + 1, + Arc::new(types.types.remove("minecraft:bat").unwrap()), + position, + 0.0, + ); + assert!(bat::resting(&m)); + client_defaults(&mut m); + assert!(!bat::resting(&m)); + m.velocity = velocity; + m.age = 1; + bat::setup_animation_states(&mut m); + m.age = 4; + apply(&mut m, &[(16, s::BYTE, Value::Byte(2))]); + bat::setup_animation_states(&mut m); + assert_eq!(m.anim.states[0].started, Some(1.0)); + + let curve = Animation::parse(&json!({"length": 1, "looping": true, + "bones": {"right_wing": [{"target": "rotation", "keyframes": + [[0,[0,0,0],[0,0,0],"linear"],[1,[0,1,0],[0,1,0],"linear"]]}]}})); + let animations = HashMap::from([("BatAnimation.BAT_FLYING".into(), curve)]); + let wing = |partial| { + let mut poses = anim::Poses::new(&m.kind.model); + anim::setup(&m, &anim::state(&m, partial), &mut poses, &animations); + poses.get("right_wing")[4] + }; + assert!(wing(0.5) > wing(0.0)); + + m.age = 5; + apply(&mut m, &[(16, s::BYTE, Value::Byte(3))]); + bat::setup_animation_states(&mut m); + assert!(bat::resting(&m)); + assert_eq!(m.anim.states[0].started, None); + assert_eq!(m.anim.states[1].started, Some(5.0)); + m.age = 7; + apply(&mut m, &[(16, s::BYTE, Value::Byte(0))]); + bat::setup_animation_states(&mut m); + assert_eq!(m.anim.states[0].started, Some(7.0)); + assert_eq!(m.anim.states[1].started, None); + assert_eq!((m.position, m.velocity), (position, velocity)); + } + #[test] fn a_wolf_takes_its_owner_flags_and_collar() { let Some(mut m) = mob("minecraft:wolf") else { diff --git a/crates/horizon-client/src/mobs/bat.rs b/crates/horizon-client/src/mobs/bat.rs index 9f38e9e60..ca5efa4a2 100644 --- a/crates/horizon-client/src/mobs/bat.rs +++ b/crates/horizon-client/src/mobs/bat.rs @@ -132,6 +132,10 @@ pub fn tick(m: &mut Mob) { } else { m.velocity.y *= 0.6; } + setup_animation_states(m); +} +/// `Bat.setupAnimationStates`: client visuals, without changing server motion. +pub fn setup_animation_states(m: &mut Mob) { let age = m.age as f32; if resting(m) { m.anim.states[0].stop(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java index dc5f8c8df..9f7a63a67 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java @@ -223,7 +223,9 @@ public final class VanillaEntityAnimOracle { } /** Render-state values vanilla derives from entity state; the case gives the entity-side input. */ - private static void hooks(EntityRenderState state, JsonObject kase) { + private static void hooks(EntityRenderState state, JsonObject kase) throws Exception { + if (state instanceof net.minecraft.client.renderer.entity.state.BatRenderState bat && kase.has("@batTicks")) + batHistory(bat, kase.getAsJsonArray("@batTicks")); if (state instanceof net.minecraft.client.renderer.entity.state.SheepRenderState sheep && kase.has("eatTick")) { // Sheep.getHeadEatPositionScale / getHeadEatAngleScale at partial tick 0. int t = kase.get("eatTick").getAsInt(); @@ -242,6 +244,34 @@ public final class VanillaEntityAnimOracle { phantom.flapTime = kase.get("flapOffset").getAsFloat() + phantom.ageInTicks; } + /** Only the server's flags are supplied; the shipped Bat starts/stops its own clocks. */ + private static final class AnimationBat extends net.minecraft.world.entity.ambient.Bat { + int flags; + AnimationBat() { super(null, null); } + @Override public boolean isResting() { return (flags & 1) != 0; } + } + + private static void batHistory(net.minecraft.client.renderer.entity.state.BatRenderState state, JsonArray ticks) throws Exception { + // Allocate without a world, as the other controlled entity oracles do. + var allocator = Class.forName("sun.misc.Unsafe"); + var field = allocator.getDeclaredField("theUnsafe"); + field.setAccessible(true); + var bat = (AnimationBat) allocator.getMethod("allocateInstance", Class.class).invoke(field.get(null), AnimationBat.class); + var type = net.minecraft.world.entity.ambient.Bat.class; + type.getField("flyAnimationState").set(bat, new net.minecraft.world.entity.AnimationState()); + type.getField("restAnimationState").set(bat, new net.minecraft.world.entity.AnimationState()); + var setup = type.getDeclaredMethod("setupAnimationStates"); + setup.setAccessible(true); + for (var flags : ticks) { + bat.tickCount++; + bat.flags = flags.getAsInt(); + setup.invoke(bat); + } + state.isResting = bat.isResting(); + state.flyAnimationState.copyFrom(bat.flyAnimationState); + state.restAnimationState.copyFrom(bat.restAnimationState); + } + public static void main(String[] args) throws Exception { SharedConstants.tryDetectVersion(); Bootstrap.bootStrap(); diff --git a/tools/test_entity_model_parity.py b/tools/test_entity_model_parity.py index 0cfc509f3..11d3f7cbc 100644 --- a/tools/test_entity_model_parity.py +++ b/tools/test_entity_model_parity.py @@ -276,6 +276,14 @@ def species_cases(layer, base_cases): for extra in SPECIES.get(name, []): for index in (2, 3, 6): yield {**base_cases[index], **extra} + if name == 'bat': + # Entity clocks, rather than injected render clocks: flight, rest, transitions and + # unrelated flag bits. Exercise the in-frame tick and server-client visual update. + for flags in ([0] * 4, [1] * 4, [0, 0, 1, 1, 0, 0], [1, 1, 0, 0, 1, 1], [2, 3, 2, 2]): + for in_frame in (False, True): + for partial in (0.0, 0.5): + yield {**base_cases[0], 'ageInTicks': len(flags) + partial, + '@batTicks': flags, '@batInFrame': in_frame} def compare_vertices(v, r, args, stats):