Merge pull request #91 from ludovic111/fix/particles-63-emitters
Entity particle bursts: five angry villager particles and the other bursts as in vanilla (part of #63)
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
#![forbid(unsafe_code)]
|
||||
//! Runs tools/test_entity_particles_parity.py's entity events through
|
||||
//! `particles::entity_event_burst` and `particles::around_self`.
|
||||
use horizon_client::{Result, particles};
|
||||
use horizon_core::random::{LegacyRandom, RandomSource};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
fs::File,
|
||||
io::{BufRead, BufReader, BufWriter, Write},
|
||||
};
|
||||
|
||||
fn d(v: f64) -> String {
|
||||
format!("{:016x}", v.to_bits())
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut out = BufWriter::new(File::create(&args[2])?);
|
||||
for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() {
|
||||
let c: Value = serde_json::from_str(&line?)?;
|
||||
writeln!(out, "== {n}")?;
|
||||
let mut random = LegacyRandom::new(c["seed"].as_i64().ok_or("seed")?);
|
||||
let feet: [f64; 3] = std::array::from_fn(|i| c["feet"][i].as_f64().unwrap_or(0.0));
|
||||
// EntityDimensions hold floats.
|
||||
let width = f64::from(c["width"].as_f64().unwrap_or(0.0) as f32);
|
||||
let height = f64::from(c["height"].as_f64().unwrap_or(0.0) as f32);
|
||||
let entity = c["entity"].as_str().unwrap_or("");
|
||||
if let Some((kind, burst)) =
|
||||
particles::entity_event_burst(entity, c["event"].as_u64().unwrap_or(0) as u8)
|
||||
{
|
||||
let mut lines = Vec::new();
|
||||
particles::around_self(&mut random, feet, width, height, burst, |p, v| {
|
||||
lines.push(format!(
|
||||
"+ {kind} {} {} {} {} {} {}",
|
||||
d(p[0]),
|
||||
d(p[1]),
|
||||
d(p[2]),
|
||||
d(v[0]),
|
||||
d(v[1]),
|
||||
d(v[2])
|
||||
));
|
||||
});
|
||||
for l in lines {
|
||||
writeln!(out, "{l}")?;
|
||||
}
|
||||
}
|
||||
writeln!(out, "next {}", random.next_long())?;
|
||||
}
|
||||
out.flush()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -139,21 +139,9 @@ impl Game<'_> {
|
||||
{
|
||||
c.extra.egg_time = 6000;
|
||||
}
|
||||
for _ in 0..3 {
|
||||
let r = &mut self.world.random;
|
||||
let p = [
|
||||
at[0] + r.next_double() - 0.5,
|
||||
at[1] + 0.5 + r.next_double() * 0.6,
|
||||
at[2] + r.next_double() - 0.5,
|
||||
];
|
||||
if let Some(ty) = horizon_client::particles::ParticleType::from_name("heart") {
|
||||
self.particles.add(
|
||||
&horizon_client::particles::ParticleOptions::simple(ty),
|
||||
p,
|
||||
[0.0; 3],
|
||||
);
|
||||
}
|
||||
}
|
||||
// Allay.duplicateAllay: entity event 18, three spawnHeartParticle.
|
||||
let id = self.mobs[index].id;
|
||||
self.particles_around_mob(id, "heart", horizon_client::particles::Burst::ALLAY);
|
||||
self.audio
|
||||
.play("minecraft:block.amethyst_block.chime", Some(at), 2.0, 1.0);
|
||||
self.consume_held();
|
||||
|
||||
@@ -909,6 +909,19 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
MobEvent::AroundSelf {
|
||||
kind,
|
||||
feet,
|
||||
width,
|
||||
height,
|
||||
burst,
|
||||
} => self.particles_around(kind, feet, [width, height], burst),
|
||||
MobEvent::ParticleAt { kind, at, velocity } => {
|
||||
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
self.particles.add(&options, at, velocity);
|
||||
}
|
||||
}
|
||||
MobEvent::Experience { at, amount } => self.spawn_orbs(at, amount),
|
||||
MobEvent::EffectPlayer {
|
||||
effect,
|
||||
@@ -1969,11 +1982,6 @@ impl Game<'_> {
|
||||
&& !horizon_client::mobs::tame::angry(m) =>
|
||||
{
|
||||
consume = true;
|
||||
let at = [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
|
||||
m.position.z,
|
||||
];
|
||||
let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0;
|
||||
if tamed {
|
||||
horizon_client::mobs::tame::set_tame(m, true);
|
||||
@@ -1985,7 +1993,12 @@ impl Game<'_> {
|
||||
}
|
||||
// TamableAnimal.spawnTamingParticles.
|
||||
let kind = if tamed { "heart" } else { "smoke" };
|
||||
self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?;
|
||||
// TamableAnimal.spawnTamingParticles (entity event 7 or 6).
|
||||
self.particles_around_mob(
|
||||
self.mobs[index].id,
|
||||
kind,
|
||||
horizon_client::particles::Burst::TAMING,
|
||||
);
|
||||
if tamed {
|
||||
let view = self.mob_entity(&self.mobs[index]);
|
||||
self.trigger_entity("minecraft:tame_animal", "entity", &view);
|
||||
@@ -2045,11 +2058,6 @@ impl Game<'_> {
|
||||
Species::Cat if !m.extra.tame && is_food => {
|
||||
consume = true;
|
||||
m.persistent = true;
|
||||
let at = [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
|
||||
m.position.z,
|
||||
];
|
||||
let tamed = m.random.next_int_bound(3).unwrap_or(1) == 0;
|
||||
if tamed {
|
||||
m.extra.tame = true;
|
||||
@@ -2058,7 +2066,12 @@ impl Game<'_> {
|
||||
}
|
||||
eat = eating_sound(m, &mut self.world.random);
|
||||
let kind = if tamed { "heart" } else { "smoke" };
|
||||
self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?;
|
||||
// TamableAnimal.spawnTamingParticles (entity event 7 or 6).
|
||||
self.particles_around_mob(
|
||||
self.mobs[index].id,
|
||||
kind,
|
||||
horizon_client::particles::Burst::TAMING,
|
||||
);
|
||||
if tamed {
|
||||
let view = self.mob_entity(&self.mobs[index]);
|
||||
self.trigger_entity("minecraft:tame_animal", "entity", &view);
|
||||
@@ -2090,18 +2103,18 @@ impl Game<'_> {
|
||||
let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2;
|
||||
eat = Some(("entity.parrot.eat", 1.0, pitch));
|
||||
}
|
||||
let at = [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
|
||||
m.position.z,
|
||||
];
|
||||
let tamed = m.random.next_int_bound(10).unwrap_or(1) == 0;
|
||||
if tamed {
|
||||
m.extra.tame = true;
|
||||
m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1]));
|
||||
}
|
||||
let kind = if tamed { "heart" } else { "smoke" };
|
||||
self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }])?;
|
||||
// TamableAnimal.spawnTamingParticles (entity event 7 or 6).
|
||||
self.particles_around_mob(
|
||||
self.mobs[index].id,
|
||||
kind,
|
||||
horizon_client::particles::Burst::TAMING,
|
||||
);
|
||||
if tamed {
|
||||
let view = self.mob_entity(&self.mobs[index]);
|
||||
self.trigger_entity("minecraft:tame_animal", "entity", &view);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::{MobEvent, equine, llama},
|
||||
mobs::{equine, llama},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
@@ -45,13 +45,14 @@ impl Game<'_> {
|
||||
m.extra.variant3 = (i32::from(m.extra.variant3) + temper).min(llama::MAX_TEMPER) as u8;
|
||||
used = true;
|
||||
}
|
||||
let at = m.center();
|
||||
if happy {
|
||||
let _ = self.handle_mob_events(vec![MobEvent::Particles {
|
||||
kind: "happy_villager",
|
||||
at,
|
||||
count: 1,
|
||||
}]);
|
||||
// AbstractHorse.handleEating: one at rest about the body.
|
||||
let id = m.id;
|
||||
self.particles_around_mob(
|
||||
id,
|
||||
"happy_villager",
|
||||
horizon_client::particles::Burst::HORSE_EATING,
|
||||
);
|
||||
}
|
||||
if !used {
|
||||
return false;
|
||||
|
||||
@@ -437,16 +437,12 @@ impl Game<'_> {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.extra.owner = owner;
|
||||
m.persistent = true;
|
||||
let at = [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
|
||||
m.position.z,
|
||||
];
|
||||
let _ = self.handle_mob_events(vec![MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at,
|
||||
count: 7,
|
||||
}]);
|
||||
// AbstractHorse.tameWithName: entity event 7, spawnTamingParticles(true).
|
||||
self.particles_around_mob(
|
||||
mob,
|
||||
"heart",
|
||||
horizon_client::particles::Burst::TAMING,
|
||||
);
|
||||
}
|
||||
}
|
||||
MobEvent::Buck { mob } if self.riding == Some(mob) => self.dismount_mount(),
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
items::ItemStack,
|
||||
mobs::{MobEvent, Species, nautilus},
|
||||
mobs::{Species, nautilus},
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
@@ -84,14 +84,14 @@ impl Game<'_> {
|
||||
m.nav_stop();
|
||||
m.ai.target = None;
|
||||
}
|
||||
let at = [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) * 0.5 + 0.5,
|
||||
m.position.z,
|
||||
];
|
||||
let sound = nautilus::eat_sound(m);
|
||||
let kind = if tamed { "heart" } else { "smoke" };
|
||||
let _ = self.handle_mob_events(vec![MobEvent::Particles { kind, at, count: 7 }]);
|
||||
// TamableAnimal.spawnTamingParticles (entity event 7 or 6).
|
||||
self.particles_around_mob(
|
||||
self.mobs[index].id,
|
||||
kind,
|
||||
horizon_client::particles::Burst::TAMING,
|
||||
);
|
||||
self.nautilus_sound(index, sound);
|
||||
if tamed {
|
||||
let view = self.mob_entity(&self.mobs[index]);
|
||||
|
||||
@@ -176,9 +176,10 @@ impl Game<'_> {
|
||||
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
|
||||
let from = self.mobs[ia].position;
|
||||
let Some((bed, variant)) = child else {
|
||||
for i in [ia, ib] {
|
||||
let p = self.mobs[i].position;
|
||||
self.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
|
||||
// VillagerMakeLove: entity event 13 for the partner, then the parent.
|
||||
for i in [ib, ia] {
|
||||
let id = self.mobs[i].id;
|
||||
self.villager_particles(id, "angry_villager");
|
||||
}
|
||||
return;
|
||||
};
|
||||
@@ -202,12 +203,52 @@ impl Game<'_> {
|
||||
child.extra.age = -24000;
|
||||
child.extra.bed = Some(bed);
|
||||
}
|
||||
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
|
||||
// VillagerMakeLove.giveBirth: entity event 12 for the child.
|
||||
self.villager_particles(id, "heart");
|
||||
}
|
||||
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
|
||||
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
self.particles.add(&options, at, [0.0; 3]);
|
||||
/// `Villager.handleEntityEvent` 12, 13, 14 and 42:
|
||||
/// `AbstractVillager.addParticlesAroundSelf`.
|
||||
pub(super) fn villager_particles(&mut self, id: u32, kind: &'static str) {
|
||||
self.particles_around_mob(id, kind, horizon_client::particles::Burst::VILLAGER);
|
||||
}
|
||||
/// `particles::around_self` about mob `id`.
|
||||
pub(super) fn particles_around_mob(
|
||||
&mut self,
|
||||
id: u32,
|
||||
kind: &'static str,
|
||||
burst: horizon_client::particles::Burst,
|
||||
) {
|
||||
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
let feet = [m.position.x, m.position.y, m.position.z];
|
||||
let size = [f64::from(m.width()), f64::from(m.height())];
|
||||
self.particles_around(kind, feet, size, burst);
|
||||
}
|
||||
/// `particles::around_self` on the client: the particle engine's random
|
||||
/// stands in for the client entity's, so no server draw moves.
|
||||
pub(super) fn particles_around(
|
||||
&mut self,
|
||||
kind: &'static str,
|
||||
feet: [f64; 3],
|
||||
size: [f64; 2],
|
||||
burst: horizon_client::particles::Burst,
|
||||
) {
|
||||
let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) else {
|
||||
return;
|
||||
};
|
||||
let options = horizon_client::particles::ParticleOptions::simple(ty);
|
||||
let mut spawned = Vec::new();
|
||||
horizon_client::particles::around_self(
|
||||
self.particles.random(),
|
||||
feet,
|
||||
size[0],
|
||||
size[1],
|
||||
burst,
|
||||
|p, v| spawned.push((p, v)),
|
||||
);
|
||||
for (p, v) in spawned {
|
||||
self.particles.add(&options, p, v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,7 +322,7 @@ impl Game<'_> {
|
||||
}
|
||||
let time = m.ai.last_hurt_by_time;
|
||||
let alive = m.alive();
|
||||
let at = m.position;
|
||||
let at = m.id;
|
||||
let e = villager::ext_mut(m);
|
||||
if e.hurt_seen != time {
|
||||
e.hurt_seen = time;
|
||||
@@ -295,8 +336,9 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
for at in angry {
|
||||
self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]);
|
||||
// Villager.setLastHurtByMob: entity event 13.
|
||||
for id in angry {
|
||||
self.villager_particles(id, "angry_villager");
|
||||
}
|
||||
}
|
||||
/// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a
|
||||
@@ -350,8 +392,8 @@ impl Game<'_> {
|
||||
GossipType::Trading,
|
||||
gossip::REPUTATION_CHANGE_PER_TRADE,
|
||||
);
|
||||
let p = self.mobs[i].position;
|
||||
self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]);
|
||||
// Villager.customServerAiStep after a trade: entity event 14.
|
||||
self.villager_particles(id, "happy_villager");
|
||||
}
|
||||
/// `Villager.getPlayerReputation` of the local player.
|
||||
pub(super) fn villager_reputation(&self, id: u32) -> i32 {
|
||||
|
||||
@@ -933,6 +933,20 @@ pub enum MobEvent {
|
||||
at: [f64; 3],
|
||||
count: u32,
|
||||
},
|
||||
/// Client particles about a mob's box (`particles::around_self`).
|
||||
AroundSelf {
|
||||
kind: &'static str,
|
||||
feet: [f64; 3],
|
||||
width: f64,
|
||||
height: f64,
|
||||
burst: crate::particles::Burst,
|
||||
},
|
||||
/// One particle exactly at `at`, moving at `velocity`.
|
||||
ParticleAt {
|
||||
kind: &'static str,
|
||||
at: [f64; 3],
|
||||
velocity: [f64; 3],
|
||||
},
|
||||
Experience {
|
||||
at: [f64; 3],
|
||||
amount: u32,
|
||||
|
||||
@@ -626,10 +626,11 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
let x = m.position.x + w * (2.0 * r.next_double() - 1.0);
|
||||
let y = m.position.y + h * r.next_double() + 0.5;
|
||||
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
|
||||
// sendParticles(HAPPY_VILLAGER, x, y, z, 1, 0, 0, 0, 0): exactly there, at rest.
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "happy_villager",
|
||||
at: [x, y, z],
|
||||
count: 1,
|
||||
count: 0,
|
||||
});
|
||||
}
|
||||
m.extra.forced_age_timer -= 1;
|
||||
@@ -655,16 +656,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
// The heart's speed and getRandomX/Y/Z, drawn even on the server.
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
let r = &mut m.random;
|
||||
for _ in 0..3 {
|
||||
let _ = r.next_gaussian();
|
||||
}
|
||||
let velocity = [
|
||||
r.next_gaussian() * 0.02,
|
||||
r.next_gaussian() * 0.02,
|
||||
r.next_gaussian() * 0.02,
|
||||
];
|
||||
let x = m.position.x + w * (2.0 * r.next_double() - 1.0);
|
||||
let y = m.position.y + h * r.next_double() + 0.5;
|
||||
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
|
||||
events.push(MobEvent::Particles {
|
||||
events.push(MobEvent::ParticleAt {
|
||||
kind: "heart",
|
||||
at: [x, y, z],
|
||||
count: 1,
|
||||
velocity,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2925,15 +2925,21 @@ impl B {
|
||||
child,
|
||||
});
|
||||
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
|
||||
let mut p = vec![m.position];
|
||||
// Entity event 12 for the partner, then this villager:
|
||||
// AbstractVillager.addParticlesAroundSelf(HEART).
|
||||
let mut bodies = Vec::new();
|
||||
if let Some(t) = cx.w.target_info(target) {
|
||||
p.push(t.position);
|
||||
let (min, max) = (t.bounds.min_position(), t.bounds.max_position());
|
||||
bodies.push((t.position, max.x - min.x, max.y - min.y));
|
||||
}
|
||||
for at in p {
|
||||
cx.events.push(MobEvent::Particles {
|
||||
bodies.push((m.position, f64::from(m.width()), f64::from(m.height())));
|
||||
for (feet, width, height) in bodies {
|
||||
cx.events.push(MobEvent::AroundSelf {
|
||||
kind: "heart",
|
||||
at: [at.x, at.y + 1.8, at.z],
|
||||
count: 1,
|
||||
feet: [feet.x, feet.y, feet.z],
|
||||
width,
|
||||
height,
|
||||
burst: crate::particles::Burst::VILLAGER,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3527,21 +3533,16 @@ fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec<usize> {
|
||||
}
|
||||
/// Entity event 14: the client shows happy particles (with its own random,
|
||||
/// not the mob's).
|
||||
/// Entity event 14 (`AcquirePoi`, `AssignProfessionFromJobSite`):
|
||||
/// `AbstractVillager.addParticlesAroundSelf(HAPPY_VILLAGER)` on the client.
|
||||
fn happy_particles(m: &Mob, cx: &mut Bx) {
|
||||
let mut r = LegacyRandom::new(cx.now ^ i64::from(m.id));
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
for _ in 0..5 {
|
||||
let at = [
|
||||
m.position.x + w * (2.0 * r.next_double() - 1.0),
|
||||
m.position.y + h * r.next_double() + 1.0,
|
||||
m.position.z + w * (2.0 * r.next_double() - 1.0),
|
||||
];
|
||||
cx.events.push(MobEvent::Particles {
|
||||
kind: "happy_villager",
|
||||
at,
|
||||
count: 0,
|
||||
});
|
||||
}
|
||||
cx.events.push(MobEvent::AroundSelf {
|
||||
kind: "happy_villager",
|
||||
feet: [m.position.x, m.position.y, m.position.z],
|
||||
width: f64::from(m.width()),
|
||||
height: f64::from(m.height()),
|
||||
burst: crate::particles::Burst::VILLAGER,
|
||||
});
|
||||
}
|
||||
/// `BehaviorUtils.findSectionClosestToVillage`.
|
||||
fn closest_section(villages: &[[i32; 3]], center: [i32; 3], radius: i32) -> [i32; 3] {
|
||||
|
||||
@@ -447,6 +447,115 @@ pub fn breaking_position(
|
||||
Some(p)
|
||||
}
|
||||
|
||||
/// A burst of particles about an entity's box (`around_self`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Burst {
|
||||
pub count: u32,
|
||||
/// Scale of the Gaussian speeds; `None` spawns them at rest without drawing any.
|
||||
pub speed: Option<f64>,
|
||||
/// Added to `getRandomY()`.
|
||||
pub y: f64,
|
||||
}
|
||||
impl Burst {
|
||||
/// `AbstractVillager.addParticlesAroundSelf`.
|
||||
pub const VILLAGER: Self = Self {
|
||||
count: 5,
|
||||
speed: Some(0.02),
|
||||
y: 1.0,
|
||||
};
|
||||
/// `TamableAnimal`/`AbstractHorse.spawnTamingParticles`,
|
||||
/// `Ocelot.spawnTrustingParticles`, `Animal`'s entity event 18.
|
||||
pub const TAMING: Self = Self {
|
||||
count: 7,
|
||||
speed: Some(0.02),
|
||||
y: 0.5,
|
||||
};
|
||||
/// `Allay`'s entity event 18: three `spawnHeartParticle`.
|
||||
pub const ALLAY: Self = Self {
|
||||
count: 3,
|
||||
speed: Some(0.02),
|
||||
y: 0.5,
|
||||
};
|
||||
/// `Dolphin.addParticlesAroundSelf`.
|
||||
pub const DOLPHIN: Self = Self {
|
||||
count: 7,
|
||||
speed: Some(0.01),
|
||||
y: 0.2,
|
||||
};
|
||||
/// `AbstractHorse.handleEating`'s growth particle.
|
||||
pub const HORSE_EATING: Self = Self {
|
||||
count: 1,
|
||||
speed: None,
|
||||
y: 0.5,
|
||||
};
|
||||
}
|
||||
/// The particle bursts entity events show on the client: the particle and
|
||||
/// burst of `handleEntityEvent(event)` for the entity type `entity`.
|
||||
pub fn entity_event_burst(entity: &str, event: u8) -> Option<(&'static str, Burst)> {
|
||||
let entity = entity.strip_prefix("minecraft:").unwrap_or(entity);
|
||||
let tamable = matches!(
|
||||
entity,
|
||||
"wolf" | "cat" | "parrot" | "nautilus" | "zombie_nautilus"
|
||||
);
|
||||
let horse = matches!(
|
||||
entity,
|
||||
"horse"
|
||||
| "donkey"
|
||||
| "mule"
|
||||
| "llama"
|
||||
| "trader_llama"
|
||||
| "camel"
|
||||
| "camel_husk"
|
||||
| "skeleton_horse"
|
||||
| "zombie_horse"
|
||||
);
|
||||
Some(match (entity, event) {
|
||||
("villager", 12) => ("heart", Burst::VILLAGER),
|
||||
("villager", 13) => ("angry_villager", Burst::VILLAGER),
|
||||
("villager", 14) => ("happy_villager", Burst::VILLAGER),
|
||||
("villager", 42) => ("splash", Burst::VILLAGER),
|
||||
("allay", 18) => ("heart", Burst::ALLAY),
|
||||
("dolphin", 38) => ("happy_villager", Burst::DOLPHIN),
|
||||
("ocelot", 41) => ("heart", Burst::TAMING),
|
||||
("ocelot", 40) => ("smoke", Burst::TAMING),
|
||||
(_, 7) if tamable || horse => ("heart", Burst::TAMING),
|
||||
(_, 6) if tamable || horse => ("smoke", Burst::TAMING),
|
||||
(_, 18) if !matches!(entity, "villager" | "allay") => ("heart", Burst::TAMING),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Particles about an entity's box, as `AbstractVillager.addParticlesAroundSelf`,
|
||||
/// `Animal`'s love hearts (entity event 18), `TamableAnimal` and
|
||||
/// `AbstractHorse.spawnTamingParticles`, `Ocelot.spawnTrustingParticles`,
|
||||
/// `Allay`'s hearts and `Dolphin.addParticlesAroundSelf` place them: `count`
|
||||
/// times three Gaussian speeds scaled by `speed` (none drawn without one), then
|
||||
/// `getRandomX(1.0)`, `getRandomY() + y` and `getRandomZ(1.0)`.
|
||||
pub fn around_self(
|
||||
random: &mut impl RandomSource,
|
||||
feet: [f64; 3],
|
||||
width: f64,
|
||||
height: f64,
|
||||
burst: Burst,
|
||||
mut emit: impl FnMut([f64; 3], [f64; 3]),
|
||||
) {
|
||||
for _ in 0..burst.count {
|
||||
let v = burst.speed.map_or([0.0; 3], |s| {
|
||||
[
|
||||
random.next_gaussian() * s,
|
||||
random.next_gaussian() * s,
|
||||
random.next_gaussian() * s,
|
||||
]
|
||||
});
|
||||
let p = [
|
||||
feet[0] + width * ((2.0 * random.next_double() - 1.0) * 1.0),
|
||||
feet[1] + height * random.next_double() + burst.y,
|
||||
feet[2] + width * ((2.0 * random.next_double() - 1.0) * 1.0),
|
||||
];
|
||||
emit(p, v);
|
||||
}
|
||||
}
|
||||
|
||||
/// ClientLevel.addDestroyBlockEffect placement and pre-constructor velocities.
|
||||
pub fn destroy_positions(
|
||||
pos: [i32; 3],
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import com.google.gson.*;
|
||||
import java.lang.reflect.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.client.multiplayer.ClientLevel;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.entity.Entity;
|
||||
import net.minecraft.world.entity.EntityDimensions;
|
||||
import net.minecraft.world.entity.animal.allay.Allay;
|
||||
import net.minecraft.world.entity.animal.camel.Camel;
|
||||
import net.minecraft.world.entity.animal.cow.Cow;
|
||||
import net.minecraft.world.entity.animal.dolphin.Dolphin;
|
||||
import net.minecraft.world.entity.animal.equine.Horse;
|
||||
import net.minecraft.world.entity.animal.equine.Llama;
|
||||
import net.minecraft.world.entity.animal.feline.Cat;
|
||||
import net.minecraft.world.entity.animal.feline.Ocelot;
|
||||
import net.minecraft.world.entity.animal.nautilus.Nautilus;
|
||||
import net.minecraft.world.entity.animal.parrot.Parrot;
|
||||
import net.minecraft.world.entity.animal.wolf.Wolf;
|
||||
import net.minecraft.world.entity.npc.villager.Villager;
|
||||
import net.minecraft.world.phys.Vec3;
|
||||
|
||||
/** Calls the real client handleEntityEvent of entities whose events are particle
|
||||
* bursts about their body, and records what they ask the level to spawn. The
|
||||
* entities are allocated without constructors and given only a level stand-in,
|
||||
* a position, dimensions and their random, which is all those handlers read. */
|
||||
public final class VanillaEntityParticlesOracle {
|
||||
static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); }
|
||||
static Field field(Class<?> type, String name) throws Exception {
|
||||
var f = type.getDeclaredField(name); f.setAccessible(true); return f;
|
||||
}
|
||||
static final class Level0 extends ClientLevel {
|
||||
List<String> events;
|
||||
Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); }
|
||||
@Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
|
||||
events.add("+ " + BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()).getPath() + " " + d(x) + " " + d(y) + " " + d(z)
|
||||
+ " " + d(xd) + " " + d(yd) + " " + d(zd));
|
||||
}
|
||||
}
|
||||
static final Map<String, Class<? extends Entity>> TYPES = Map.ofEntries(
|
||||
Map.entry("villager", Villager.class), Map.entry("cow", Cow.class), Map.entry("wolf", Wolf.class),
|
||||
Map.entry("cat", Cat.class), Map.entry("parrot", Parrot.class), Map.entry("horse", Horse.class),
|
||||
Map.entry("llama", Llama.class), Map.entry("camel", Camel.class), Map.entry("ocelot", Ocelot.class),
|
||||
Map.entry("dolphin", Dolphin.class), Map.entry("allay", Allay.class), Map.entry("nautilus", Nautilus.class));
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
SharedConstants.tryDetectVersion(); Bootstrap.bootStrap();
|
||||
var u = Class.forName("sun.misc.Unsafe"); var unsafe = field(u, "theUnsafe").get(null);
|
||||
var allocate = u.getMethod("allocateInstance", Class.class);
|
||||
var level = (Level0) allocate.invoke(unsafe, Level0.class); level.events = new ArrayList<>();
|
||||
Field levelField = field(Entity.class, "level"), position = field(Entity.class, "position"),
|
||||
dimensions = field(Entity.class, "dimensions"), random = field(Entity.class, "random");
|
||||
try (var output = Files.newBufferedWriter(Path.of(args[1]))) {
|
||||
int n = 0;
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
var c = JsonParser.parseString(line).getAsJsonObject();
|
||||
output.write("== " + n++); output.newLine();
|
||||
var entity = (Entity) allocate.invoke(unsafe, TYPES.get(c.get("entity").getAsString()));
|
||||
var feet = c.getAsJsonArray("feet");
|
||||
levelField.set(entity, level);
|
||||
position.set(entity, new Vec3(feet.get(0).getAsDouble(), feet.get(1).getAsDouble(), feet.get(2).getAsDouble()));
|
||||
dimensions.set(entity, EntityDimensions.scalable(c.get("width").getAsFloat(), c.get("height").getAsFloat()));
|
||||
var r = RandomSource.create(c.get("seed").getAsLong());
|
||||
random.set(entity, r);
|
||||
level.events.clear();
|
||||
entity.handleEntityEvent((byte) c.get("event").getAsInt());
|
||||
for (var e : level.events) { output.write(e); output.newLine(); }
|
||||
output.write("next " + r.nextLong()); output.newLine();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the particle bursts entity events show on the client (villagers'
|
||||
hearts, anger and happiness, love hearts, taming and trusting hearts and smoke,
|
||||
the allay's and dolphin's) with the real handleEntityEvent of each entity:
|
||||
particle, count, positions about the body, motion and every random draw."""
|
||||
import json
|
||||
import platform
|
||||
import random
|
||||
import struct
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness, test_rust_parity as base, test_model_baking_parity as baking
|
||||
|
||||
EVENTS = {
|
||||
'villager': [12, 13, 14, 42],
|
||||
'cow': [18], 'wolf': [6, 7, 18], 'cat': [6, 7, 18], 'parrot': [6, 7], 'nautilus': [6, 7, 18],
|
||||
'horse': [6, 7, 18], 'llama': [6, 7, 18], 'camel': [6, 7, 18],
|
||||
'ocelot': [40, 41, 18], 'dolphin': [38], 'allay': [18],
|
||||
}
|
||||
# Dyadic sizes and positions: serde_json's decimal parsing may round others a unit off.
|
||||
SIZES = [(0.6, 1.95), (0.9, 1.4), (0.3, 0.85), (1.3964844, 1.6), (0.35, 0.6), (0.875, 0.9375)]
|
||||
|
||||
|
||||
def cases(rng):
|
||||
for entity, events in EVENTS.items():
|
||||
for event in events:
|
||||
for _ in range(40):
|
||||
w, h = rng.choice(SIZES)
|
||||
feet = [rng.randrange(-4096, 4096) / 64 for _ in range(3)]
|
||||
yield dict(entity=entity, event=event, feet=feet, width=w, height=h,
|
||||
seed=rng.randrange(-2**63, 2**63))
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
path = build / 'cases.jsonl'
|
||||
count = 0
|
||||
with path.open('w') as out:
|
||||
for case in cases(random.Random(0x454e5450)):
|
||||
out.write(json.dumps(case, separators=(',', ':')) + '\n')
|
||||
count += 1
|
||||
return path, count
|
||||
|
||||
|
||||
def close(a, b):
|
||||
"""Lines equal but for doubles within 1e-12 relative error. The motion is
|
||||
Gaussian, and MarsagliaPolarGaussian calls Math.log, which HotSpot's x86-64
|
||||
intrinsic rounds a unit apart from the platform libm horizon_core::jmath
|
||||
uses for a small fraction of arguments."""
|
||||
ta, tb = a.split(), b.split()
|
||||
if len(ta) != len(tb):
|
||||
return False
|
||||
for x, y in zip(ta, tb):
|
||||
if x == y:
|
||||
continue
|
||||
if len(x) != 16 or len(y) != 16:
|
||||
return False
|
||||
fx, fy = (struct.unpack('>d', bytes.fromhex(t))[0] for t in (x, y))
|
||||
if not abs(fx - fy) <= 1e-12 * max(1.0, abs(fx)):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
lock, jars, _ = base.verify_artifacts()
|
||||
name, oracle, probe = 'rust-entity-particles-parity', 'VanillaEntityParticlesOracle', 'entity_particles_probe'
|
||||
build = lab.LOCAL / name
|
||||
build.mkdir(exist_ok=True)
|
||||
report = build / 'report.json'
|
||||
report.unlink(missing_ok=True)
|
||||
sources = [lab.ROOT / p for p in [
|
||||
'tools/test_entity_particles_parity.py', 'tools/oracle_harness.py', 'tools/test_rust_parity.py', 'tools/lab.py',
|
||||
f'mods/horizon/src/test/java/dev/horizonlab/parity/{oracle}.java', 'Cargo.toml', 'Cargo.lock',
|
||||
'crates/horizon-client/Cargo.toml', 'crates/horizon-client/src/particles.rs',
|
||||
f'crates/horizon-client/examples/{probe}.rs', 'crates/horizon-core/src/random.rs']]
|
||||
tested = base.source_hashes(sources)
|
||||
cases_path, units = make_cases(build)
|
||||
classes, dependencies, _ = harness.compile_oracle(build, oracle, jars, baking.client_libraries(),
|
||||
lock['minecraft']['java_major'])
|
||||
binary = harness.build_probe(build, probe)
|
||||
harness.run_logged([binary, cases_path, build / 'rust.txt'], build, 'rust')
|
||||
harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client')
|
||||
vanilla = (build / 'client.txt').read_text().splitlines()
|
||||
rust = (build / 'rust.txt').read_text().splitlines()
|
||||
assert len(vanilla) == len(rust), f'{len(vanilla)} vanilla lines, {len(rust)} Rust lines'
|
||||
tolerated = 0
|
||||
for line, (a, b) in enumerate(zip(vanilla, rust), 1):
|
||||
if a != b:
|
||||
assert close(a, b), f'Parity mismatch at output line {line}: vanilla={a!r}, Rust={b!r}'
|
||||
tolerated += 1
|
||||
particles = sum(line.startswith('+ ') for line in vanilla)
|
||||
assert particles > units, 'too few particles to establish parity'
|
||||
base.ensure_sources_unchanged(sources, tested)
|
||||
lab.write_json(report, dict(
|
||||
schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(),
|
||||
rustc=subprocess.check_output(['rustc', '--version'], text=True).strip(), units=units,
|
||||
sources_sha256=tested, input_sha256=lab.digest(cases_path, 'sha256'),
|
||||
client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=len(vanilla),
|
||||
libm_tolerated_lines=tolerated, output_sha256=lab.digest(build / 'rust.txt', 'sha256'),
|
||||
scope=('The real client handleEntityEvent of Villager (12, 13, 14, 42), Animal (18, love hearts), TamableAnimal '
|
||||
'and AbstractHorse (6, 7, taming), Ocelot (40, 41, trusting), Dolphin (38) and Allay (18), on entities '
|
||||
'allocated with a stand-in level, a position, dimensions and a seeded random: the particle type, '
|
||||
'count, positions, motion and draws on the entity random. Which server code fires each event, and '
|
||||
'the particles themselves once spawned, are covered elsewhere.')))
|
||||
print(f'{units:,} entity events, {particles:,} particles match the pinned client ({tolerated} lines within the '
|
||||
f'Math.log tolerance): {report}', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user