Animate remote squid bodies and tentacles from server velocity
Run the client branch of Squid.aiStep, preserve authoritative movement and synchronize tentacle-cycle resets with entity event 19. Co-Authored-By: OpenAI GPT-6.1 Sol <noreply@openai.com>
This commit is contained in:
@@ -83,6 +83,7 @@ mod sound_engine_fixture;
|
||||
mod sound_event_fixture;
|
||||
mod spawn_rules_fixture;
|
||||
mod sprint_probe;
|
||||
mod squid_client_probe;
|
||||
mod subtitle_fixture;
|
||||
mod tab_list_fixture;
|
||||
mod team_rules_fixture;
|
||||
@@ -107,6 +108,7 @@ probes! {
|
||||
block_transform_fixture,
|
||||
breaking_fixture,
|
||||
camera_probe,
|
||||
squid_client_probe,
|
||||
cauldron_fixture,
|
||||
chat_screen_fixture,
|
||||
cloud_fixture,
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
use horizon_client::{
|
||||
Result,
|
||||
mobs::{Mob, MobTypes, aquatic},
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
path::Path,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
pub fn main() -> Result<()> {
|
||||
let args: Vec<_> = crate::args().collect();
|
||||
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3");
|
||||
let types = MobTypes::load(&root)?;
|
||||
let mut out = BufWriter::new(File::create(&args[2])?);
|
||||
for line in BufReader::new(File::open(&args[1])?).lines() {
|
||||
let row: Value = serde_json::from_str(&line?)?;
|
||||
let kind = Arc::new(
|
||||
types.types[&format!("minecraft:{}", row["species"].as_str().unwrap())].clone(),
|
||||
);
|
||||
let mut mob = Mob::new(1, kind, Vec3::ZERO, 0.0);
|
||||
mob.fluids.in_water = row["water"].as_bool().unwrap();
|
||||
mob.velocity = Vec3::new(
|
||||
row["x"].as_f64().unwrap(),
|
||||
row["y"].as_f64().unwrap(),
|
||||
row["z"].as_f64().unwrap(),
|
||||
);
|
||||
mob.body_yaw = row["body"].as_f64().unwrap() as f32;
|
||||
for (i, value) in row["v"].as_array().unwrap().iter().enumerate() {
|
||||
mob.anim.v[i] = value.as_f64().unwrap() as f32;
|
||||
}
|
||||
if row["reset"].as_bool().unwrap() {
|
||||
aquatic::squid_cycle_event(&mut mob);
|
||||
}
|
||||
let velocity = mob.velocity;
|
||||
aquatic::squid_client_step(&mut mob);
|
||||
assert_eq!(
|
||||
velocity, mob.velocity,
|
||||
"a remote animation must preserve packet velocity"
|
||||
);
|
||||
write!(out, "{:08x}", mob.body_yaw.to_bits())?;
|
||||
for value in &mob.anim.v[..6] {
|
||||
write!(out, " {:08x}", value.to_bits())?;
|
||||
}
|
||||
writeln!(out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -810,6 +810,7 @@ impl Game<'_> {
|
||||
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
|
||||
for e in events {
|
||||
match e {
|
||||
MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at),
|
||||
MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at),
|
||||
MobEvent::Sound(name, at, volume, pitch)
|
||||
| MobEvent::LocalSound(name, at, volume, pitch) => {
|
||||
|
||||
@@ -2174,6 +2174,11 @@ impl Game<'_> {
|
||||
{
|
||||
horizon_client::mobs::rabbit::hop_event(m);
|
||||
}
|
||||
if p.event == 19
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
{
|
||||
horizon_client::mobs::aquatic::squid_cycle_event(m);
|
||||
}
|
||||
// EntityEvent.DEATH: start the death animation.
|
||||
if p.event == 3
|
||||
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
|
||||
@@ -3581,6 +3586,8 @@ impl Game<'_> {
|
||||
} else if m.alive() {
|
||||
m.body_rotation_tick();
|
||||
}
|
||||
// Squid.aiStep follows LivingEntity's interpolation and head turn.
|
||||
horizon_client::mobs::aquatic::squid_client_step(m);
|
||||
// WalkAnimationState.update from the horizontal distance moved.
|
||||
let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z);
|
||||
let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0);
|
||||
|
||||
@@ -868,6 +868,11 @@ pub struct Mob {
|
||||
/// Events a mob tick asks the game to act on.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum MobEvent {
|
||||
/// Squid.handleEntityEvent(19), resetting the remote tentacle cycle.
|
||||
SquidCycle {
|
||||
mob: u32,
|
||||
at: [f64; 3],
|
||||
},
|
||||
/// Rabbit entity event 1, sent only when a ground jump actually happens.
|
||||
RabbitHop {
|
||||
mob: u32,
|
||||
|
||||
@@ -234,12 +234,40 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
/// Squid.aiStep: tentacle cycle, propulsion and body rotation.
|
||||
fn squid_ai_step(m: &mut Mob) {
|
||||
squid_step(m, false);
|
||||
}
|
||||
|
||||
/// Squid.aiStep also runs on remote entities: animate from packet velocity,
|
||||
/// without running goals or replacing that velocity with the server's movement vector.
|
||||
pub fn squid_client_step(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
|
||||
m.anim.vo = m.anim.v;
|
||||
squid_step(m, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Squid.handleEntityEvent(19): begin the next server-synchronised tentacle cycle.
|
||||
pub fn squid_cycle_event(m: &mut Mob) {
|
||||
if matches!(m.species(), Species::Squid | Species::GlowSquid) {
|
||||
m.anim.v[TENTACLE_MOVEMENT] = 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
fn squid_step(m: &mut Mob, client: bool) {
|
||||
let v = &mut m.anim.v;
|
||||
v[TENTACLE_MOVEMENT] += v[TENTACLE_SPEED];
|
||||
if v[TENTACLE_MOVEMENT] > PI * 2.0 {
|
||||
v[TENTACLE_MOVEMENT] -= PI * 2.0;
|
||||
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
if f64::from(v[TENTACLE_MOVEMENT]) > std::f64::consts::TAU {
|
||||
if client {
|
||||
v[TENTACLE_MOVEMENT] = PI * 2.0;
|
||||
} else {
|
||||
v[TENTACLE_MOVEMENT] -= PI * 2.0;
|
||||
if m.random.next_int_bound(10).unwrap_or(1) == 0 {
|
||||
m.anim.v[TENTACLE_SPEED] = 1.0 / (m.random.next_float() + 1.0) * 0.2;
|
||||
}
|
||||
m.outbox.push(MobEvent::SquidCycle {
|
||||
mob: m.id,
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
});
|
||||
}
|
||||
}
|
||||
let v = &mut m.anim.v;
|
||||
@@ -248,28 +276,39 @@ fn squid_ai_step(m: &mut Mob) {
|
||||
let scale = v[TENTACLE_MOVEMENT] / PI;
|
||||
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]);
|
||||
if !client {
|
||||
let mv = m.extra.vector;
|
||||
m.velocity = Vec3::new(mv[0], mv[1], mv[2]);
|
||||
}
|
||||
m.anim.v[ROTATE_SPEED] = 1.0;
|
||||
} else {
|
||||
m.anim.v[ROTATE_SPEED] *= 0.8;
|
||||
}
|
||||
} else {
|
||||
v[TENTACLE_ANGLE] = 0.0;
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
if !client {
|
||||
m.velocity = Vec3::new(m.velocity.x * 0.9, m.velocity.y * 0.9, m.velocity.z * 0.9);
|
||||
}
|
||||
m.anim.v[ROTATE_SPEED] *= 0.99;
|
||||
}
|
||||
let mv = m.velocity;
|
||||
let horizontal = (mv.x * mv.x + mv.z * mv.z).sqrt();
|
||||
m.body_yaw += (-(mv.x.atan2(mv.z) as f32).to_degrees() - m.body_yaw) * 0.1;
|
||||
m.body_yaw += (-(horizon_core::geometry::trig::atan2(mv.x, mv.z) as f32) * 57.295776
|
||||
- m.body_yaw)
|
||||
* 0.1;
|
||||
m.yaw = m.body_yaw;
|
||||
let v = &mut m.anim.v;
|
||||
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;
|
||||
v[X_BODY_ROT] += (-(horizon_core::geometry::trig::atan2(horizontal, mv.y) as f32)
|
||||
* 57.295776
|
||||
- v[X_BODY_ROT])
|
||||
* 0.1;
|
||||
} else {
|
||||
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);
|
||||
if !client {
|
||||
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;
|
||||
v[X_BODY_ROT] += (-90.0 - v[X_BODY_ROT]) * 0.02;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.JsonParser;
|
||||
import java.io.PrintWriter;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.world.effect.MobEffect;
|
||||
import net.minecraft.world.entity.*;
|
||||
import net.minecraft.world.entity.animal.squid.Squid;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.phys.AABB;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** Runs the real Squid.aiStep, with unrelated movement/world services controlled. */
|
||||
public final class VanillaSquidClientOracle {
|
||||
static Field field(Class<?> owner, String name) throws Exception {
|
||||
var f = owner.getDeclaredField(name); f.setAccessible(true); return f;
|
||||
}
|
||||
static final class Shell extends Squid {
|
||||
Level world; boolean water;
|
||||
Shell() { super(EntityTypes.SQUID, null); }
|
||||
@Override public Level level() { return world; }
|
||||
@Override public boolean isAgeLocked() { return true; }
|
||||
@Override public boolean isInWater() { return water; }
|
||||
@Override protected boolean isImmobile() { return true; }
|
||||
@Override protected void applyInput() {}
|
||||
@Override public boolean isEffectiveAi() { return false; }
|
||||
@Override public boolean isFallFlying() { return false; }
|
||||
@Override public boolean hasEffect(Holder<MobEffect> effect) { return false; }
|
||||
@Override public LivingEntity getControllingPassenger() { return null; }
|
||||
@Override public void calculateEntityAnimation(boolean flying) {}
|
||||
@Override protected void pushEntities() {}
|
||||
}
|
||||
static String bits(float value) { return String.format("%08x", Float.floatToIntBits(value)); }
|
||||
public static void main(String[] args) throws Exception {
|
||||
net.minecraft.SharedConstants.tryDetectVersion();
|
||||
net.minecraft.server.Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe");
|
||||
var uf = field(u, "theUnsafe"); var unsafe = uf.get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var world = (ClientLevel) allocate.invoke(unsafe, ClientLevel.class);
|
||||
field(Level.class, "isClientSide").setBoolean(world, true);
|
||||
String[] names = {"tentacleMovement", "tentacleAngle", "xBodyRot", "zBodyRot", "tentacleSpeed", "rotateSpeed"};
|
||||
Field[] values = new Field[names.length];
|
||||
for (int i = 0; i < names.length; i++) values[i] = field(Squid.class, names[i]);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1])));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
var row = JsonParser.parseString(line).getAsJsonObject();
|
||||
var m = (Shell) allocate.invoke(unsafe, Shell.class);
|
||||
m.world = world; field(Entity.class, "level").set(m, world); m.water = row.get("water").getAsBoolean();
|
||||
field(Entity.class, "type").set(m, EntityTypes.SQUID);
|
||||
field(LivingEntity.class, "equipment").set(m, new EntityEquipment());
|
||||
field(Entity.class, "interpolationHandler").set(m, Proxy.newProxyInstance(
|
||||
InterpolationHandler.class.getClassLoader(), new Class<?>[]{InterpolationHandler.class},
|
||||
(proxy, method, arguments) -> method.getName().equals("hasActiveInterpolation") ? true : null));
|
||||
m.setBoundingBox(new AABB(0, 0, 0, 1, 1, 1));
|
||||
m.setDeltaMovement(new Vec3(row.get("x").getAsDouble(), row.get("y").getAsDouble(), row.get("z").getAsDouble()));
|
||||
m.yBodyRot = row.get("body").getAsFloat();
|
||||
for (int i = 0; i < names.length; i++) values[i].setFloat(m, row.getAsJsonArray("v").get(i).getAsFloat());
|
||||
if (row.get("reset").getAsBoolean()) m.handleEntityEvent((byte)19);
|
||||
m.aiStep();
|
||||
out.print(bits(m.yBodyRot));
|
||||
for (var f : values) out.print(" " + bits(f.getFloat(m)));
|
||||
out.println();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the real Squid.aiStep client branch and cycle event with Rust."""
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
|
||||
def make_input(build):
|
||||
rng = random.Random(1684)
|
||||
rows = []
|
||||
for species in ('squid', 'glow_squid'):
|
||||
for water in (False, True):
|
||||
for reset in (False, True):
|
||||
for velocity in ((0, 0, 0), (.1, 0, 0), (0, .1, 0),
|
||||
(0, -.1, 0), (0, 0, -.1), (.1, .2, -.3)):
|
||||
for movement in (0, 1, 2.4, 3.14, 4, 6.2, 6.4):
|
||||
rows.append(dict(species=species, water=water, reset=reset,
|
||||
x=velocity[0], y=velocity[1], z=velocity[2],
|
||||
body=rng.uniform(-180, 180),
|
||||
v=[movement, .2, -45, 33, .15, .8]))
|
||||
for _ in range(1000):
|
||||
rows.append(dict(species=rng.choice(('squid', 'glow_squid')), water=True,
|
||||
reset=False, x=rng.uniform(.01, .2), y=rng.uniform(.01, .2),
|
||||
z=rng.uniform(.01, .2), body=rng.uniform(-180, 180),
|
||||
v=[rng.uniform(0, 7), 0, rng.uniform(-90, 90),
|
||||
rng.uniform(0, 180), rng.uniform(.1, .2), rng.random()]))
|
||||
path = build / 'inputs.jsonl'
|
||||
path.write_text(''.join(json.dumps(row) + '\n' for row in rows))
|
||||
return path, len(rows)
|
||||
|
||||
|
||||
def main():
|
||||
harness.differential(
|
||||
'rust-squid-client-parity', 'VanillaSquidClientOracle', 'squid_client_probe',
|
||||
make_input,
|
||||
'Actual Squid.aiStep on a client with controlled inherited movement/world services. '
|
||||
'Checks water/air body rotation and tentacle state, cycle clamping and event 19. '
|
||||
'Glow squid uses the same inherited method; packet dispatch and rendering are separate.',
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/mobs/aquatic.rs'])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user