Verify entity model animation against vanilla and fix what differed

A new Java oracle bakes every vanilla model layer, builds the model's own render state and runs the real setupAnim; tools/test_entity_model_parity.py replays the same states through Horizon's animation code and compares every part pose, visibility and the baked polygon sums (about 3700 cases over 125 layers). Fixes the harness found: model sine and cosine now use vanilla's quantised table, the creeper's swapped leg bindings, humanoid arm poses in vanilla order (held items no longer tilt mob arms, bows pose both arms last, crossbow charge, riding, crouching), swing weapon down, piglin ears and dancing, illager hats, arms and bow pose, zombified piglin ears, baby donkey head and legs, hoglin baby head, ravager neck, vex charging arms, feline sitting and lying poses including babies, camel and zombie/skeleton horse baby models, and new ports of the goat, polar bear, panda, llama, turtle, strider, snow golem, silverfish, endermite, parrot, bee, bat, armadillo, axolotl, frog, rabbit and fox models. Hidden parts are now an explicit flag instead of a zero scale, and skipDraw is supported.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 03:44:46 +02:00
parent 2b618b1dfe
commit e0541ece83
26 changed files with 2608 additions and 354 deletions
@@ -0,0 +1,433 @@
//! Replays the render states of the vanilla entity-animation oracle through
//! Horizon's `mobs::anim::setup` and writes every part's pose.
//!
//! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \
//! RESOURCES VANILLA.jsonl OUT.jsonl
use horizon_client::mobs::{
Mob, MobData, MobTypes, Part, Species, allay,
anim::{self, Poses, State},
aquatic, body_anim as b_anim, equine, guardian,
keyframes::AnimationState,
shulker, species, tame,
};
use horizon_core::geometry::Vec3;
use serde_json::{Value, json};
use std::{collections::BTreeMap, fs, path::PathBuf, sync::Arc};
fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap<String, Value>) {
let p = poses.pose(part);
let mut polys = 0;
let mut sum = 0.0f64;
for polygon in &part.polygons {
polys += 1;
for v in polygon.vertices {
sum += f64::from(v[0])
+ 2.0 * f64::from(v[1])
+ 3.0 * f64::from(v[2])
+ 5.0 * f64::from(v[3])
+ 7.0 * f64::from(v[4]);
}
}
let visible = !poses.is_hidden(part) && !poses.skips(part);
let mut row: Vec<Value> = p.iter().map(|&x| json!(x)).collect();
row.push(json!(u8::from(visible)));
row.push(json!(polys));
row.push(json!(sum));
out.insert(path.to_owned(), Value::Array(row));
for c in &part.children {
let child = if path.is_empty() {
c.name.clone()
} else {
format!("{path}/{}", c.name)
};
walk(c, &child, poses, out);
}
}
/// The entity-side values behind the render-state fields the case sets, for
/// the species whose Horizon animation reads them from the `Mob`.
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::Sheep => mob.extra.anim_ticks = num("eatTick") as i32,
Species::Guardian | Species::ElderGuardian => {
mob.anim.v[guardian::TAIL] = num("tailAnimation");
mob.anim.vo[guardian::TAIL] = num("tailAnimation");
mob.anim.v[guardian::SPIKES] = num("spikesAnimation");
mob.anim.vo[guardian::SPIKES] = num("spikesAnimation");
}
Species::Shulker => {
mob.anim.v[shulker::PEEK] = num("peekAmount");
mob.anim.vo[shulker::PEEK] = num("peekAmount");
}
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
| Species::Giant
| Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::WitherSkeleton
| Species::Parched => {
mob.ai.aggressive = flag("isAggressive");
mob.extra.crouching = flag("isCrouching");
mob.extra.passenger = flag("isPassenger");
if flag("isHoldingBow") {
mob.extra.main_hand = Some("minecraft:bow".into());
}
}
Species::IronGolem => {
mob.extra.anim_ticks = num("attackTicksRemaining") as i32;
mob.extra.counter = num("offerFlowerTick") as i32;
}
Species::Hoglin | Species::Zoglin => {
mob.extra.anim_ticks = num("attackAnimationRemainingTicks") as i32;
}
Species::Ravager => {
mob.extra.counter2 = num("stunnedTicksRemaining") as i32;
mob.extra.counter = num("attackTicksRemaining") as i32;
let roar = num("roarAnimation");
if roar > 0.0 {
mob.extra.anim_ticks = (20.0 - roar * 20.0) as i32;
}
}
Species::Vex => mob.extra.flag = flag("isCharging"),
Species::Squid | Species::GlowSquid => {
mob.anim.v[aquatic::TENTACLE_ANGLE] = num("tentacleAngle");
mob.anim.vo[aquatic::TENTACLE_ANGLE] = num("tentacleAngle");
}
Species::Dolphin => {
if flag("isMoving") {
mob.velocity.x = 0.1;
}
}
Species::Cod | Species::Salmon | Species::TropicalFish | Species::Tadpole => {
mob.fluids.in_water = flag("isInWater");
}
Species::Allay => {
mob.extra.flag = flag("isDancing");
mob.extra.ints[4] = if flag("isSpinning") { 10 } else { 20 };
mob.anim.v[allay::SPIN] = num("spinningProgress") * 15.0;
mob.anim.vo[allay::SPIN] = num("spinningProgress") * 15.0;
mob.anim.v[allay::HOLD] = num("holdingAnimationProgress") * 5.0;
mob.anim.vo[allay::HOLD] = num("holdingAnimationProgress") * 5.0;
}
Species::Horse
| Species::Donkey
| Species::Mule
| Species::ZombieHorse
| Species::SkeletonHorse => {
for (slot, key) in [
(equine::EAT, "eatAnimation"),
(equine::STAND, "standAnimation"),
(equine::MOUTH, "feedingAnimation"),
] {
mob.anim.v[slot] = num(key);
mob.anim.vo[slot] = num(key);
}
mob.fluids.in_water = flag("isInWater");
mob.extra.chested = flag("hasChest");
}
Species::Camel => {
for (i, k) in [
"sitAnimationState",
"sitPoseAnimationState",
"sitUpAnimationState",
"idleAnimationState",
"dashAnimationState",
]
.into_iter()
.enumerate()
{
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
}
mob.extra.anim_ticks = num("jumpCooldown") as i32;
}
Species::Chicken => {
mob.anim.flap = num("flap");
mob.anim.flap_o = num("flap");
mob.anim.flap_speed = num("flapSpeed");
mob.anim.flap_speed_o = num("flapSpeed");
}
Species::Wolf => {
mob.extra.sitting = flag("isSitting");
mob.extra.anger = if flag("isAngry") { 100 } else { 0 };
mob.anim.v[tame::SHAKE] = num("shakeAnim");
mob.anim.vo[tame::SHAKE] = num("shakeAnim");
mob.anim.v[tame::INTEREST] = num("interest");
mob.anim.vo[tame::INTEREST] = num("interest");
}
Species::Creaking => {
mob.extra.flag2 = !flag("canMove");
for (i, k) in [
"attackAnimationState",
"invulnerabilityAnimationState",
"deathAnimationState",
]
.into_iter()
.enumerate()
{
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
}
}
Species::Witch if flag("isHoldingItem") => {
mob.extra.main_hand = Some("minecraft:potion".into());
}
_ => {}
}
}
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let root = PathBuf::from(&args[0]);
let types = MobTypes::load(&root)?;
let animations = MobData::load_animations(&root);
let mut out = String::new();
for line in fs::read_to_string(&args[1])?.lines() {
let v: Value = serde_json::from_str(line)?;
let layer = v["layer"]
.as_str()
.unwrap_or_default()
.trim_start_matches("minecraft:");
let baby = layer.contains("_baby#");
let adult = layer.replace("_baby#", "#");
// Variant layers (sizes, hatless villagers, climate cows...) animate
// like their base model.
let mut base = adult.clone();
for cut in ["_no_hat", "_small", "_medium", "_large"] {
base = base.replace(cut, "");
}
let base = base.trim_start_matches("cold_").trim_start_matches("warm_");
let Some(def) = species::ALL.iter().find(|d| {
d.model == layer
|| (baby && d.model == adult)
|| d.model == base
|| d.model.trim_end_matches("#main") == base.trim_end_matches("#main")
}) else {
out.push_str(&format!("{}\n", json!({"skip": "no species"})));
continue;
};
let Some(kind) = types.types.get(&format!("minecraft:{}", def.name)) else {
out.push_str(&format!("{}\n", json!({"skip": "no type"})));
continue;
};
let kind = Arc::new(kind.clone());
let model = kind
.layer(layer)
.cloned()
.unwrap_or_else(|| kind.model.clone());
let mut mob = Mob::new(7, kind, Vec3::new(0.0, 64.0, 0.0), 0.0);
mob.extra.main_hand = None;
let case = &v["case"];
let f = |k: &str| case[k].as_f64().unwrap_or(0.0) as f32;
if baby {
mob.extra.age = -24000;
}
mob.age = f("ageInTicks") as u32;
let state = State {
pos: f("walkAnimationPos"),
speed: f("walkAnimationSpeed"),
age: f("ageInTicks"),
y_rot: f("yRot"),
x_rot: f("xRot"),
swing: f("swingAnimation"),
baby,
partial: 0.0,
};
let mut poses = Poses::new(&model);
entity_state(&mut mob, def.species, case);
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;
let started = |k: &str| AnimationState {
started: case[k].as_f64().map(|v| v as f32),
};
let (p, s) = (&mut poses, &state);
match def.species {
Species::Goat => b_anim::goat(
p,
s,
&b_anim::Goat {
left_horn: flag("hasLeftHorn"),
right_horn: flag("hasRightHorn"),
ramming_x_head_rot: num("rammingXHeadRot"),
},
),
Species::PolarBear => b_anim::polar_bear(p, s, num("standScale")),
Species::Panda => b_anim::panda(
p,
s,
&b_anim::Panda {
unhappy: flag("isUnhappy"),
sneezing: flag("isSneezing"),
sneeze_time: num("sneezeTime") as i32,
eating: flag("isEating"),
scared: flag("isScared"),
sit_amount: num("sitAmount"),
lie_on_back_amount: num("lieOnBackAmount"),
roll_amount: num("rollAmount"),
},
),
Species::Llama | Species::TraderLlama => b_anim::llama(p, s, flag("hasChest")),
Species::Turtle => b_anim::turtle(
p,
s,
&b_anim::Turtle {
on_land: flag("isOnLand"),
laying_egg: flag("isLayingEgg"),
has_egg: flag("hasEgg"),
},
),
Species::Strider => b_anim::strider(p, s, flag("isRidden")),
Species::SnowGolem => b_anim::snow_golem(p, s),
Species::Silverfish => b_anim::silverfish(p, s),
Species::Endermite => b_anim::endermite(p, s),
Species::Parrot => b_anim::parrot(
p,
s,
match case["pose"].as_str() {
Some("FLYING") => b_anim::ParrotPose::Flying,
Some("ON_SHOULDER") => b_anim::ParrotPose::OnShoulder,
Some("SITTING") => b_anim::ParrotPose::Sitting,
Some("PARTY") => b_anim::ParrotPose::Party,
_ => b_anim::ParrotPose::Standing,
},
num("flapAngle"),
),
Species::Bee => b_anim::bee(
p,
s,
&b_anim::Bee {
has_stinger: flag("hasStinger"),
on_ground: flag("isOnGround"),
angry: flag("isAngry"),
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,
&b_anim::Armadillo {
hiding_in_shell: flag("isHidingInShell"),
roll_out: started("rollOutAnimationState"),
roll_up: started("rollUpAnimationState"),
peek: started("peekAnimationState"),
},
&animations,
),
Species::Axolotl => b_anim::axolotl(
p,
s,
&b_anim::Axolotl {
playing_dead: num("playingDeadFactor"),
in_water: num("inWaterFactor"),
on_ground: num("onGroundFactor"),
moving: num("movingFactor"),
swim: started("swimAnimation"),
walk: started("walkAnimationState"),
idle_on_ground: started("idleOnGroundAnimationState"),
idle_underwater_on_ground: started("idleUnderWaterOnGroundAnimationState"),
idle_underwater: started("idleUnderWaterAnimationState"),
play_dead: started("playDeadAnimationState"),
},
&animations,
),
Species::Frog => b_anim::frog(
p,
s,
&b_anim::Frog {
swimming: flag("isSwimming"),
jump: started("jumpAnimationState"),
croak: started("croakAnimationState"),
tongue: started("tongueAnimationState"),
swim_idle: started("swimIdleAnimationState"),
},
&animations,
),
Species::Rabbit => b_anim::rabbit(
p,
s,
&started("hopAnimationState"),
&started("idleHeadTiltAnimationState"),
&animations,
),
Species::Fox => b_anim::fox(
p,
s,
&b_anim::Fox {
crouching: flag("isCrouching"),
sleeping: flag("isSleeping"),
sitting: flag("isSitting"),
pouncing: flag("isPouncing"),
faceplanted: flag("isFaceplanted"),
head_roll_angle: num("headRollAngle"),
crouch_amount: num("crouchAmount"),
leg_motion_pos: 0.67,
},
&animations,
),
Species::Cat | Species::Ocelot => horizon_client::mobs::tame::feline(
p,
s,
&horizon_client::mobs::tame::Feline {
crouching: flag("isCrouching"),
sprinting: flag("isSprinting"),
sitting: flag("isSitting"),
lie_down: num("lieDownAmount"),
lie_down_tail: num("lieDownAmountTail"),
relax_one: num("relaxStateOneAmount"),
},
),
Species::Piglin | Species::PiglinBrute => {
use horizon_client::mobs::piglin::{PiglinPose, piglin_pose};
let pose = match case["armPose"].as_str() {
Some("DANCING") => PiglinPose::Dancing,
Some("ATTACKING_WITH_MELEE_WEAPON") => PiglinPose::MeleeWeapon,
Some("CROSSBOW_HOLD") => PiglinPose::CrossbowHold,
Some("CROSSBOW_CHARGE") => PiglinPose::CrossbowCharge,
Some("ADMIRING_ITEM") => PiglinPose::AdmiringItem,
_ => PiglinPose::Default,
};
piglin_pose(
p,
s,
pose,
num("maxCrossbowChageDuration"),
num("ticksUsingItem"),
);
}
Species::Evoker | Species::Pillager | Species::Vindicator => {
use horizon_client::mobs::illager::{ArmPose, anim_pose};
let pose = match case["armPose"].as_str() {
Some("CROSSED") => ArmPose::Crossed,
Some("ATTACKING") => ArmPose::Attacking,
Some("SPELLCASTING") => ArmPose::Spellcasting,
Some("BOW_AND_ARROW") => ArmPose::BowAndArrow,
Some("CROSSBOW_HOLD") => ArmPose::CrossbowHold,
Some("CROSSBOW_CHARGE") => ArmPose::CrossbowCharge,
Some("CELEBRATING") => ArmPose::Celebrating,
_ => ArmPose::Neutral,
};
mob.extra.passenger = flag("isRiding");
mob.extra.using_item = num("ticksUsingItem") as i32;
anim_pose(&mob, s, p, pose);
}
_ => anim::setup(&mob, s, p, &animations),
}
let mut parts = BTreeMap::new();
walk(&model, "", &poses, &mut parts);
out.push_str(&format!("{}\n", json!({"parts": parts})));
}
fs::write(&args[2], out)?;
Ok(())
}
+1
View File
@@ -9,6 +9,7 @@ pub mod ai;
pub mod allay;
pub mod anim;
pub mod aquatic;
pub mod body_anim;
pub mod camel;
pub mod control;
pub mod creaking;
+10 -8
View File
@@ -8,6 +8,7 @@ use super::{
goals::{Cx, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone},
nav::NavKind,
};
use horizon_core::geometry::trig::Mth;
// Allay state: `main_hand` the held item, `ints[1]` how many it carries,
// `tame` a liked player, `point` the wanted item (set by the game),
@@ -15,8 +16,8 @@ use super::{
// pickup cooldown, `flag` dancing with `ints[4]` the dance clock,
// `egg_time` the duplication cooldown. AnimState slots: holding (0),
// spinning (1).
const HOLD: usize = 0;
const SPIN: usize = 1;
pub const HOLD: usize = 0;
pub const SPIN: usize = 1;
pub fn register(m: &mut Mob) {
m.ai.mov.kind = MoveKind::Flying {
@@ -151,22 +152,22 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
use std::f32::consts::PI;
let (speed, pos) = (s.speed, s.pos);
let flap_speed = (s.age * 20.0).to_radians() + pos;
let flap = flap_speed.cos() * PI * 0.15 + speed;
let flap = flap_speed.mcos() * PI * 0.15 + speed;
let idle_bob = (s.age * 9.0).to_radians();
let flying = (speed / 0.3).min(1.0);
let idle = 1.0 - flying;
let hold = m.anim.lerp(HOLD, s.partial) / 5.0;
if m.extra.flag {
let dance = (s.age * 8.0).to_radians() + speed;
let freq = dance.cos() * 16f32.to_radians();
let freq = dance.mcos() * 16f32.to_radians();
let spin = m.anim.lerp(SPIN, s.partial) / 15.0;
let spinning = (m.extra.ints[4] as f32 % 55.0) < 15.0;
if spinning {
p.yrot("root", PI * 4.0 * spin);
}
p.zrot("root", freq * (1.0 - spin));
p.yrot("head", dance.cos() * 30f32.to_radians() * (1.0 - spin));
p.zrot("head", dance.cos() * 14f32.to_radians() * (1.0 - spin));
p.yrot("head", dance.mcos() * 30f32.to_radians() * (1.0 - spin));
p.zrot("head", dance.mcos() * 14f32.to_radians() * (1.0 - spin));
} else {
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
@@ -177,11 +178,12 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("left_wing", PI / 4.0 - flap);
p.xrot("body", flying * PI / 4.0);
let arm_x = hold * (-PI / 3.0 + (-1.134_464 + PI / 3.0) * flying);
p.get("root")[1] += idle_bob.cos() * 0.25 * idle;
// `(float) Math.cos`: the exact function, not `Mth.cos`.
p.get("root")[1] += (f64::from(idle_bob).cos() as f32) * 0.25 * idle;
p.xrot("right_arm", arm_x);
p.xrot("left_arm", arm_x);
let arm_bob = idle * (1.0 - hold);
let amount = 0.436_332_32 - (idle_bob + PI * 1.5).cos() * PI * 0.075 * arm_bob;
let amount = 0.436_332_32 - (idle_bob + PI * 1.5).mcos() * PI * 0.075 * arm_bob;
p.zrot("left_arm", -amount);
p.zrot("right_arm", amount);
p.yrot("right_arm", 0.279_252_68 * hold);
+232 -146
View File
@@ -2,6 +2,7 @@
//! (quadrupeds, humanoids, creepers, spiders, chickens...) applied to a map of
//! part poses before the model is drawn.
use super::{Mob, Part, keyframes::AnimationState, living::wrap};
use horizon_core::geometry::trig::Mth;
use std::collections::HashMap;
use std::f32::consts::PI;
@@ -98,6 +99,10 @@ impl AnimState {
pub struct Poses {
map: HashMap<String, [f32; 9]>,
dummy: [f32; 9],
/// Parts with `skipDraw` set: their own cubes are not drawn, children are.
skipped: std::collections::HashSet<String>,
/// Parts with `visible` cleared: neither they nor their children draw.
hidden: std::collections::HashSet<String>,
}
impl Poses {
pub fn new(model: &Part) -> Self {
@@ -112,6 +117,8 @@ impl Poses {
Self {
map,
dummy: [0.0; 9],
skipped: Default::default(),
hidden: Default::default(),
}
}
pub fn get(&mut self, name: &str) -> &mut [f32; 9] {
@@ -123,6 +130,12 @@ impl Poses {
pub fn pose(&self, part: &Part) -> [f32; 9] {
self.map.get(&part.name).copied().unwrap_or(part.pose)
}
pub fn skip_draw(&mut self, name: &str) {
self.skipped.insert(name.to_owned());
}
pub fn skips(&self, part: &Part) -> bool {
self.skipped.contains(&part.name)
}
pub fn has(&self, name: &str) -> bool {
self.map.contains_key(name)
}
@@ -135,14 +148,17 @@ impl Poses {
pub fn zrot(&mut self, n: &str, v: f32) {
self.get(n)[5] = v;
}
/// `ModelPart.visible = v`; a hidden part and its children do not draw.
pub fn visible(&mut self, n: &str, v: bool) {
if !v {
let p = self.get(n);
p[6] = 0.0;
p[7] = 0.0;
p[8] = 0.0;
if v {
self.hidden.remove(n);
} else if self.map.contains_key(n) {
self.hidden.insert(n.to_owned());
}
}
pub fn is_hidden(&self, part: &Part) -> bool {
self.hidden.contains(&part.name)
}
}
/// The LivingEntityRenderState values setupAnim reads.
#[derive(Clone, Copy, Debug)]
@@ -191,21 +207,21 @@ fn head(p: &mut Poses, s: &State) {
p.yrot("head", s.y_rot.to_radians());
}
/// QuadrupedModel.setupAnim
fn quadruped(p: &mut Poses, s: &State) {
pub(super) fn quadruped(p: &mut Poses, s: &State) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * sp);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * sp);
}
/// AnimationUtils.bobModelPart
fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) {
let q = p.get(n);
q[5] += scale * ((age * 0.09).cos() * 0.05 + 0.05);
q[3] += scale * ((age * 0.067).sin() * 0.05);
q[5] += scale * ((age * 0.09).mcos() * 0.05 + 0.05);
q[3] += scale * ((age * 0.067).msin() * 0.05);
}
#[derive(Clone, Copy, PartialEq, Eq)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ArmPose {
Empty,
Item,
@@ -213,118 +229,196 @@ pub enum ArmPose {
CrossbowHold,
CrossbowCharge,
}
/// HumanoidModel.setupAnim holding an item or not (piglins).
pub fn humanoid_item(p: &mut Poses, s: &State, holding: bool) {
let right = if holding {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(p, s, right, ArmPose::Empty, None, holding);
/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself.
pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) {
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// HumanoidModel.setupAnim with empty hands (endermen).
pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) {
humanoid(p, s, ArmPose::Empty, ArmPose::Empty, None, false);
humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty));
}
/// HumanoidModel.setupAnim up to (and including) the attack animation hook.
fn humanoid(
p: &mut Poses,
s: &State,
right: ArmPose,
left: ArmPose,
zombie: Option<bool>,
holding: bool,
) {
/// `AnimationUtils.swingWeaponDown` with the right arm as the main arm.
pub(super) fn swing_weapon_down(p: &mut Poses, swing: f32, age: f32) {
let attack2 = (swing * PI).msin();
let attack = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot("right_arm", -1.884_955_8 + (age * 0.09).mcos() * 0.15);
p.xrot("left_arm", -0.0 + (age * 0.19).mcos() * 0.5);
p.get("right_arm")[3] += attack2 * 2.2 - attack * 0.4;
p.get("left_arm")[3] += attack2 * 1.2 - attack * 0.4;
bob(p, "right_arm", age, 1.0);
bob(p, "left_arm", age, -1.0);
}
/// What `HumanoidModel.setupAnim` reads besides the walk and head inputs.
#[derive(Clone, Copy, Debug)]
pub struct Hum {
pub right: ArmPose,
pub left: ArmPose,
pub crouching: bool,
pub passenger: bool,
/// `Some(aggressive)` for `ZombieModel`-style `animateZombieArms`.
pub zombie: Option<bool>,
/// The main hand holds something (`getMainHandItemStack() != EMPTY`).
pub holding: bool,
/// `maxCrossbowChargeDuration`, `ticksUsingItem`.
pub charge: (f32, f32),
/// `PiglinModel.setupAttackAnimation`: swing a held weapon down.
pub weapon_swing: bool,
}
impl Hum {
pub fn new(right: ArmPose, left: ArmPose) -> Self {
Self {
right,
left,
crouching: false,
passenger: false,
zombie: None,
holding: false,
charge: (0.0, 0.0),
weapon_swing: false,
}
}
}
impl ArmPose {
fn two_handed(self) -> bool {
matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge)
}
fn affects_offhand(self) -> bool {
self.two_handed()
}
}
/// `AnimationUtils.animateCrossbowHold`.
fn crossbow_hold(p: &mut Poses, hx: f32, hy: f32, in_right: bool) {
let (hold, shoot) = if in_right {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if in_right { -0.3 } else { 0.3 } + hy);
p.yrot(shoot, if in_right { 0.6 } else { -0.6 } + hy);
p.xrot(hold, -PI / 2.0 + hx + 0.1);
p.xrot(shoot, -1.5 + hx);
}
/// `AnimationUtils.animateCrossbowCharge`.
fn crossbow_charge(p: &mut Poses, max: f32, ticks: f32, in_right: bool) {
let (hold, pull) = if in_right {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if in_right { -0.8 } else { 0.8 });
p.xrot(hold, -0.970_796_35);
p.xrot(pull, -0.970_796_35);
let use_ticks = ticks.clamp(0.0, max);
let alpha = use_ticks / max;
let lerp = |a: f32, p0: f32, p1: f32| p0 + a * (p1 - p0);
p.yrot(
pull,
lerp(alpha, 0.4, 0.85) * if in_right { 1.0 } else { -1.0 },
);
let x = lerp(alpha, p.get(pull)[3], -PI / 2.0);
p.xrot(pull, x);
}
/// `HumanoidModel.poseRightArm` / `poseLeftArm`.
fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) {
let arm = if right { "right_arm" } else { "left_arm" };
let (hx, hy) = (p.get("head")[3], p.get("head")[4]);
match pose {
ArmPose::Empty => p.yrot(arm, 0.0),
ArmPose::Item => {
let x = p.get(arm)[3];
p.xrot(arm, x * 0.5 - PI / 10.0);
p.yrot(arm, 0.0);
}
ArmPose::Bow => {
p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 });
p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 });
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -PI / 2.0 + hx);
}
ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right),
ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right),
}
}
/// `HumanoidModel.setupAnim` (and `ZombieModel.setupAttackAnimation`).
pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) {
head(p, s);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp);
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp);
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp);
p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp);
p.yrot("right_leg", 0.005);
p.yrot("left_leg", -0.005);
p.zrot("right_leg", 0.005);
p.zrot("left_leg", -0.005);
let (hx, hy) = (p.get("head")[3], p.get("head")[4]);
for (arm, pose) in [("right_arm", right), ("left_arm", left)] {
match pose {
ArmPose::Empty => p.yrot(arm, 0.0),
ArmPose::Item => {
let x = p.get(arm)[3];
p.xrot(arm, x * 0.5 - PI / 10.0);
p.yrot(arm, 0.0);
}
ArmPose::Bow => {
let right_main = arm == "right_arm";
p.yrot("right_arm", -0.1 + hy - if right_main { 0.0 } else { 0.4 });
p.yrot("left_arm", 0.1 + hy + if right_main { 0.4 } else { 0.0 });
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -PI / 2.0 + hx);
}
ArmPose::CrossbowHold => {
let r = arm == "right_arm";
let (hold, shoot) = if r {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if r { -0.3 } else { 0.3 } + hy);
p.yrot(shoot, if r { 0.6 } else { -0.6 } + hy);
p.xrot(hold, -PI / 2.0 + hx + 0.1);
p.xrot(shoot, -1.5 + hx);
}
ArmPose::CrossbowCharge => {
let r = arm == "right_arm";
let (hold, pull) = if r {
("right_arm", "left_arm")
} else {
("left_arm", "right_arm")
};
p.yrot(hold, if r { -0.8 } else { 0.8 });
p.xrot(hold, -0.970_796_35);
p.xrot(pull, -0.970_796_35);
p.yrot(pull, 0.6 * if r { 1.0 } else { -1.0 });
p.xrot(pull, -PI / 2.0);
}
if h.passenger {
p.get("right_arm")[3] += -PI / 5.0;
p.get("left_arm")[3] += -PI / 5.0;
p.xrot("right_leg", -1.413_716_7);
p.yrot("right_leg", PI / 10.0);
p.zrot("right_leg", 0.078_539_82);
p.xrot("left_leg", -1.413_716_7);
p.yrot("left_leg", -PI / 10.0);
p.zrot("left_leg", -0.078_539_82);
}
// The main arm is the right one: the off-hand pose goes first unless it
// needs both hands.
if h.left.two_handed() {
pose_arm(p, h.right, true, h);
if !h.right.affects_offhand() {
pose_arm(p, h.left, false, h);
}
} else {
pose_arm(p, h.left, false, h);
if !h.left.affects_offhand() {
pose_arm(p, h.right, true, h);
}
}
// setupAttackAnimation (WHACK swing with the right arm).
let hx = p.get("head")[3];
let swing = s.swing;
if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).sin() * 0.2;
if swing > 0.0 && h.weapon_swing {
swing_weapon_down(p, swing, s.age);
} else if swing > 0.0 {
let body_y = (swing.sqrt() * PI * 2.0).msin() * 0.2;
p.yrot("body", body_y);
let age_scale = if s.baby { 0.5 } else { 1.0 };
{
let r = p.get("right_arm");
r[2] = body_y.sin() * 5.0 * age_scale;
r[0] = -body_y.cos() * 5.0 * age_scale;
r[2] = body_y.msin() * 5.0 * age_scale;
r[0] = -body_y.mcos() * 5.0 * age_scale;
}
{
let l = p.get("left_arm");
l[2] = -body_y.sin() * 5.0 * age_scale;
l[0] = body_y.cos() * 5.0 * age_scale;
l[2] = -body_y.msin() * 5.0 * age_scale;
l[0] = body_y.mcos() * 5.0 * age_scale;
}
p.get("right_arm")[4] += body_y;
p.get("left_arm")[4] += body_y;
p.get("left_arm")[3] += body_y;
// Ease.outQuart
let eased = 1.0 - (1.0 - swing).powi(4);
let aa = (eased * PI).sin();
let bb = (swing * PI).sin() * -(hx - 0.7) * 0.75;
let aa = (eased * PI).msin();
let bb = (swing * PI).msin() * -(hx - 0.7) * 0.75;
let r = p.get("right_arm");
r[3] -= aa * 1.2 + bb;
r[4] += body_y * 2.0;
r[5] += (swing * PI).sin() * -0.4;
r[5] += (swing * PI).msin() * -0.4;
}
if let Some(aggressive) = zombie {
if let Some(aggressive) = h.zombie {
// AnimationUtils.animateZombieArms
let raise = !s.baby || !holding;
let raise = !s.baby || !h.holding;
let drop = if raise {
-PI / if aggressive { 1.5 } else { 2.25 }
} else {
0.0
};
let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).sin();
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let ym = if raise { 1.0 } else { -1.0 } * (swing * PI).msin();
let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
let x = drop + ym * 1.2 - xm * 0.4;
let y = 0.1 - ym * 0.6;
p.xrot("right_arm", x);
@@ -334,6 +428,17 @@ fn humanoid(
p.yrot("left_arm", if raise { y } else { -y });
p.zrot("left_arm", 0.0);
}
if h.crouching {
p.xrot("body", 0.5);
p.get("right_arm")[3] += 0.4;
p.get("left_arm")[3] += 0.4;
p.get("right_leg")[2] += 4.0;
p.get("left_leg")[2] += 4.0;
p.get("head")[1] += 4.2;
p.get("body")[1] += 3.2;
p.get("left_arm")[1] += 3.2;
p.get("right_arm")[1] += 3.2;
}
bob(p, "right_arm", s.age, 1.0);
bob(p, "left_arm", s.age, -1.0);
}
@@ -344,6 +449,9 @@ pub fn setup(
p: &mut Poses,
w_anims: &HashMap<String, super::keyframes::Animation>,
) {
if super::body_anim::anim(m, s, p, w_anims) {
return;
}
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Allay => super::allay::anim(m, s, p),
@@ -368,7 +476,7 @@ pub fn setup(
};
let angle = if t > 4 && t <= 36 {
let f = ((t - 4) as f32 - partial) / 32.0;
PI / 5.0 + 0.219_911_49 * (f * 28.7).sin()
PI / 5.0 + 0.219_911_49 * (f * 28.7).msin()
} else if t > 0 {
PI / 5.0
} else {
@@ -382,9 +490,9 @@ pub fn setup(
let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial;
let flap_speed =
m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial;
let angle = (flap.sin() + 1.0) * flap_speed;
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot("left_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
let angle = (flap.msin() + 1.0) * flap_speed;
p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
p.xrot("left_leg", (s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed);
p.zrot("right_wing", angle);
p.zrot("left_wing", -angle);
if !s.baby {
@@ -396,57 +504,35 @@ pub fn setup(
| Anim::ZombieVillager
| Anim::ZombifiedPiglin
| Anim::Humanoid { zombie_arms: true } => {
let holding = m.extra.main_hand.is_some();
let right = if holding {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(p, s, right, ArmPose::Empty, Some(m.ai.aggressive), holding);
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.zombie = Some(m.ai.aggressive);
h.holding = m.extra.main_hand.is_some();
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
if m.kind.anim == Anim::ZombifiedPiglin {
super::piglin::ears(p, s);
}
}
Anim::Skeleton | Anim::Humanoid { zombie_arms: false } => {
let bow = m.extra.main_hand.as_deref() == Some("minecraft:bow");
let player = matches!(m.kind.anim, Anim::Humanoid { .. });
let right = if bow && m.ai.aggressive {
ArmPose::Bow
} else if m.extra.main_hand.is_some() {
} else if player && m.extra.main_hand.is_some() {
ArmPose::Item
} else {
ArmPose::Empty
};
humanoid(
p,
s,
right,
ArmPose::Empty,
None,
m.extra.main_hand.is_some(),
);
if m.extra.passenger {
// HumanoidModel.setupAnim: riding.
p.get("right_arm")[3] -= PI / 5.0;
p.get("left_arm")[3] -= PI / 5.0;
for (leg, side) in [("right_leg", 1.0), ("left_leg", -1.0)] {
p.xrot(leg, -1.413_716_7);
p.yrot(leg, side * PI / 10.0);
p.zrot(leg, side * 0.078_539_82);
}
}
if m.extra.crouching {
p.xrot("body", 0.5);
p.get("right_arm")[3] += 0.4;
p.get("left_arm")[3] += 0.4;
p.get("right_leg")[2] += 4.0;
p.get("left_leg")[2] += 4.0;
p.get("head")[1] += 4.2;
p.get("body")[1] += 3.2;
p.get("left_arm")[1] += 3.2;
p.get("right_arm")[1] += 3.2;
}
let mut h = Hum::new(right, ArmPose::Empty);
h.crouching = m.extra.crouching;
h.passenger = m.extra.passenger;
humanoid(p, s, &h);
if m.ai.aggressive && !bow {
// SkeletonModel melee pose.
let sw = s.swing;
let s2 = (sw * PI).sin();
let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).sin();
let s2 = (sw * PI).msin();
let s1 = ((1.0 - (1.0 - sw) * (1.0 - sw)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", -(0.1 - s2 * 0.6));
@@ -474,37 +560,37 @@ pub fn setup(
// DonkeyModel: the chests show once fitted.
if !m.extra.chested {
for part in ["left_chest", "right_chest"] {
if p.has(part) {
let v = p.get(part);
v[6] = 0.0;
v[7] = 0.0;
v[8] = 0.0;
}
p.visible(part, false);
}
}
}
Anim::Hoglin => super::piglin::hoglin_anim(m, s, p),
Anim::Blaze => super::nether::blaze_anim(s, p),
Anim::Ghast => super::nether::ghast_anim(s, p),
Anim::Feline if m.species() == super::Species::Cat => super::tame::cat_anim(m, s, p),
Anim::Feline => super::tame::cat_anim(m, s, p),
Anim::Enderman => super::enderman::anim(m, s, p),
Anim::Slime | Anim::MagmaCube => super::cube::anim(m, s, p),
Anim::Creeper => {
head(p, s);
p.xrot("right_hind_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot("left_hind_leg", (s.pos * 0.6662 + PI).cos() * 1.4 * s.speed);
// CreeperModel binds its fields to the opposite-side parts, so the
// left formulas drive the right parts and the reverse.
p.xrot("left_hind_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
p.xrot(
"right_front_leg",
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed,
"right_hind_leg",
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed,
);
p.xrot("left_front_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed);
p.xrot(
"left_front_leg",
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed,
);
p.xrot("right_front_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed);
}
Anim::Spider => {
head(p, s);
let pos = s.pos * 0.6662;
let sp = s.speed;
let swing = |o: f32| -((pos * 2.0 + o).cos() * 0.4) * sp;
let step = |o: f32| ((pos + o).sin() * 0.4).abs() * sp;
let swing = |o: f32| -((pos * 2.0 + o).mcos() * 0.4) * sp;
let step = |o: f32| ((pos + o).msin() * 0.4).abs() * sp;
let legs = [
("hind", 0.0f32, 0.0f32),
("middle_hind", PI, PI),
+16 -15
View File
@@ -12,12 +12,13 @@ use super::{
nav::NavKind,
};
use crate::blocks::Fluid;
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
// Squid animation slots in AnimState.v.
const TENTACLE_MOVEMENT: usize = 0;
const TENTACLE_ANGLE: usize = 1;
pub const TENTACLE_ANGLE: usize = 1;
const X_BODY_ROT: usize = 2;
const Z_BODY_ROT: usize = 3;
const TENTACLE_SPEED: usize = 4;
@@ -229,7 +230,7 @@ fn squid_ai_step(m: &mut Mob) {
if m.fluids.in_water {
if v[TENTACLE_MOVEMENT] < PI {
let scale = v[TENTACLE_MOVEMENT] / PI;
v[TENTACLE_ANGLE] = (scale * scale * PI).sin() * PI * 0.25;
v[TENTACLE_ANGLE] = (scale * scale * PI).msin() * PI * 0.25;
if scale > 0.75 {
let mv = m.extra.vector;
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
@@ -250,7 +251,7 @@ fn squid_ai_step(m: &mut Mob) {
v[Z_BODY_ROT] += PI * v[ROTATE_SPEED] * 1.5;
v[X_BODY_ROT] += (-(horizontal.atan2(mv.y) as f32).to_degrees() - v[X_BODY_ROT]) * 0.1;
} else {
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].sin().abs() * PI * 0.25;
v[TENTACLE_ANGLE] = v[TENTACLE_MOVEMENT].msin().abs() * PI * 0.25;
let yd = m.velocity.y - m.kind.gravity;
m.velocity = Vec3::new(0.0, yd * 0.98, 0.0);
let v = &mut m.anim.v;
@@ -339,9 +340,9 @@ impl Goal for SquidRandomMovement {
let angle = m.random.next_float() * PI * 2.0;
let y = -0.1 + m.random.next_float() * 0.2;
m.extra.vector = [
f64::from(angle.cos() * 0.2),
f64::from(angle.mcos() * 0.2),
f64::from(y),
f64::from(angle.sin() * 0.2),
f64::from(angle.msin() * 0.2),
];
}
}
@@ -496,23 +497,23 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot(&format!("tentacle{i}"), angle);
}
}
S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).sin()),
S::Cod => p.yrot("tail_fin", -amp * 0.45 * (0.6 * s.age).msin()),
// TadpoleModel: a stronger tail swing out of water.
S::Tadpole => {
let a = if m.fluids.in_water { 1.0 } else { 1.5 };
p.yrot("tail", -a * 0.25 * (0.3 * s.age).sin())
p.yrot("tail", -a * 0.25 * (0.3 * s.age).msin())
}
S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).sin()),
S::TropicalFish => p.yrot("tail", -amp * 0.45 * (0.6 * s.age).msin()),
S::Salmon => {
let (a, k) = if m.fluids.in_water {
(1.0, 1.0)
} else {
(1.3, 1.7)
};
p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).sin());
p.yrot("body_back", -a * 0.25 * (k * 0.6 * s.age).msin());
}
S::Pufferfish => {
let fin = 0.2 - 0.4 * (s.age * 0.2).sin();
let fin = 0.2 - 0.4 * (s.age * 0.2).msin();
if p.has("right_blue_fin") {
p.zrot("right_blue_fin", -fin);
p.zrot("left_blue_fin", fin);
@@ -526,9 +527,9 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("body", s.y_rot.to_radians());
let moving = m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z > 1.0e-7;
if moving {
p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).cos();
p.xrot("tail", -0.1 * (s.age * 0.3).cos());
p.xrot("tail_fin", -0.2 * (s.age * 0.3).cos());
p.get("body")[3] += -0.05 - 0.05 * (s.age * 0.3).mcos();
p.xrot("tail", -0.1 * (s.age * 0.3).mcos());
p.xrot("tail_fin", -0.2 * (s.age * 0.3).mcos());
}
}
_ => {}
@@ -565,7 +566,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option<glam::Mat4> {
(1.0, 1.0)
};
let mut t = glam::Mat4::from_rotation_y((180.0 - body).to_radians())
* glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).sin()).to_radians());
* glam::Mat4::from_rotation_y((a * 4.3 * (k * 0.6 * age).msin()).to_radians());
if !m.fluids.in_water {
let off = if m.species() == S::Cod {
glam::Vec3::new(0.1, 0.1, -0.1)
@@ -577,7 +578,7 @@ pub fn rotations(m: &Mob, alpha: f32, body: f32) -> Option<glam::Mat4> {
Some(t)
}
S::Pufferfish => Some(
glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).cos() * 0.08, 0.0))
glam::Mat4::from_translation(glam::Vec3::new(0.0, (age * 0.05).mcos() * 0.08, 0.0))
* glam::Mat4::from_rotation_y((180.0 - body).to_radians()),
),
_ => None,
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -8,6 +8,7 @@ use super::{
Tempt, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::collections::HashMap;
@@ -179,7 +180,7 @@ pub fn dash(m: &mut Mob, amount: f32, events: &mut Vec<MobEvent>) {
return;
}
let yaw = m.yaw.to_radians();
let (dx, dz) = (f64::from(-yaw.sin()), f64::from(yaw.cos()));
let (dx, dz) = (f64::from(-yaw.msin()), f64::from(yaw.mcos()));
let speed = m.movement_speed();
let a = f64::from(amount);
m.velocity.x += dx * 22.2222 * a * speed;
+8
View File
@@ -68,6 +68,14 @@ impl MobData {
data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default();
data
}
/// Only the keyframe animation definitions of `mob-data.json`.
pub fn load_animations(root: &Path) -> HashMap<String, Animation> {
fs::read(root.join("mob-data.json"))
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
.map(|v| Self::from_json(&v).animations)
.unwrap_or_default()
}
pub fn entity_has(&self, tag: &str, entity: &str) -> bool {
self.entity_tags
.get(tag)
+24 -11
View File
@@ -9,6 +9,7 @@ use super::{
Tempt, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -24,9 +25,9 @@ pub const COLORS: [&str; 7] = [
pub const MARKINGS: [&str; 5] = ["", "white", "whitefield", "whitedots", "blackdots"];
// AnimState slots.
const EAT: usize = 0;
const STAND: usize = 1;
const MOUTH: usize = 2;
pub const EAT: usize = 0;
pub const STAND: usize = 1;
pub const MOUTH: usize = 2;
/// What a rider asks of its mount this tick.
#[derive(Clone, Copy, Debug, Default)]
@@ -164,7 +165,7 @@ fn boost_factor(m: &mut Mob) -> f32 {
m.extra.counter2 = 0;
return 1.0;
}
1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).sin()
1.0 + 1.15 * (m.extra.counter as f32 / m.extra.counter2 as f32 * PI).msin()
}
/// `AbstractHorse.MountPanicGoal`: only without a rider.
#[derive(Clone, Debug)]
@@ -360,7 +361,7 @@ pub fn ridden_step(m: &mut Mob) {
let impulse = m.extra.vector[0] as f32 * r.jump;
m.velocity.y = f64::from(impulse);
if forward > 0.0 {
let (s, c) = (m.yaw.to_radians().sin(), m.yaw.to_radians().cos());
let (s, c) = (m.yaw.to_radians().msin(), m.yaw.to_radians().mcos());
m.velocity.x += f64::from(-0.4 * s * r.jump);
m.velocity.z += f64::from(0.4 * c * r.jump);
}
@@ -482,19 +483,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let mut head_x = s.x_rot.to_radians();
let (speed, pos) = (s.speed, s.pos);
if speed > 0.2 {
head_x += (pos * 0.8).cos() * 0.15 * speed;
head_x += (pos * 0.8).mcos() * 0.15 * speed;
}
let eating = m.anim.lerp(EAT, s.partial);
let standing = m.anim.lerp(STAND, s.partial);
let istand = 1.0 - standing;
let feeding = m.anim.lerp(MOUTH, s.partial);
let in_water = if m.fluids.in_water { 0.2 } else { 1.0 };
let leg1 = (in_water * pos * 0.6662 + PI).cos();
let leg1 = (in_water * pos * 0.6662 + PI).mcos();
let leg_x = leg1 * 0.8 * speed;
let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.sin() * 0.05);
let base = (1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05);
p.xrot(
"head_parts",
standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.sin() * 0.05) + base,
standing * (PI / 12.0 + head_x) + eating * (2.181_661_6 + s.age.msin() * 0.05) + base,
);
p.yrot(
"head_parts",
@@ -527,7 +528,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
rf[2] = z;
}
let stand = stand_angle * standing;
let bob = (s.age * 0.6 + PI).cos();
let bob = (s.age * 0.6 + PI).mcos();
let rleg = (stand_x_off + bob) * standing + leg_x * istand;
let lleg = (stand_x_off - bob) * standing - leg_x * istand;
p.xrot("left_hind_leg", stand - leg1 * 0.5 * speed * istand);
@@ -536,9 +537,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("right_front_leg", lleg);
if baby && donkey {
let lerp = |t: f32, a: f32, b: f32| a + (b - a) * t;
// BabyDonkeyModel lerps the right leg from the left leg's new height.
let y = lerp(standing, p.get("left_hind_leg")[1], -0.3);
p.get("left_hind_leg")[1] = y;
p.get("right_hind_leg")[1] = y;
p.get("right_hind_leg")[1] = lerp(standing, y, -0.3);
}
let age = if baby { 0.5 } else { 1.0 };
p.xrot("tail", tail_off + PI / 6.0 + speed * 0.75);
@@ -548,4 +550,15 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
t[2] += speed * 2.0 * age;
}
p.yrot("tail", 0.0);
if baby && donkey {
// BabyDonkeyModel overrides the state's pitch with -30 degrees and
// sets the head parts again.
let head_x = -30.0f32 * horizon_core::geometry::trig::DEG_TO_RAD;
let base =
(1.0 - standing.max(eating)) * (PI / 6.0 + head_x + feeding * s.age.msin() * 0.05);
p.xrot(
"head_parts",
standing * (PI / 12.0 + head_x) + eating * (PI / 2.0 + s.age.msin() * 0.05) + base,
);
}
}
+11 -10
View File
@@ -12,15 +12,16 @@ use super::{
nav::NavKind,
path::PathType,
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
// Guardian state: `flag` an active beam target (DATA_ID_ATTACK_TARGET),
// `flag2` moving (DATA_ID_MOVING), `counter2` the client attack time.
// AnimState slots: tail animation, its speed, spikes animation.
const TAIL: usize = 0;
pub const TAIL: usize = 0;
const TAIL_SPEED: usize = 1;
const SPIKES: usize = 2;
pub const SPIKES: usize = 2;
const EYE_X: usize = 3;
const EYE_Y: usize = 4;
@@ -166,8 +167,8 @@ pub fn move_control(m: &mut Mob) {
let t = f64::from(m.age as i32 + m.id as i32);
let push = (t * 0.5).sin() * 0.05;
let (cos, sin) = (
f64::from(m.yaw.to_radians().cos()),
f64::from(m.yaw.to_radians().sin()),
f64::from(m.yaw.to_radians().mcos()),
f64::from(m.yaw.to_radians().msin()),
);
let y_push = (t * 0.75).sin() * 0.05;
m.velocity = m.velocity.add_vector(Vec3::new(
@@ -277,7 +278,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.anim.v[EYE_Y] = if look[1] - m.eye_y() > 0.0 { 0.0 } else { 1.0 };
let yaw = m.head_yaw.to_radians();
let pitch = m.head_pitch.to_radians();
let view = [-yaw.sin() * pitch.cos(), yaw.cos() * pitch.cos()];
let view = [-yaw.msin() * pitch.mcos(), yaw.mcos() * pitch.mcos()];
let d = [m.position.x - look[0], m.position.z - look[2]];
let len = (d[0] * d[0] + d[1] * d[1]).sqrt().max(1e-9);
let (dx, dz) = ((d[0] / len) as f32, (d[1] / len) as f32);
@@ -365,7 +366,7 @@ pub fn beam_geometry(
128u32.saturating_sub((cs * 64.0) as u32),
);
let color = 0xFF00_0000 | (b.min(255) << 16) | (g.min(255) << 8) | r.min(255);
let at = |a: f32, radius: f32| (a.cos() * radius, a.sin() * radius);
let at = |a: f32, radius: f32| (a.mcos() * radius, a.msin() * radius);
let quarter = std::f32::consts::FRAC_PI_4;
let (wx, wz) = at(rot + PI, 0.2);
let (ex, ez) = at(rot, 0.2);
@@ -432,7 +433,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
8.0, -8.0, 0.0, 0.0, -8.0, -8.0, 8.0, 8.0, 8.0, -8.0, 0.0, 0.0,
];
for i in 0..12 {
let offset = 1.0 + (s.age * 1.5 + i as f32).cos() * 0.01 - withdrawal;
let offset = 1.0 + (s.age * 1.5 + i as f32).mcos() * 0.01 - withdrawal;
let part = p.get(&format!("spike{i}"));
part[0] = X[i] * offset;
part[1] = 16.0 + Y[i] * offset;
@@ -442,7 +443,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
e[0] = m.anim.v[EYE_X];
e[1] = m.anim.v[EYE_Y];
let tail = m.anim.lerp(TAIL, s.partial);
p.yrot("tail0", tail.sin() * PI * 0.05);
p.yrot("tail1", tail.sin() * PI * 0.1);
p.yrot("tail2", tail.sin() * PI * 0.15);
p.yrot("tail0", tail.msin() * PI * 0.05);
p.yrot("tail1", tail.msin() * PI * 0.1);
p.yrot("tail2", tail.msin() * PI * 0.15);
}
+63 -33
View File
@@ -9,6 +9,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
@@ -304,8 +305,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..5 {
let a = angle + i as f32 * PI * 0.4;
place(
x + f64::from(a.cos()) * 1.5,
z + f64::from(a.sin()) * 1.5,
x + f64::from(a.mcos()) * 1.5,
z + f64::from(a.msin()) * 1.5,
a,
0,
);
@@ -313,8 +314,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..8 {
let a = angle + i as f32 * PI * 2.0 / 8.0 + PI * 2.0 / 5.0;
place(
x + f64::from(a.cos()) * 2.5,
z + f64::from(a.sin()) * 2.5,
x + f64::from(a.mcos()) * 2.5,
z + f64::from(a.msin()) * 2.5,
a,
3,
);
@@ -323,8 +324,8 @@ fn cast_fangs(m: &mut Mob, cx: &mut Cx) {
for i in 0..16 {
let reach = 1.25 * f64::from(i + 1);
place(
x + f64::from(angle.cos()) * reach,
z + f64::from(angle.sin()) * reach,
x + f64::from(angle.mcos()) * reach,
z + f64::from(angle.msin()) * reach,
angle,
i,
);
@@ -532,8 +533,9 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
pitch,
));
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum ArmPose {
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum ArmPose {
BowAndArrow,
Spellcasting,
Crossed,
Celebrating,
@@ -578,35 +580,53 @@ pub fn shows_item(m: &Mob) -> bool {
m.species() != Species::Vindicator || m.ai.aggressive
}
fn hide(p: &mut Poses, part: &str) {
if p.has(part) {
let v = p.get(part);
v[6] = 0.0;
v[7] = 0.0;
v[8] = 0.0;
}
p.visible(part, false);
}
/// `IllagerModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
anim_pose(m, s, p, arm_pose(m));
}
/// `IllagerModel.setupAnim` for a given arm pose.
pub fn anim_pose(m: &Mob, s: &State, p: &mut Poses, pose: ArmPose) {
// The hat is hidden by the model's constructor.
hide(p, "hat");
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
p.yrot("head", hy);
p.xrot("head", hx);
let (pos, sp) = (s.pos, s.speed);
p.xrot("right_arm", (pos * 0.6662 + PI).cos() * 2.0 * sp * 0.5);
p.yrot("right_arm", 0.0);
p.zrot("right_arm", 0.0);
p.xrot("left_arm", (pos * 0.6662).cos() * 2.0 * sp * 0.5);
p.yrot("left_arm", 0.0);
p.zrot("left_arm", 0.0);
p.xrot("right_leg", (pos * 0.6662).cos() * 1.4 * sp * 0.5);
p.xrot("left_leg", (pos * 0.6662 + PI).cos() * 1.4 * sp * 0.5);
let pose = arm_pose(m);
if m.extra.passenger {
for arm in ["right_arm", "left_arm"] {
p.xrot(arm, -PI / 5.0);
p.yrot(arm, 0.0);
p.zrot(arm, 0.0);
}
p.xrot("right_leg", -1.413_716_7);
p.yrot("right_leg", PI / 10.0);
p.zrot("right_leg", 0.078_539_82);
p.xrot("left_leg", -1.413_716_7);
p.yrot("left_leg", -PI / 10.0);
p.zrot("left_leg", -0.078_539_82);
} else {
p.xrot("right_arm", (pos * 0.6662 + PI).mcos() * 2.0 * sp * 0.5);
p.yrot("right_arm", 0.0);
p.zrot("right_arm", 0.0);
p.xrot("left_arm", (pos * 0.6662).mcos() * 2.0 * sp * 0.5);
p.yrot("left_arm", 0.0);
p.zrot("left_arm", 0.0);
p.xrot("right_leg", (pos * 0.6662).mcos() * 1.4 * sp * 0.5);
p.yrot("right_leg", 0.0);
p.zrot("right_leg", 0.0);
p.xrot("left_leg", (pos * 0.6662 + PI).mcos() * 1.4 * sp * 0.5);
p.yrot("left_leg", 0.0);
p.zrot("left_leg", 0.0);
}
match pose {
ArmPose::Attacking => {
if m.extra.main_hand.is_none() {
// animateZombieArms + bobArms
let swing = s.swing;
let a = (swing * PI).sin();
let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let a = (swing * PI).msin();
let b = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", -(0.1 - a * 0.6));
@@ -617,22 +637,25 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
} else {
// swingWeaponDown (right-handed).
let swing = s.swing;
let a2 = (swing * PI).sin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).sin();
let a2 = (swing * PI).msin();
let a = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin();
p.zrot("right_arm", 0.0);
p.zrot("left_arm", 0.0);
p.yrot("right_arm", PI / 20.0);
p.yrot("left_arm", -PI / 20.0);
p.xrot(
"right_arm",
-1.884_955_8 + (s.age * 0.09).cos() * 0.15 + (a2 * 2.2 - a * 0.4),
-1.884_955_8 + (s.age * 0.09).mcos() * 0.15 + (a2 * 2.2 - a * 0.4),
);
p.xrot(
"left_arm",
-0.0 + (s.age * 0.19).mcos() * 0.5 + (a2 * 1.2 - a * 0.4),
);
p.xrot("left_arm", (s.age * 0.19).cos() * 0.5);
}
let bob = |p: &mut Poses, part: &str, sign: f32| {
let v = p.get(part);
v[5] += sign * ((s.age * 0.09).cos() * 0.05 + 0.05);
v[3] += sign * (s.age * 0.067).sin() * 0.05;
v[5] += sign * ((s.age * 0.09).mcos() * 0.05 + 0.05);
v[3] += sign * (s.age * 0.067).msin() * 0.05;
};
bob(p, "right_arm", 1.0);
bob(p, "left_arm", -1.0);
@@ -659,7 +682,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.25;
v[3] = (s.age * 0.6662).mcos() * 0.25;
v[4] = 0.0;
v[5] = z_rot;
}
@@ -672,11 +695,18 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.05;
v[3] = (s.age * 0.6662).mcos() * 0.05;
v[4] = 0.0;
v[5] = z_rot;
}
}
ArmPose::BowAndArrow => {
p.yrot("right_arm", -0.1 + hy);
p.xrot("right_arm", -PI / 2.0 + hx);
p.xrot("left_arm", -0.942_477_9 + hx);
p.yrot("left_arm", hy - 0.4);
p.zrot("left_arm", PI / 2.0);
}
ArmPose::Crossed | ArmPose::Neutral => {}
}
if pose == ArmPose::Crossed {
+12 -11
View File
@@ -10,6 +10,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -181,25 +182,25 @@ pub fn blaze_anim(s: &State, p: &mut Poses) {
let mut angle = age * PI * -0.1;
for i in 0..4 {
let part = p.get(&format!("part{i}"));
part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).cos();
part[0] = angle.cos() * 9.0;
part[2] = angle.sin() * 9.0;
part[1] = -2.0 + ((i * 2) as f32 + age).mul_add(0.25, 0.0).mcos();
part[0] = angle.mcos() * 9.0;
part[2] = angle.msin() * 9.0;
angle += PI / 2.0;
}
angle = PI / 4.0 + age * PI * 0.03;
for i in 4..8 {
let part = p.get(&format!("part{i}"));
part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).cos();
part[0] = angle.cos() * 7.0;
part[2] = angle.sin() * 7.0;
part[1] = 2.0 + (((i * 2) as f32 + age) * 0.25).mcos();
part[0] = angle.mcos() * 7.0;
part[2] = angle.msin() * 7.0;
angle += PI / 2.0;
}
angle = 0.471_238_94 + age * PI * -0.05;
for i in 8..12 {
let part = p.get(&format!("part{i}"));
part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).cos();
part[0] = angle.cos() * 5.0;
part[2] = angle.sin() * 5.0;
part[1] = 11.0 + ((i as f32 * 1.5 + age) * 0.5).mcos();
part[0] = angle.mcos() * 5.0;
part[2] = angle.msin() * 5.0;
angle += PI / 2.0;
}
p.yrot("head", s.y_rot.to_radians());
@@ -365,7 +366,7 @@ impl Goal for GhastShoot {
}
if self.charge == 20 {
let yaw = m.yaw.to_radians();
let view = [-f64::from(yaw.sin()), f64::from(yaw.cos())];
let view = [-f64::from(yaw.msin()), f64::from(yaw.mcos())];
let half = f64::from(m.height()) * 0.5;
let ty = (t.bounds.min_position().y + t.bounds.max_position().y) * 0.5;
let dir = [
@@ -404,7 +405,7 @@ pub fn ghast_anim(s: &State, p: &mut Poses) {
for i in 0..9 {
let name = format!("tentacle{i}");
if p.has(&name) {
p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).sin() + 0.4);
p.xrot(&name, 0.2 * (s.age * 0.3 + i as f32).msin() + 0.4);
}
}
}
+10 -9
View File
@@ -5,6 +5,7 @@ use super::{
control::MoveKind,
goals::{Cx, Goal, MOVE, TARGET, goal_clone, reduced},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
/// Phantom state in `Extra`: `flag` swooping, `home` the anchor,
@@ -151,9 +152,9 @@ impl CircleAroundAnchor {
]);
self.angle += self.clockwise * 15.0f32.to_radians();
m.extra.vector = [
f64::from(a[0]) + f64::from(self.distance * self.angle.cos()),
f64::from(a[0]) + f64::from(self.distance * self.angle.mcos()),
f64::from(a[1]) + f64::from(-4.0 + self.height),
f64::from(a[2]) + f64::from(self.distance * self.angle.sin()),
f64::from(a[2]) + f64::from(self.distance * self.angle.msin()),
];
}
}
@@ -319,9 +320,9 @@ pub fn move_control(m: &mut Mob) {
let x_rot = -((-dy).atan2(sd) as f32).to_degrees();
m.head_pitch = x_rot;
let move_angle = (m.yaw + 90.0).to_radians();
let tx = f64::from(speed * move_angle.cos()) * (dx / sd2).abs();
let tz = f64::from(speed * move_angle.sin()) * (dz / sd2).abs();
let ty = f64::from(speed * x_rot.to_radians().sin()) * (dy / sd2).abs();
let tx = f64::from(speed * move_angle.mcos()) * (dx / sd2).abs();
let tz = f64::from(speed * move_angle.msin()) * (dz / sd2).abs();
let ty = f64::from(speed * x_rot.to_radians().msin()) * (dy / sd2).abs();
let v = m.velocity;
m.velocity = Vec3::new(
v.x + (tx - v.x) * 0.2,
@@ -336,20 +337,20 @@ pub fn move_control(m: &mut Mob) {
/// `PhantomModel.setupAnim` (flap time offset by the id).
pub fn anim(m: &Mob, s: &super::anim::State, p: &mut super::anim::Poses) {
let flap = (m.id as f32 * 3.0 + s.age) * 7.448_451_f32.to_radians();
let wing = flap.cos() * 16.0f32.to_radians();
let wing = flap.mcos() * 16.0f32.to_radians();
p.zrot("left_wing_base", wing);
p.zrot("left_wing_tip", wing);
p.zrot("right_wing_base", -wing);
p.zrot("right_wing_tip", -wing);
let tail = -(5.0 + (flap * 2.0).cos() * 5.0f32).to_radians();
let tail = -(5.0 + (flap * 2.0).mcos() * 5.0f32).to_radians();
p.xrot("tail_base", tail);
p.xrot("tail_tip", tail);
}
/// The flap sound when a wingbeat begins (`Phantom.isFlapping`).
pub fn flap_sound(m: &Mob, events: &mut Vec<MobEvent>) {
let t = m.id as f32 * 3.0 + m.age as f32;
let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos();
let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).cos();
let a = (t * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos();
let b = ((t + 1.0) * 7.448_451_f32.to_radians() + std::f32::consts::PI).mcos();
if a > 0.0 && b <= 0.0 {
events.push(MobEvent::Sound(
"entity.phantom.flap",
+95 -30
View File
@@ -9,6 +9,7 @@ use super::{
NearestTarget, Prey, RandomLookAround, Stroll, goal_clone,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -251,48 +252,112 @@ pub fn hoglin_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
};
cx.events.push(MobEvent::Sound(sound, m.center(), 1.0, 1.0));
}
/// `AbstractPiglinModel.setupAnim`: the ears flap around their default angle
/// (30 degrees for adults, 5 for babies).
pub fn ears(p: &mut Poses, s: &State) {
use horizon_core::geometry::trig::DEG_TO_RAD;
let default = if s.baby { 5.0 } else { 30.0 } * DEG_TO_RAD;
let freq = s.age * 0.1 + s.pos * 0.5;
let amp = 0.08 + s.speed * 0.4;
p.zrot("left_ear", -default - (freq * 1.2).mcos() * amp);
p.zrot("right_ear", default + freq.mcos() * amp);
}
/// Piglins' and brutes' ears flap (`AbstractPiglinModel`), arms follow the
/// arm pose (`PiglinModel`).
pub fn piglin_anim(m: &Mob, s: &State, p: &mut Poses) {
super::anim::humanoid_item(p, s, m.extra.main_hand.is_some());
let default = PI / 6.0;
let freq = s.age * 0.1 + s.pos * 0.5;
let amp = 0.08 + s.speed * 0.4;
p.zrot("left_ear", -default - (freq * 1.2).cos() * amp);
p.zrot("right_ear", default + freq.cos() * amp);
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
if m.extra.using_item > 0 {
// ADMIRING_ITEM: head down at the left hand.
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
let pose = if m.extra.using_item > 0 {
PiglinPose::AdmiringItem
} else if m.extra.flag {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
let a = (m.extra.using_item as f32).clamp(0.0, 25.0) / 25.0;
p.yrot("left_arm", 0.4 + 0.45 * a);
p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a);
PiglinPose::CrossbowCharge
} else if m.extra.main_hand.as_deref() == Some("minecraft:crossbow") && m.ai.aggressive {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
} else if m.ai.aggressive && m.extra.main_hand.is_some() && s.swing == 0.0 {
p.xrot("right_arm", -1.8);
PiglinPose::CrossbowHold
} else if m.ai.aggressive && m.extra.main_hand.is_some() {
PiglinPose::MeleeWeapon
} else {
PiglinPose::Default
};
piglin_pose(p, s, pose, 25.0, m.extra.using_item as f32);
}
/// `PiglinArmPose`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PiglinPose {
Default,
Dancing,
MeleeWeapon,
CrossbowHold,
CrossbowCharge,
AdmiringItem,
}
/// `PiglinModel.setupAnim` for a piglin facing right-handed.
pub fn piglin_pose(p: &mut Poses, s: &State, pose: PiglinPose, max_charge: f32, ticks: f32) {
use super::anim::{ArmPose, Hum, humanoid};
let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty);
h.weapon_swing = pose == PiglinPose::MeleeWeapon;
h.charge = (max_charge, ticks);
humanoid(p, s, &h);
ears(p, s);
let (hy, hx) = (s.y_rot.to_radians(), s.x_rot.to_radians());
let rad = |v: f64| v as f32;
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
match pose {
PiglinPose::Dancing => {
let dance = s.age / 60.0;
p.zrot(
"right_ear",
rad(std::f64::consts::PI / 6.0) + deg * (dance * 30.0).msin() * 10.0,
);
p.zrot(
"left_ear",
rad(-std::f64::consts::PI / 6.0) - deg * (dance * 30.0).mcos() * 10.0,
);
p.get("head")[0] += (dance * 10.0).msin();
p.get("head")[1] += (dance * 40.0).msin() + 0.4;
let z = deg * (70.0 + (dance * 40.0).mcos() * 10.0);
p.zrot("right_arm", z);
p.zrot("left_arm", -z);
p.get("right_arm")[1] += (dance * 40.0).msin() * 0.5 - 0.5;
p.get("left_arm")[1] += (dance * 40.0).msin() * 0.5 + 0.5;
p.get("body")[1] += (dance * 40.0).msin() * 0.35;
}
PiglinPose::MeleeWeapon if s.swing == 0.0 => p.xrot("right_arm", -1.8),
PiglinPose::CrossbowHold => {
p.yrot("right_arm", -0.3 + hy);
p.yrot("left_arm", 0.6 + hy);
p.xrot("right_arm", -PI / 2.0 + hx + 0.1);
p.xrot("left_arm", -1.5 + hx);
}
PiglinPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
p.xrot("left_arm", -0.970_796_35);
let alpha = ticks.clamp(0.0, max_charge) / max_charge;
p.yrot("left_arm", 0.4 + alpha * (0.85 - 0.4));
let x = -0.970_796_35 + alpha * (-PI / 2.0 - -0.970_796_35);
p.xrot("left_arm", x);
}
PiglinPose::AdmiringItem => {
p.xrot("head", 0.5);
p.yrot("head", 0.0);
p.yrot("left_arm", 0.5);
p.xrot("left_arm", -0.9);
}
_ => {}
}
}
/// `HoglinModel.setupAnim`.
pub fn hoglin_anim(m: &Mob, s: &State, p: &mut Poses) {
let (pos, sp) = (s.pos, s.speed);
p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.sin());
p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.sin());
p.zrot("right_ear", -PI * 2.0 / 9.0 - sp * pos.msin());
p.zrot("left_ear", PI * 2.0 / 9.0 + sp * pos.msin());
p.yrot("head", s.y_rot.to_radians());
let remaining = m.extra.anim_ticks as f32;
let f = 1.0 - (10.0 - 2.0 * remaining).abs() / 10.0;
p.xrot("head", 0.872_664_63 + (-PI / 9.0 - 0.872_664_63) * f);
p.xrot("right_front_leg", pos.cos() * 1.2 * sp);
p.xrot("left_front_leg", (pos + PI).cos() * 1.2 * sp);
p.xrot("right_hind_leg", (pos + PI).cos() * 1.2 * sp);
p.xrot("left_hind_leg", pos.cos() * 1.2 * sp);
if s.baby {
p.get("head")[1] += f * 2.5;
}
p.xrot("right_front_leg", pos.mcos() * 1.2 * sp);
p.xrot("left_front_leg", (pos + PI).mcos() * 1.2 * sp);
p.xrot("right_hind_leg", (pos + PI).mcos() * 1.2 * sp);
p.xrot("left_hind_leg", pos.mcos() * 1.2 * sp);
}
+14 -12
View File
@@ -7,6 +7,7 @@ use super::{
goals::{Float, HurtByTarget, LookAtPlayer, MeleeAttack, NearestTarget, Stroll},
path::PathType,
};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
@@ -134,9 +135,9 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
events.push(MobEvent::Particles {
kind: "entity_effect",
at: [
m.position.x - width * f64::from(yaw.sin()),
m.position.x - width * f64::from(yaw.msin()),
m.position.y + f64::from(m.height()) - 0.3,
m.position.z + width * f64::from(yaw.cos()),
m.position.z + width * f64::from(yaw.mcos()),
],
count: 0,
});
@@ -225,34 +226,35 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let neck_x_rot = p.get("neck")[3];
let neck = p.get("neck");
neck[2] = -6.5 + head;
neck[1] = -7.0 - head * neck_x_rot.sin();
neck[1] = -7.0 - head * neck_x_rot.msin();
let mouth = if attack > 5.0 {
((-4.0 + attack) / 4.0).sin() * PI * 0.4
((-4.0 + attack) / 4.0).msin() * PI * 0.4
} else {
PI / 20.0 * (PI * attack / 10.0).sin()
PI / 20.0 * (PI * attack / 10.0).msin()
};
p.xrot("mouth", mouth);
} else {
let is_stunned = stunned > 0.0;
let x_rot: f32 = if is_stunned { 0.219_911_49 } else { 0.0 };
let neck = p.get("neck");
let y_offset = -neck[3].msin();
neck[0] = 0.0;
neck[1] = -7.0 + x_rot.sin();
neck[1] = -7.0 - y_offset;
neck[2] = 5.5;
neck[3] = x_rot;
p.xrot("mouth", PI * if is_stunned { 0.05 } else { 0.01 });
if is_stunned {
p.get("neck")[0] = ((stunned / 40.0) * 10.0).sin() * 3.0;
p.get("neck")[0] = ((f64::from(stunned) / 40.0) * 10.0).sin() as f32 * 3.0;
} else if m.extra.anim_ticks > 0 {
let roar = (20.0 - m.extra.anim_ticks as f32 + s.partial) / 20.0;
p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).sin());
p.xrot("mouth", PI / 2.0 * (roar * PI * 0.25).msin());
}
}
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
let (pos, leg) = (s.pos, 0.4 * s.speed);
p.xrot("right_hind_leg", (pos * 0.6662).cos() * leg);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * leg);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * leg);
p.xrot("left_front_leg", (pos * 0.6662).cos() * leg);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * leg);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * leg);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * leg);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * leg);
}
+4 -3
View File
@@ -8,6 +8,7 @@ use super::{
living::wrap,
};
use crate::mesher::Vertex;
use horizon_core::geometry::trig::Mth;
use std::f32::consts::PI;
/// A texture lookup into the shared atlas (name without namespace -> uv rect).
@@ -667,7 +668,7 @@ fn species_scale(m: &Mob, alpha: f32) -> glam::Mat4 {
let s = ((m.previous_swell as f32 + (m.swell - m.previous_swell) as f32 * alpha)
/ 28.0)
.clamp(0.0, 1.0);
let wobble = 1.0 + (s * 100.0).sin() * s * 0.01;
let wobble = 1.0 + (s * 100.0).msin() * s * 0.01;
let s4 = s * s * s * s;
let xz = (1.0 + s4 * 0.4) * wobble;
let y = (1.0 + s4 * 0.1) / wobble;
@@ -699,10 +700,10 @@ pub fn draw(
p[3],
))
* glam::Mat4::from_scale(glam::Vec3::new(p[6], p[7], p[8]));
if p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
if poses.is_hidden(part) || p[6] == 0.0 && p[7] == 0.0 && p[8] == 0.0 {
return;
}
for poly in &part.polygons {
for poly in part.polygons.iter().filter(|_| !poses.skips(part)) {
for v in poly.vertices {
let pos = m.transform_point3(glam::Vec3::new(v[0], v[1], v[2]) / 16.0);
out.push(Vertex {
+5 -4
View File
@@ -11,6 +11,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileWorld, STEPS};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -20,7 +21,7 @@ use std::f32::consts::PI;
// Shulker state: `variant3` the attach face (3D data value), `counter` the
// raw peek (0..100), `color` the shell colour (16 none). AnimState slot 0
// the current peek amount.
const PEEK: usize = 0;
pub const PEEK: usize = 0;
pub const NO_COLOR: u8 = 16;
pub fn register(m: &mut Mob) {
@@ -335,14 +336,14 @@ pub fn rotations(m: &Mob) -> glam::Mat4 {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
let peek = m.anim.lerp(PEEK, s.partial);
let bs = (0.5 + peek) * PI;
let q = -1.0 + bs.sin();
let q = -1.0 + bs.msin();
let extra = if bs > PI {
(s.age * 0.1).sin() * 0.7
(s.age * 0.1).msin() * 0.7
} else {
0.0
};
let lid = p.get("lid");
lid[1] = 16.0 + bs.sin() * 8.0 + extra;
lid[1] = 16.0 + bs.msin() * 8.0 + extra;
lid[4] = if peek > 0.3 {
q * q * q * q * PI * 0.125
} else {
@@ -1221,6 +1221,9 @@ impl Def {
Species::Hoglin => &["hoglin_baby"],
Species::Zoglin => &["zoglin_baby"],
Species::Strider => &["strider_baby"],
Species::Camel => &["camel_baby"],
Species::ZombieHorse => &["zombie_horse_baby"],
Species::SkeletonHorse => &["skeleton_horse_baby"],
_ => &[],
};
v.extend_from_slice(extra);
+73 -37
View File
@@ -10,6 +10,7 @@ use super::{
reduced,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{
geometry::{Aabb, Vec3},
random::RandomSource,
@@ -54,8 +55,8 @@ pub fn wolf_variant_for(biome: &str, has_tag: &dyn Fn(&str) -> bool) -> u8 {
pub const RED: u8 = 14;
// AnimState slots: begging interest and the shake animation.
const INTEREST: usize = 0;
const SHAKE: usize = 1;
pub const INTEREST: usize = 0;
pub const SHAKE: usize = 1;
pub fn register(m: &mut Mob) {
m.extra.color = RED;
@@ -537,7 +538,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.anim.vo[SHAKE] = 0.0;
}
if m.anim.v[SHAKE] > 0.4 {
let count = (((m.anim.v[SHAKE] - 0.4) * PI).sin() * 7.0) as u32;
let count = (((m.anim.v[SHAKE] - 0.4) * PI).msin() * 7.0) as u32;
if count > 0 {
events.push(MobEvent::Particles {
kind: "splash",
@@ -576,7 +577,7 @@ fn tail_angle(m: &Mob) -> f32 {
/// `WolfRenderState.getBodyRollAngle`.
fn body_roll(shake: f32, offset: f32) -> f32 {
let p = ((shake + offset) / 1.8).clamp(0.0, 1.0);
(p * PI).sin() * (p * PI * 11.0).sin() * 0.15 * PI
(p * PI).msin() * (p * PI * 11.0).msin() * 0.15 * PI
}
/// `WolfModel.setupAnim` with the adult and baby overrides.
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
@@ -585,7 +586,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
if angry(m) {
p.yrot("tail", 0.0);
} else {
p.yrot("tail", (pos * 0.6662).cos() * 1.4 * speed);
p.yrot("tail", (pos * 0.6662).mcos() * 1.4 * speed);
}
if m.extra.sitting {
let age = if baby { 0.5 } else { 1.0 };
@@ -615,10 +616,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("upper_body", 0.0);
}
} else {
p.xrot("right_hind_leg", (pos * 0.6662).cos() * 1.4 * speed);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * 1.4 * speed);
p.xrot("left_front_leg", (pos * 0.6662).cos() * 1.4 * speed);
p.xrot("right_hind_leg", (pos * 0.6662).mcos() * 1.4 * speed);
p.xrot("left_hind_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * 1.4 * speed);
p.xrot("left_front_leg", (pos * 0.6662).mcos() * 1.4 * speed);
}
// shakeOffWater
let shake = m.anim.lerp(SHAKE, s.partial);
@@ -946,26 +947,39 @@ pub fn cat_rotations(m: &Mob, partial: f32) -> glam::Mat4 {
glam::Mat4::from_translation(glam::Vec3::new(0.4 * lie, 0.15 * lie, 0.1 * lie))
* glam::Mat4::from_rotation_z((90.0 * lie).to_radians())
}
/// `Mth.rotLerp`: degrees-wrapping, applied by the feline models to radians.
fn rot_lerp(t: f32, from: f32, to: f32) -> f32 {
let mut d = (to - from) % (PI * 2.0);
if d < -PI {
d += PI * 2.0;
}
if d >= PI {
d -= PI * 2.0;
}
from + t * d
from + t * super::living::wrap(to - from)
}
/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats.
/// `FelineRenderState` values the feline models read.
#[derive(Clone, Copy, Debug, Default)]
pub struct Feline {
pub crouching: bool,
pub sprinting: bool,
pub sitting: bool,
pub lie_down: f32,
pub lie_down_tail: f32,
pub relax_one: f32,
}
/// `AdultFelineModel` / `BabyFelineModel.setupAnim` for cats and ocelots.
pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
let baby = m.is_baby();
let age = if baby { 0.5 } else { 1.0 };
let wanted = m.ai.mov.has_wanted();
let speed_mod = m.ai.mov.speed_modifier;
// Cat.customServerAiStep: crouch while stalking, sprint while dashing.
let crouching = wanted && (speed_mod - 0.6).abs() < 1e-6;
let sprinting = wanted && (speed_mod - 1.33).abs() < 1e-6;
let sitting = cat_sitting(m);
let st = Feline {
crouching: wanted && (speed_mod - 0.6).abs() < 1e-6,
sprinting: wanted && (speed_mod - 1.33).abs() < 1e-6,
sitting: cat_sitting(m),
lie_down: m.anim.lerp(LIE, s.partial),
lie_down_tail: m.anim.lerp(LIE_TAIL, s.partial),
relax_one: m.anim.lerp(RELAX, s.partial),
};
feline(p, s, &st);
}
pub fn feline(p: &mut Poses, s: &State, st: &Feline) {
let baby = s.baby;
let age = if baby { 0.5 } else { 1.0 };
let (crouching, sprinting, sitting) = (st.crouching, st.sprinting, st.sitting);
let add = |p: &mut Poses, part: &str, x: f32, y: f32, z: f32| {
let v = p.get(part);
v[0] += x;
@@ -994,18 +1008,18 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("body", PI / 2.0);
}
if sprinting {
p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).cos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).cos() * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.cos() * sp);
p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + 0.3).mcos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI + 0.3).mcos() * sp);
p.xrot("right_front_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("tail2", 1.727_876_1 + PI / 10.0 * pos.mcos() * sp);
} else {
p.xrot("left_hind_leg", (pos * 0.6662).cos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI).cos() * sp);
p.xrot("right_front_leg", (pos * 0.6662).cos() * sp);
p.xrot("left_hind_leg", (pos * 0.6662).mcos() * sp);
p.xrot("right_hind_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("left_front_leg", (pos * 0.6662 + PI).mcos() * sp);
p.xrot("right_front_leg", (pos * 0.6662).mcos() * sp);
let swing = if crouching { 0.471_238_94 } else { PI / 4.0 };
p.xrot("tail2", 1.727_876_1 + swing * pos.cos() * sp);
p.xrot("tail2", 1.727_876_1 + swing * pos.mcos() * sp);
}
} else if baby {
let x = p.get("body")[3] - 0.436_332_32;
@@ -1034,9 +1048,31 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("right_hind_leg", -PI / 2.0);
add(p, "right_hind_leg", 0.0, 3.0 * age, -4.0 * age);
}
let lie = m.anim.lerp(LIE, s.partial);
let lie_tail = m.anim.lerp(LIE_TAIL, s.partial);
if lie > 0.0 && !baby {
let lie = st.lie_down;
let lie_tail = st.lie_down_tail;
if lie > 0.0 && baby {
add(p, "body", 1.0, 0.0, 0.0);
let hx = p.get("head")[3];
p.xrot("head", rot_lerp(lie, hx, PI / 18.0));
let hz = p.get("head")[5];
p.zrot("head", rot_lerp(lie, hz, -PI * 5.0 / 12.0));
add(p, "head", 1.5, 0.75, -0.5);
p.xrot("right_front_leg", -PI / 4.0);
add(p, "right_front_leg", 3.5, -0.5, 0.0);
p.xrot("left_front_leg", -PI / 2.0);
add(p, "left_front_leg", 1.5, -1.0, -2.0);
p.xrot("right_hind_leg", PI * 2.0 / 9.0);
p.yrot("right_hind_leg", PI / 9.0);
p.zrot("right_hind_leg", -PI / 9.0);
add(p, "right_hind_leg", 2.5, -0.25, 0.5);
add(p, "left_hind_leg", 1.5, 0.0, -1.0);
let t = p.get("tail1");
let (tx, ty, tz) = (t[3], t[4], t[5]);
p.xrot("tail1", tx + rot_lerp(lie_tail, tx, -PI / 6.0));
p.yrot("tail1", ty + rot_lerp(lie_tail, ty, 0.0));
p.zrot("tail1", tz + rot_lerp(lie_tail, tz, -PI / 18.0));
add(p, "tail1", 1.0, 0.5, -0.25);
} else if lie > 0.0 {
let (hz, hy) = (p.get("head")[5], p.get("head")[4]);
p.zrot("head", rot_lerp(lie, hz, -1.270_796_3));
p.yrot("head", rot_lerp(lie, hy, 1.270_796_3));
@@ -1052,7 +1088,7 @@ pub fn cat_anim(m: &Mob, s: &State, p: &mut Poses) {
p.xrot("tail1", rot_lerp(lie_tail, t1, 0.8));
p.xrot("tail2", rot_lerp(lie_tail, t2, -0.4));
}
let relax = m.anim.lerp(RELAX, s.partial);
let relax = st.relax_one;
if relax > 0.0 {
let hx = p.get("head")[3];
p.xrot("head", rot_lerp(relax, hx, -0.581_776_44));
+26 -6
View File
@@ -9,6 +9,7 @@ use super::{
Cx, Float, Goal, HurtByTarget, LookAtPlayer, MOVE, NearestTarget, goal_clone, reduced,
},
};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::f32::consts::PI;
@@ -224,19 +225,38 @@ pub fn ai_step(m: &mut Mob, w: &super::MobWorld) {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
let bob = (s.age * 5.5).to_radians().cos() * 0.1;
let bob = (s.age * 5.5 * horizon_core::geometry::trig::DEG_TO_RAD).mcos() * 0.1;
p.zrot("right_arm", PI / 5.0 + bob);
p.zrot("left_arm", -(PI / 5.0 + bob));
if m.extra.flag {
p.xrot("body", 0.0);
// Holding the sword in the right hand.
p.xrot("right_arm", PI * 7.0 / 6.0);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
// setArmsCharging
let (right, left) = (m.extra.main_hand.is_some(), m.extra.off_hand.is_some());
if !right && !left {
p.xrot("right_arm", -1.221_730_5);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
p.xrot("left_arm", -1.221_730_5);
p.yrot("left_arm", -PI / 12.0);
p.zrot("left_arm", 0.471_238_88 + bob);
} else {
let sword = (std::f64::consts::PI * 7.0 / 6.0) as f32;
if right {
p.xrot("right_arm", sword);
p.yrot("right_arm", PI / 12.0);
p.zrot("right_arm", -0.471_238_88 - bob);
}
if left {
p.xrot("left_arm", sword);
p.yrot("left_arm", -PI / 12.0);
p.zrot("left_arm", 0.471_238_88 + bob);
}
}
} else {
p.xrot("body", PI / 20.0);
}
let wing = 1.099_557_4 + (s.age * 45.836_624).to_radians().cos() * 16.2_f32.to_radians();
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
let wing = 1.099_557_4 + (s.age * 45.836_624 * deg).mcos() * deg * 16.2;
p.yrot("left_wing", wing);
p.yrot("right_wing", -wing);
p.xrot("left_wing", 0.471_238_88);
+4 -3
View File
@@ -13,6 +13,7 @@ use super::{
},
};
use crate::items::ItemStack;
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::{collections::HashMap, f32::consts::PI};
@@ -603,16 +604,16 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", if awake { s.y_rot.to_radians() } else { 0.0 });
p.xrot("head", if awake { s.x_rot.to_radians() } else { 0.0 });
if m.extra.ints[0] > 0 {
p.zrot("head", 0.3 * (0.45 * s.age).sin());
p.zrot("head", 0.3 * (0.45 * s.age).msin());
p.xrot("head", 0.4);
} else {
p.zrot("head", 0.0);
}
let leg = (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5;
let leg = (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5;
p.xrot("right_leg", leg);
p.xrot(
"left_leg",
(s.pos * 0.6662 + PI).cos() * 1.4 * s.speed * 0.5,
(s.pos * 0.6662 + PI).mcos() * 1.4 * s.speed * 0.5,
);
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
+6 -10
View File
@@ -9,6 +9,7 @@ use super::{
},
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
pub fn register(m: &mut Mob) {
@@ -258,20 +259,15 @@ pub fn ai_step(m: &mut Mob, cx_events: &mut Vec<MobEvent>, target_far: bool) {
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("head", s.y_rot.to_radians());
p.xrot("head", s.x_rot.to_radians());
p.xrot("right_leg", (s.pos * 0.6662).cos() * 1.4 * s.speed * 0.5);
p.xrot("right_leg", (s.pos * 0.6662).mcos() * 1.4 * s.speed * 0.5);
p.xrot(
"left_leg",
(s.pos * 0.6662 + std::f32::consts::PI).cos() * 1.4 * s.speed * 0.5,
(s.pos * 0.6662 + std::f32::consts::PI).mcos() * 1.4 * s.speed * 0.5,
);
let speed = 0.01 * (m.id % 10) as f32;
p.xrot(
"nose",
(s.age * speed).sin() * 4.5 * std::f32::consts::PI / 180.0,
);
p.zrot(
"nose",
(s.age * speed).cos() * 2.5 * std::f32::consts::PI / 180.0,
);
let deg = horizon_core::geometry::trig::DEG_TO_RAD;
p.xrot("nose", (s.age * speed).msin() * 4.5 * deg);
p.zrot("nose", (s.age * speed).mcos() * 2.5 * deg);
if m.extra.main_hand.is_some() {
let n = p.get("nose");
n[0] = 0.0;
+6 -5
View File
@@ -13,6 +13,7 @@ use super::{
nav::NavKind,
};
use crate::projectiles::{Projectile, ProjectileKind};
use horizon_core::geometry::trig::Mth;
use horizon_core::{geometry::Vec3, random::RandomSource};
// Wither state: `counter` the invulnerable ticks, `counter2` the block
@@ -102,9 +103,9 @@ fn head_pos(m: &Mob, i: usize) -> [f64; 3] {
}
let a = (m.body_yaw + 180.0 * (i as f32 - 1.0)).to_radians();
[
m.position.x + f64::from(a.cos()) * 1.3,
m.position.x + f64::from(a.mcos()) * 1.3,
m.position.y + 2.2,
m.position.z + f64::from(a.sin()) * 1.3,
m.position.z + f64::from(a.msin()) * 1.3,
]
}
/// `performRangedAttack`: a skull from a head toward a point.
@@ -348,13 +349,13 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot(head, (y - body).to_radians());
p.xrot(head, x.to_radians());
}
let anim = (s.age * 0.1).cos();
let anim = (s.age * 0.1).mcos();
let rib = (0.065 + 0.05 * anim) * std::f32::consts::PI;
p.xrot("ribcage", rib);
let tail = p.get("tail");
tail[0] = -2.0;
tail[1] = 6.9 + rib.cos() * 10.0;
tail[2] = -0.5 + rib.sin() * 10.0;
tail[1] = 6.9 + rib.mcos() * 10.0;
tail[2] = -0.5 + rib.msin() * 10.0;
p.xrot("tail", (0.265 + 0.1 * anim) * std::f32::consts::PI);
p.yrot("center_head", s.y_rot.to_radians());
p.xrot("center_head", s.x_rot.to_radians());
+14
View File
@@ -23,6 +23,20 @@ pub fn cos(angle: f64) -> f32 {
sine_table()[((angle * SCALE + 16384.0) as i64 & 65535) as usize]
}
/// `Mth.sin` / `Mth.cos` on a float, as the models call them.
pub trait Mth {
fn msin(self) -> f32;
fn mcos(self) -> f32;
}
impl Mth for f32 {
fn msin(self) -> f32 {
sin(f64::from(self))
}
fn mcos(self) -> f32 {
cos(f64::from(self))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -0,0 +1,196 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import net.minecraft.SharedConstants;
import net.minecraft.client.model.EntityModel;
import net.minecraft.client.model.geom.LayerDefinitions;
import net.minecraft.client.model.geom.ModelLayerLocation;
import net.minecraft.client.model.geom.ModelPart;
import net.minecraft.client.renderer.entity.state.EntityRenderState;
import net.minecraft.server.Bootstrap;
/**
* Original oracle for the client's entity model animation: bakes each vanilla model layer, builds
* its own render state class with the given walk/age/head/attack values plus optional extra
* fields, runs the real setupAnim and writes every part's pose.
*
* Input lines: "layer-key ModelClass|case-json" where case-json is an object of state field
* name to value. Output lines: {layer, case, parts:{path:[x,y,z,xRot,yRot,zRot,xScale,yScale,zScale,visible]}}.
*/
public final class VanillaEntityAnimOracle {
private static Field cubes;
private static Field children;
@SuppressWarnings("unchecked")
private static void dump(String path, ModelPart part, JsonObject out) throws Exception {
var pose = new JsonArray();
for (float f : new float[] {part.x, part.y, part.z, part.xRot, part.yRot, part.zRot, part.xScale, part.yScale, part.zScale})
pose.add(f);
pose.add(part.visible && !part.skipDraw ? 1 : 0);
int polys = 0;
double sum = 0;
for (ModelPart.Cube cube : (List<ModelPart.Cube>) cubes.get(part)) {
for (ModelPart.Polygon polygon : cube.polygons) {
polys++;
for (ModelPart.Vertex v : polygon.vertices()) {
float u = Float.isFinite(v.u()) ? v.u() : 0.0F, w = Float.isFinite(v.v()) ? v.v() : 0.0F;
sum += v.x() + 2.0 * v.y() + 3.0 * v.z() + 5.0 * u + 7.0 * w;
}
}
}
pose.add(polys);
pose.add(sum);
out.add(path, pose);
for (var entry : ((Map<String, ModelPart>) children.get(part)).entrySet())
dump(path.isEmpty() ? entry.getKey() : path + "/" + entry.getKey(), entry.getValue(), out);
}
private static Class<?> findClass(String simple) throws Exception {
for (String pkg : new String[] {"net.minecraft.client.model"}) {
// Search subpackages by trying every known class location through the jar index.
for (String name : CLASS_NAMES) {
if (name.endsWith("." + simple) || name.equals(simple)) return Class.forName(name);
}
}
throw new ClassNotFoundException(simple);
}
private static final List<String> CLASS_NAMES = new ArrayList<>();
private static Class<?> raw(java.lang.reflect.Type t, Map<java.lang.reflect.TypeVariable<?>, java.lang.reflect.Type> env) {
if (t instanceof Class<?> c) return c;
if (t instanceof java.lang.reflect.ParameterizedType p) return raw(p.getRawType(), env);
if (t instanceof java.lang.reflect.TypeVariable<?> v) {
var bound = env.get(v);
return raw(bound != null ? bound : v.getBounds()[0], env);
}
throw new IllegalArgumentException("cannot resolve " + t);
}
/** The render state class: the model's `S`, resolved through its generic superclasses. */
private static Class<?> stateClass(Class<?> model) {
var env = new HashMap<java.lang.reflect.TypeVariable<?>, java.lang.reflect.Type>();
Class<?> current = model;
for (var v : current.getTypeParameters()) env.put(v, raw(v.getBounds()[0], env));
while (current != net.minecraft.client.model.Model.class) {
var sup = current.getGenericSuperclass();
if (sup instanceof java.lang.reflect.ParameterizedType p) {
var params = ((Class<?>) p.getRawType()).getTypeParameters();
for (int i = 0; i < params.length; i++) env.put(params[i], raw(p.getActualTypeArguments()[i], env));
current = (Class<?>) p.getRawType();
} else {
current = (Class<?>) sup;
}
}
return raw(net.minecraft.client.model.Model.class.getTypeParameters()[0], env);
}
private static Field field(Class<?> type, String name) {
for (Class<?> c = type; c != null; c = c.getSuperclass()) {
try {
return c.getDeclaredField(name);
} catch (NoSuchFieldException e) {
}
}
return null;
}
private static void set(Object state, String name, JsonElement value) throws Exception {
boolean optional = name.startsWith("?") || Set.of("walkAnimationPos", "walkAnimationSpeed", "yRot", "xRot", "isBaby", "swingAnimation", "ageScale", "ageInTicks", "entityId", "yHeadRot", "yBodyRot", "eatTick", "flapOffset", "interest").contains(name);
if (name.startsWith("?")) name = name.substring(1);
Field f = field(state.getClass(), name);
if (f == null && optional) return;
if (f == null) throw new IllegalArgumentException("no field " + name + " on " + state.getClass());
f.setAccessible(true);
Class<?> t = f.getType();
if (t == float.class) f.setFloat(state, value.getAsFloat());
else if (t == int.class) f.setInt(state, value.getAsInt());
else if (t == double.class) f.setDouble(state, value.getAsDouble());
else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean());
else if (t.isEnum()) {
for (Object c : t.getEnumConstants()) if (((Enum<?>) c).name().equals(value.getAsString())) f.set(state, c);
} else if (t.getSimpleName().equals("AnimationState")) {
// value = age in ticks since start (negative = stopped)
var a = (net.minecraft.world.entity.AnimationState) f.get(state);
a.stop();
if (value.getAsJsonPrimitive().isNumber()) a.start(value.getAsInt());
} else throw new IllegalArgumentException("unsupported type " + t + " for " + name);
}
/** Render-state values vanilla derives from entity state; the case gives the entity-side input. */
private static void hooks(EntityRenderState state, JsonObject kase) {
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();
float a = 0.0F;
sheep.headEatPositionScale = t <= 0 ? 0.0F : t >= 4 && t <= 36 ? 1.0F : t < 4 ? (t - a) / 4.0F : -(t - 40 - a) / 4.0F;
if (t > 4 && t <= 36) {
float scale = (t - 4 - a) / 32.0F;
sheep.headEatAngleScale = (float) (Math.PI / 5) + 0.21991149F * net.minecraft.util.Mth.sin(scale * 28.7F);
} else {
sheep.headEatAngleScale = t > 0 ? (float) (Math.PI / 5) : sheep.xRot * (float) (Math.PI / 180.0);
}
}
if (state instanceof net.minecraft.client.renderer.entity.state.WolfRenderState wolf && kase.has("interest"))
wolf.headRollAngle = kase.get("interest").getAsFloat() * 0.15F * (float) Math.PI;
if (state instanceof net.minecraft.client.renderer.entity.state.PhantomRenderState phantom && kase.has("flapOffset"))
phantom.flapTime = kase.get("flapOffset").getAsFloat() + phantom.ageInTicks;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion();
Bootstrap.bootStrap();
cubes = ModelPart.class.getDeclaredField("cubes");
cubes.setAccessible(true);
children = ModelPart.class.getDeclaredField("children");
children.setAccessible(true);
try (var zip = new java.util.zip.ZipFile(args[2])) {
zip.stream().map(e -> e.getName()).filter(n -> n.startsWith("net/minecraft/client/model/") && n.endsWith(".class"))
.forEach(n -> CLASS_NAMES.add(n.substring(0, n.length() - 6).replace('/', '.')));
}
var roots = LayerDefinitions.createRoots();
var byName = new HashMap<String, ModelLayerLocation>();
for (var key : roots.keySet()) byName.put(key.toString(), key);
var gson = new Gson();
var out = new StringBuilder();
for (String line : Files.readAllLines(Path.of(args[0]))) {
if (line.isBlank()) continue;
var halves = line.split("\\|", 2);
var head = halves[0].split(" ");
var layer = head[0];
var kase = JsonParser.parseString(halves[1]).getAsJsonObject();
var result = new JsonObject();
result.addProperty("layer", layer);
result.add("case", kase);
try {
var location = byName.get(layer);
if (location == null) throw new IllegalArgumentException("no layer " + layer);
var cls = findClass(head[1]);
var baked = roots.get(location).bakeRoot();
var model = (net.minecraft.client.model.Model<EntityRenderState>) cls.getConstructor(ModelPart.class).newInstance(baked);
var type = stateClass(cls);
var state = (EntityRenderState) type.getDeclaredConstructor().newInstance();
state.getClass();
for (var entry : kase.entrySet()) set(state, entry.getKey(), entry.getValue());
hooks(state, kase);
if (state instanceof net.minecraft.client.renderer.entity.state.ArmedEntityRenderState armed && armed.swingAnimation > 0)
armed.currentSwing = new net.minecraft.world.entity.LivingEntity.SwingDescription(net.minecraft.world.InteractionHand.MAIN_HAND, net.minecraft.world.item.component.SwingAnimation.DEFAULT, 6);
model.setupAnim(state);
var parts = new JsonObject();
dump("", baked, parts);
result.add("parts", parts);
} catch (Throwable error) {
var cause = error.getCause() != null ? error.getCause() : error;
result.addProperty("error", cause.toString());
}
out.append(gson.toJson(result)).append('\n');
}
Files.writeString(Path.of(args[1]), out.toString(), StandardCharsets.UTF_8);
}
}
+296
View File
@@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""Compare entity model geometry and setupAnim poses with the vanilla 26.3 client.
The Java oracle bakes each vanilla model layer, builds the model's own render
state class with the generated walk/age/head/attack inputs (plus per-species
state fields), runs the real `setupAnim` and writes every part's pose.
`examples/entity_anim_fixture` replays the same inputs through Horizon's
`mobs::anim::setup` and the loaded model tree; the two must agree on every part
pose and on the baked polygon count and vertex sums.
test_entity_model_parity.py [--filter SUBSTRING] [--detail LAYER] [--tolerance EPS]
"""
import argparse
import json
import math
import os
from pathlib import Path
import random
import re
import subprocess
import sys
try:
from . import lab, test_rust_parity as base, test_model_baking_parity as baking
except ImportError:
import lab, test_rust_parity as base, test_model_baking_parity as baking
CLIENT = lab.LOCAL / 'minecraft' / '26.3' / 'sources' / 'client' / 'net' / 'minecraft' / 'client'
# Models that no renderer builds with a plain `new Model(context.bakeLayer(CONSTANT))`.
EXTRAS = [
('minecraft:zombie#main', 'ZombieModel'), ('minecraft:zombie_baby#main', 'BabyZombieModel'),
('minecraft:husk#main', 'ZombieModel'), ('minecraft:husk_baby#main', 'BabyZombieModel'),
('minecraft:zombie_villager#main', 'ZombieVillagerModel'),
('minecraft:zombie_villager_baby#main', 'BabyZombieVillagerModel'),
('minecraft:zombified_piglin#main', 'AdultZombifiedPiglinModel'),
('minecraft:zombified_piglin_baby#main', 'BabyZombifiedPiglinModel'),
('minecraft:skeleton#main', 'SkeletonModel'), ('minecraft:stray#main', 'SkeletonModel'),
('minecraft:wither_skeleton#main', 'SkeletonModel'),
('minecraft:spider#main', 'SpiderModel'), ('minecraft:cave_spider#main', 'SpiderModel'),
('minecraft:enderman#main', 'EndermanModel'), ('minecraft:endermite#main', 'EndermiteModel'),
('minecraft:piglin#main', 'AdultPiglinModel'), ('minecraft:piglin_brute#main', 'AdultPiglinModel'),
('minecraft:piglin_baby#main', 'BabyPiglinModel'),
('minecraft:hoglin#main', 'HoglinModel'), ('minecraft:zoglin#main', 'HoglinModel'),
('minecraft:hoglin_baby#main', 'BabyHoglinModel'), ('minecraft:zoglin_baby#main', 'BabyHoglinModel'),
('minecraft:guardian#main', 'GuardianModel'), ('minecraft:elder_guardian#main', 'GuardianModel'),
('minecraft:evoker#main', 'IllagerModel'), ('minecraft:illusioner#main', 'IllagerModel'),
('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'),
('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'),
('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'),
('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'),
('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'),
('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'),
('minecraft:skeleton_horse_baby#main', 'BabyHorseModel'), ('minecraft:zombie_horse_baby#main', 'BabyHorseModel'),
('minecraft:cave_spider#main', 'SpiderModel'),
('minecraft:stray#main', 'SkeletonModel'),
]
# Layers a renderer reuses for another entity under a different constant.
SKIP_LAYERS = re.compile(r'(banner|bell|book|skull|head|chest|shulker_box|boat|cushion|conduit|leash|arrow|trident|'
r'shield|elytra|spin_attack|ears|cape|decorated_pot|minecart|wind_charge|evoker_fangs|'
r'llama_spit|shulker_bullet|bee_stinger|end_crystal|armor_stand|copper_golem|#(helmet|chestplate|leggings|'
r'boots|outer|armor|decor|saddle|collar|wool|wool_undercoat|eyes|wind|inner|pattern|tendrils|'
r'heart|bioluminescent|pulsating_spots|water_patch|flag|cage|shell)$)')
def layer_constant(name):
"""minecraft:cow_baby#main -> constant COW_BABY (the main layer of a model)."""
return name.split(':')[1].split('#')[0].upper()
def renderer_pairs():
pairs = {}
pattern = re.compile(r'new (\w+)\(\s*(?:context|this\.context|\w*)\.bakeLayer\(ModelLayers\.(\w+)\)')
for path in sorted((CLIENT / 'renderer').rglob('*.java')):
for match in pattern.finditer(path.read_text()):
pairs[match.group(2)] = match.group(1)
return pairs
def layers(models):
chosen = {}
pairs = renderer_pairs()
for key in models:
if not key.endswith('#main') or SKIP_LAYERS.search(key):
continue
constant = layer_constant(key)
if constant in pairs:
chosen[key] = pairs[constant]
for key, cls in EXTRAS:
if key in models:
chosen[key] = cls
return chosen
def cases(layer):
rng = random.Random(0x414e494d + sum(map(ord, layer)))
baby = '_baby#' in layer
base_cases = [
(0.0, 0.0, 0.0, 0.0, 0.0, 0.0),
(1.0, 0.5, 10.0, 0.0, 0.0, 0.0),
(3.7, 0.6, 57.3, 20.0, -15.0, 0.0),
(12.25, 1.0, 123.5, -35.0, 40.0, 0.0),
(7.5, 0.3, 33.3, 5.0, 5.0, 0.35),
(2.0, 0.0, 77.7, 45.0, -60.0, 0.8),
]
for _ in range(14):
base_cases.append((rng.uniform(0, 30), rng.uniform(0, 1), rng.uniform(0, 400),
rng.uniform(-50, 50), rng.uniform(-70, 70),
rng.choice([0.0, rng.uniform(0.01, 0.99)])))
cases_out = []
for pos, speed, age, y, x, attack in base_cases:
cases_out.append({'walkAnimationPos': pos, 'walkAnimationSpeed': speed, 'ageInTicks': age,
'yRot': y, 'xRot': x, 'swingAnimation': attack, 'isBaby': baby, 'ageScale': 0.5 if baby else 1.0,
'entityId': 7, 'yHeadRot': y, 'yBodyRot': 0.0})
name = layer.split(':')[1].split('#')[0].removesuffix('_baby')
cases_out = [{**c, **DEFAULTS.get(name, {})} for c in cases_out]
yield from cases_out
yield from species_cases(layer, cases_out)
T, F = True, False
FOX = [{'isCrouching': T, 'crouchAmount': 0.8}, {'isSleeping': T}, {'isSitting': T}, {'isPouncing': T, 'crouchAmount': 0.6},
{'isFaceplanted': T}, {'headRollAngle': 0.3}, {'isCrouching': T, 'isPouncing': T, 'crouchAmount': 0.4}]
ILLAGER = [{'armPose': pose, 'maxCrossbowChargeDuration': 25, 'ticksUsingItem': 10.0}
for pose in ['NEUTRAL', 'CROSSED', 'ATTACKING', 'SPELLCASTING', 'BOW_AND_ARROW', 'CROSSBOW_HOLD',
'CROSSBOW_CHARGE', 'CELEBRATING']] + [{'isRiding': T, 'armPose': 'CROSSED'}]
FELINE = [{'isCrouching': T}, {'isSprinting': T}, {'isSitting': T}, {'lieDownAmount': 0.7, 'lieDownAmountTail': 0.5},
{'relaxStateOneAmount': 0.6}, {'isSitting': T, 'lieDownAmount': 1.0, 'lieDownAmountTail': 0.2}]
ZOMBIE = [{'isAggressive': T}, {'isCrouching': T}, {'isPassenger': T}, {'isAggressive': T, 'isPassenger': T, 'isCrouching': T}]
SKELETON = ZOMBIE + [{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW'}, {'isHoldingBow': T},
{'isAggressive': T, 'isHoldingBow': T, 'rightArmPose': 'BOW_AND_ARROW', 'isCrouching': T}]
PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem': 12.0}
for pose in ['DEFAULT', 'DANCING', 'ATTACKING_WITH_MELEE_WEAPON', 'CROSSBOW_HOLD', 'CROSSBOW_CHARGE', 'ADMIRING_ITEM']]
EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7},
{'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}]
WATER = [{'isInWater': T}, {'isInWater': F}]
SPECIES = {
'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE,
'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}],
'hoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)],
'zoglin': [{'attackAnimationRemainingTicks': t} for t in (3, 7, 10)],
'ravager': [{'stunnedTicksRemaining': 20.0}, {'attackTicksRemaining': 8.0}, {'attackTicksRemaining': 3.0},
{'roarAnimation': 0.5}],
'vex': [{'isCharging': T}, {'isCharging': F}],
'squid': [{'tentacleAngle': 0.7}], 'glow_squid': [{'tentacleAngle': 1.2}],
'dolphin': [{'isMoving': T}, {'isMoving': F}],
'cod': WATER, 'salmon': WATER, 'tropical_fish_small': WATER,
'allay': [{'isDancing': T, 'isSpinning': T, 'spinningProgress': 0.6}, {'isDancing': T, 'isSpinning': F, 'spinningProgress': 0.2},
{'holdingAnimationProgress': 0.8}, {'holdingAnimationProgress': 1.0}],
'camel': [{'sitAnimationState': 2}, {'sitPoseAnimationState': 3}, {'sitUpAnimationState': 1}, {'idleAnimationState': 4},
{'dashAnimationState': 2}, {'jumpCooldown': 20.0}],
'chicken': [{'flap': 2.0, 'flapSpeed': 0.7}, {'flap': 5.3, 'flapSpeed': 1.0}],
'wolf': [{'isSitting': T}, {'isAngry': T, 'tailAngle': 1.5393804}, {'shakeAnim': 0.9}, {'interest': 0.6},
{'isSitting': T, 'shakeAnim': 0.5, 'interest': 0.3}],
'zombie': ZOMBIE, 'husk': ZOMBIE, 'drowned': ZOMBIE, 'zombie_villager': ZOMBIE, 'zombified_piglin': ZOMBIE, 'giant': ZOMBIE,
'skeleton': SKELETON, 'stray': SKELETON, 'wither_skeleton': SKELETON, 'bogged': SKELETON,
'piglin': PIGLIN, 'piglin_brute': PIGLIN,
'cat': FELINE, 'ocelot': FELINE,
'creaking': [{'canMove': F}, {'attackAnimationState': 2}, {'invulnerabilityAnimationState': 3}, {'deathAnimationState': 1}],
'evoker': ILLAGER, 'pillager': ILLAGER, 'vindicator': ILLAGER,
'sheep': [{'eatTick': t} for t in (2, 10, 36, 39)],
'guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}, {'tailAnimation': 0.0, 'spikesAnimation': 0.0}],
'elder_guardian': [{'tailAnimation': 4.0, 'spikesAnimation': 0.3}],
'shulker': [{'peekAmount': v} for v in (0.0, 0.2, 0.5, 1.0)],
'witch': [{'isHoldingItem': T}, {'isHoldingItem': F}],
'goat': [{'hasLeftHorn': T, 'hasRightHorn': T}, {'hasLeftHorn': F, 'hasRightHorn': T, 'rammingXHeadRot': 0.6},
{'hasLeftHorn': T, 'hasRightHorn': F}],
'polar_bear': [{'standScale': 0.0}, {'standScale': 0.5}, {'standScale': 1.0}],
'panda': [{'isUnhappy': T}, {'isSneezing': T, 'sneezeTime': 5}, {'isSneezing': T, 'sneezeTime': 16},
{'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3},
{'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}],
'llama': [{'hasChest': T}, {'hasChest': F}],
'trader_llama': [{'hasChest': T}, {'hasChest': F}],
'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}],
'strider': [{'isRidden': T}, {'isRidden': F}],
'parrot': [{'pose': pose, 'flapAngle': 0.4} for pose in ['STANDING', 'FLYING', 'ON_SHOULDER', 'SITTING', 'PARTY']],
'bee': [{'hasStinger': T}, {'hasStinger': F, 'isOnGround': T}, {'isAngry': T}, {'rollAmount': 0.6, 'isAngry': T},
{'isOnGround': T, 'hasStinger': T}],
'bat': [{'isResting': T, 'restAnimationState': 3}, {'flyAnimationState': 2}, {'isResting': F, 'flyAnimationState': 0}],
'armadillo': [{'isHidingInShell': T}, {'isHidingInShell': T, 'rollUpAnimationState': 2},
{'rollOutAnimationState': 4}, {'peekAnimationState': 1}],
'axolotl': [{'playingDeadFactor': 0.0, 'inWaterFactor': 1.0, 'onGroundFactor': 0.0, 'movingFactor': 1.0},
{'inWaterFactor': 1.0, 'movingFactor': 0.0}, {'onGroundFactor': 1.0, 'movingFactor': 1.0},
{'onGroundFactor': 1.0, 'movingFactor': 0.0}, {'inWaterFactor': 0.5, 'onGroundFactor': 0.5, 'movingFactor': 0.5},
{'playingDeadFactor': 1.0, 'inWaterFactor': 1.0},
{'walkAnimationState': 1}, {'swimAnimation': 2}, {'idleOnGroundAnimationState': 3},
{'idleUnderWaterAnimationState': 2}, {'idleUnderWaterOnGroundAnimationState': 1}, {'playDeadAnimationState': 4}],
'frog': [{'isSwimming': T}, {'isSwimming': F}, {'jumpAnimationState': 2}, {'croakAnimationState': 1},
{'tongueAnimationState': 3}, {'swimIdleAnimationState': 2, 'isSwimming': T}],
'rabbit': [{'hopAnimationState': 2}, {'idleHeadTiltAnimationState': 1}],
'fox': FOX,
}
# Render-state defaults that are not zero/false in vanilla.
DEFAULTS = {'creaking': {'canMove': T}, 'wolf': {'tailAngle': 0.6283185307179586}, 'axolotl': {'inWaterFactor': 1.0}, 'bee': {'hasStinger': T}, 'sheep': {'eatTick': 0},
'goat': {'hasLeftHorn': T, 'hasRightHorn': T}, 'parrot': {'pose': 'STANDING'},
'phantom': {'flapOffset': 21.0}, 'guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0},
'elder_guardian': {'tailAnimation': 1.3, 'spikesAnimation': 1.0}}
def species_cases(layer, base_cases):
name = layer.split(':')[1].split('#')[0].removesuffix('_baby')
for extra in SPECIES.get(name, []):
for index in (2, 3, 6):
yield {**base_cases[index], **extra}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--filter', default='')
parser.add_argument('--detail', default='')
parser.add_argument('--tolerance', type=float, default=5e-7)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
build = lab.LOCAL / 'rust-entity-model-parity'; build.mkdir(parents=True, exist_ok=True)
resources = lab.LOCAL / 'horizon-client' / '26.3'
models = json.loads((resources / 'entity-models.json').read_text())
chosen = {k: v for k, v in layers(models).items() if args.filter in k}
extra_cases = json.loads((Path(__file__).with_suffix('.cases.json')).read_text()) \
if Path(__file__).with_suffix('.cases.json').exists() else {}
lines = []
for layer, cls in sorted(chosen.items()):
for case in cases(layer):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
for case in extra_cases.get(layer.split(':')[1].split('#')[0], []):
lines.append(f'{layer} {cls}|{json.dumps(case)}')
inputs = build / 'inputs.txt'; inputs.write_text('\n'.join(lines) + '\n')
classes = build / 'classes'; classes.mkdir(exist_ok=True)
oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaEntityAnimOracle.java'
dependencies = os.pathsep.join(map(str, [jars['client'], *libraries]))
def run(command, name):
with (build / (name + '.log')).open('w') as log:
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log, stderr=subprocess.STDOUT)
if result.returncode:
print((build / (name + '.log')).read_text()[-4000:]); sys.exit(f'{name} failed')
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-cp', dependencies, '-d', classes, oracle], 'compile-java')
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaEntityAnimOracle',
inputs, build / 'vanilla.jsonl', jars['client']], 'vanilla')
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example', 'entity_anim_fixture', '--',
resources, build / 'vanilla.jsonl', build / 'rust.jsonl'], 'rust')
vanilla = [json.loads(l) for l in (build / 'vanilla.jsonl').read_text().splitlines()]
rust = [json.loads(l) for l in (build / 'rust.jsonl').read_text().splitlines()]
assert len(vanilla) == len(rust), (len(vanilla), len(rust))
errors, skipped, mismatched, checked = {}, set(), {}, 0
for v, r in zip(vanilla, rust):
layer = v['layer']
if 'error' in v:
errors[layer] = v['error']; continue
if 'skip' in r:
skipped.add(layer); continue
checked += 1
bad = []
for path, expected in v['parts'].items():
got = r['parts'].get(path)
if got is None:
bad.append((path, 'missing in Horizon')); continue
names = ['x', 'y', 'z', 'xRot', 'yRot', 'zRot', 'xScale', 'yScale', 'zScale', 'visible', 'polys', 'vsum']
for i, (a, b) in enumerate(zip(expected, got)):
if i == 11 and abs(a - b) <= 1e-3 * max(1, abs(a)):
continue
if i == 9:
a, b = bool(a), bool(b)
if a != b:
bad.append((path, f'visible {a} != {b}'))
continue
if abs(a - b) > args.tolerance * (1.0 + abs(a)):
bad.append((path, f'{names[i]} {a!r} != {b!r}'))
for path in r['parts']:
if path not in v['parts']:
bad.append((path, 'extra in Horizon'))
if bad:
mismatched.setdefault(layer, []).append((v['case'], bad))
print(f'{checked} cases compared over {len(chosen) - len(skipped) - len(errors)} layers')
if errors:
print('oracle errors:'); [print(' ', k, v) for k, v in sorted(errors.items())]
if skipped:
print('layers without a Horizon species:', ', '.join(sorted(skipped)))
for layer, items in sorted(mismatched.items()):
parts = {}
for case, bad in items:
for path, why in bad:
parts.setdefault(path, (why, case))
total = sum(1 for x in vanilla if x['layer'] == layer)
print(f'MISMATCH {layer}: {len(items)}/{total} cases, {len(parts)} parts')
detailed = args.detail == layer
for path, (why, case) in list(parts.items())[:(10 ** 6 if detailed else 4)]:
print(f' {path or "<root>"}: {why}' + (f' case={json.dumps(case)}' if detailed else ''))
if mismatched or errors:
sys.exit(f'{len(mismatched)} layers differ from vanilla')
print('entity model parity ok')
if __name__ == '__main__':
main()