Merge pull request #89 from ludovic111/fix/particles-63-providers

Particles: vanilla random streams, and fixes to 20 providers (part of #63)
This commit is contained in:
Ludovic Marie
2026-10-14 16:08:48 +02:00
committed by GitHub
4 changed files with 986 additions and 82 deletions
@@ -0,0 +1,217 @@
#![forbid(unsafe_code)]
//! Runs tools/test_particle_providers_parity.py's particles through
//! `ParticleEngine`: built with the seeds the vanilla oracle recovered, then
//! ticked over air or a stone floor at y 63, printing their state each tick.
use horizon_client::{
Result,
assets::Assets,
blocks::BlockFacts,
chunk::Chunk,
collisions,
particles::{ParticleEngine, ParticleLevel, ParticleOptions, ParticleSnapshot, ParticleType},
world::World,
};
use serde_json::Value;
use std::{
collections::HashMap,
fs::File,
io::{BufRead, BufReader, BufWriter, Write},
path::Path,
sync::Arc,
};
fn d(v: f64) -> String {
format!("{:016x}", v.to_bits())
}
fn f(v: f32) -> String {
format!("{:08x}", v.to_bits())
}
fn color(v: &Value, default: u32) -> u32 {
v.as_u64().map_or(default, |c| c as u32)
}
fn rgb(c: u32) -> [f32; 3] {
[
((c >> 16) & 255) as f32 / 255.0,
((c >> 8) & 255) as f32 / 255.0,
(c & 255) as f32 / 255.0,
]
}
fn options(case: &Value) -> Option<ParticleOptions> {
let ty = ParticleType::from_name(case["type"].as_str()?)?;
let o = &case["options"];
let scale = o["scale"].as_f64().unwrap_or(1.0) as f32;
let c = color(&o["color"], 0xFFFF_FFFF);
let argb = {
let [r, g, b] = rgb(c);
[r, g, b, ((c >> 24) & 255) as f32 / 255.0]
};
Some(match ty {
ParticleType::Block | ParticleType::BlockCrumble | ParticleType::DustPillar => {
ParticleOptions::block(ty, "terrain".into(), 0xFF_FFFF)
}
// Stone's map colour: FallingDustParticle.Provider's tint without a tint source.
ParticleType::FallingDust => ParticleOptions::block(ty, "terrain".into(), 0x70_7070),
ParticleType::Dust => ParticleOptions::dust(rgb(c), scale),
ParticleType::DustColorTransition => {
ParticleOptions::dust_transition(rgb(c), rgb(color(&o["to"], 0)), scale)
}
ParticleType::Effect | ParticleType::InstantEffect => ParticleOptions {
scale,
..ParticleOptions::colored(ty, argb)
},
ParticleType::EntityEffect | ParticleType::TintedLeaves => {
ParticleOptions::colored(ty, argb)
}
ParticleType::DragonBreath => ParticleOptions {
scale,
..ParticleOptions::simple(ty)
},
ParticleType::SculkCharge => ParticleOptions::sculk_charge(scale),
ParticleType::Shriek => ParticleOptions::shriek(scale as i32),
ParticleType::Trail => {
let t = &o["target"];
ParticleOptions::trail(
[t[0].as_f64()?, t[1].as_f64()?, t[2].as_f64()?],
c & 0xFF_FFFF,
o["duration"].as_i64()? as i32,
)
}
_ => ParticleOptions::simple(ty),
})
}
fn state(s: &ParticleSnapshot) -> String {
let mut out = format!(
"{} {} {} {}",
s.age,
s.lifetime,
u8::from(s.removed),
u8::from(s.on_ground)
);
for v in s.position.iter().chain(&s.velocity).chain(&s.previous) {
out += &format!(" {}", d(*v));
}
if let Some(q) = &s.quad {
out += &format!(" | {} {}", f(q.size[0]), f(q.size[1]));
for v in q.rgba.iter().chain(&q.roll) {
out += &format!(" {}", f(*v));
}
out += &format!(" {}", q.sprite);
for v in q.uv {
out += &format!(" {}", f(v));
}
out += &format!(" {:x}", q.light);
}
out
}
fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result<World> {
let mut world = World::new(facts.air, 0);
let stone = assets
.registry
.default_state("minecraft:stone")
.ok_or("missing stone")?;
for cz in -3..=2 {
for cx in -3..=2 {
world
.chunks
.insert((cx, cz), Arc::new(Chunk::empty(cx, cz)));
if floor {
for z in 0..16 {
for x in 0..16 {
world.set(cx * 16 + x, 63, cz * 16 + z, stone)?;
}
}
}
}
}
Ok(world)
}
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().collect();
let root = Path::new(".local/horizon-client/26.3");
let assets = Assets::load(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let collision = collisions::load(root, assets.registry)?;
let worlds = [
world(&assets, &facts, false)?,
world(&assets, &facts, true)?,
];
let mut engine = ParticleEngine::new(root, &HashMap::new());
// The oracle's output: the seed line of each case.
let mut seeds = Vec::new();
for line in BufReader::new(File::open(&args[2])?).lines() {
let line = line?;
if line.starts_with("seed ") || line.starts_with("null ") || line == "no provider" {
seeds.push(line);
}
}
let mut out = BufWriter::new(File::create(&args[3])?);
for (n, line) in BufReader::new(File::open(&args[1])?).lines().enumerate() {
let case: Value = serde_json::from_str(&line?)?;
writeln!(out, "== {n}")?;
let Some(options) = options(&case) else {
writeln!(out, "no provider")?;
continue;
};
let seed = case["seed"].as_i64().ok_or("seed")?;
engine.seed_randoms(seed, seed ^ 0x6C_6576_656C, seed ^ 0x73_7065_6C6C);
engine.requested = Some(Vec::new());
engine.sounds.clear();
let level = ParticleLevel {
world: &worlds[usize::from(case["floor"].as_bool() == Some(true))],
facts: &facts,
collision: &collision,
player: None,
};
let v = |key: &str| -> [f64; 3] {
std::array::from_fn(|i| case[key][i].as_f64().unwrap_or(0.0))
};
let seed_line = seeds.get(n).cloned().unwrap_or_default();
let local = seed_line
.split(' ')
.nth(1)
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(0);
let Some(mut particle) = engine.probe_create(&options, v("pos"), v("vel"), local, &level)
else {
writeln!(out, "null {}", engine.next_randoms()[0])?;
continue;
};
writeln!(out, "{seed_line}")?;
let [a, b, c] = engine.next_randoms();
writeln!(out, "next {a} {b} {c}")?;
let events = |engine: &mut ParticleEngine, out: &mut BufWriter<File>| -> Result<()> {
for (o, p, v) in engine.requested.replace(Vec::new()).unwrap_or_default() {
write!(out, "+ {}", o.ty.name())?;
for x in p.iter().chain(&v) {
write!(out, " {}", d(*x))?;
}
writeln!(out)?;
}
for (name, p, volume, pitch) in std::mem::take(&mut engine.sounds) {
writeln!(
out,
"~ {name} {} {} {} {} {}",
d(p[0]),
d(p[1]),
d(p[2]),
f(volume),
f(pitch)
)?;
}
Ok(())
};
writeln!(out, "0 {}", state(&engine.snapshot(&particle)))?;
events(&mut engine, &mut out)?;
let ticks = case["ticks"].as_i64().unwrap_or(0);
let mut t = 1;
while t <= ticks && particle.is_alive() {
engine.probe_tick(&mut particle, &level);
writeln!(out, "{t} {}", state(&engine.snapshot(&particle)))?;
events(&mut engine, &mut out)?;
t += 1;
}
}
out.flush()?;
Ok(())
}
+259 -82
View File
@@ -14,7 +14,7 @@ use crate::{
};
use glam::{DVec3, Quat, Vec3 as FVec3};
use horizon_core::{
geometry::{Aabb, Axis, Vec3},
geometry::{Aabb, Axis, Vec3, trig},
random::{LegacyRandom, RandomSource},
};
use horizon_world::block_collision::BlockCollisionRegistry;
@@ -406,6 +406,8 @@ pub struct Particle {
no_render: bool,
/// Ticked once when created (`CritParticle` constructor).
pre_tick: bool,
/// `Particle.random`: the particle's own generator (`RandomSource.create()`).
random: LegacyRandom,
}
fn aabb_at(p: [f64; 3], w: f32, h: f32) -> Aabb {
let w = f64::from(w) / 2.0;
@@ -475,9 +477,14 @@ pub fn destroy_positions(
impl Particle {
/// `Particle(level, x, y, z)` + `SingleQuadParticle` (no initial velocity).
fn at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self {
let mut particle = Self::base_at(random, ty, p);
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `Particle(level, x, y, z)` without `SingleQuadParticle` (`NoRenderParticle`).
fn base_at(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3]) -> Self {
let mut particle = Self::blank(ty, p);
particle.lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32;
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
fn blank(ty: ParticleType, p: [f64; 3]) -> Self {
@@ -511,10 +518,17 @@ impl Particle {
behaviour: Behaviour::Base,
no_render: false,
pre_tick: false,
random: LegacyRandom::new(0),
}
}
/// `Particle(level, x, y, z, xa, ya, za)`: jittered, normalized initial velocity.
fn moving(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3], v: [f64; 3]) -> Self {
let mut particle = Self::base_moving(random, ty, p, v);
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `Particle(level, x, y, z, xa, ya, za)` without `SingleQuadParticle`.
fn base_moving(random: &mut LegacyRandom, ty: ParticleType, p: [f64; 3], v: [f64; 3]) -> Self {
let lifetime = (4.0 / (random.next_float() * 0.9 + 0.1)) as i32;
let mut d = [
v[0] + f64::from((random.next_float() * 2.0 - 1.0) * 0.4),
@@ -532,7 +546,6 @@ impl Particle {
let mut particle = Self::blank(ty, p);
particle.lifetime = lifetime;
particle.velocity = d;
particle.size = 0.1 * (random.next_float() * 0.5 + 0.5) * 2.0;
particle
}
/// `TerrainParticle(level, x, y, z, xa, ya, za, state)`: a crumb from a
@@ -556,6 +569,19 @@ impl Particle {
p.uv = [(uo + 1.0) / 4.0, vo / 4.0, uo / 4.0, (vo + 1.0) / 4.0];
p
}
/// What `CritParticle`'s providers do once its constructor has ticked it.
fn after_constructor_tick(&mut self) {
match self.ty {
// MagicProvider.
ParticleType::EnchantedHit => {
self.rgba[0] *= 0.3;
self.rgba[1] *= 0.8;
}
// DamageIndicatorProvider.
ParticleType::DamageIndicator => self.lifetime = 20,
_ => {}
}
}
/// `Particle.setPower`.
pub fn set_power(&mut self, power: f32) {
let power = f64::from(power);
@@ -653,6 +679,21 @@ impl Particle {
self.velocity[2] *= f64::from(0.7f32);
}
}
/// `getLightCoords(a)` from the world's smooth sky and block light (0..=240).
fn light_coords(&self, partial: f32, sky: u32, block: u32) -> (u32, u32) {
let t = ((self.age as f32 + partial) / self.lifetime as f32).clamp(0.0, 1.0);
match self.light {
Light::World => (sky, block),
Light::FullBright => (240, 240),
Light::Block15 => (sky, 240),
Light::AgeEmission => (sky, (block + (t * 240.0) as u32).min(240)),
Light::AgeEmission4 => {
let b = self.age as f32 / self.lifetime as f32;
let b = (b * b) * (b * b);
(sky, (block + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240))
}
}
}
fn quad_size(&self, a: f32) -> f32 {
let t = (self.age as f32 + a) / self.lifetime as f32;
match self.size_curve {
@@ -672,6 +713,34 @@ impl Particle {
}
}
/// A particle's fields as the parity probe reports them.
#[derive(Clone, Debug)]
pub struct ParticleSnapshot {
pub age: i32,
pub lifetime: i32,
pub removed: bool,
pub on_ground: bool,
pub position: [f64; 3],
pub velocity: [f64; 3],
pub previous: [f64; 3],
/// `SingleQuadParticle` state; `None` for `NoRenderParticle`s.
pub quad: Option<QuadSnapshot>,
}
/// `SingleQuadParticle` state at a render.
#[derive(Clone, Debug)]
pub struct QuadSnapshot {
/// `getQuadSize` at partial ticks 0 and 0.5.
pub size: [f32; 2],
pub rgba: [f32; 4],
/// `roll`, `oRoll`.
pub roll: [f32; 2],
pub sprite: String,
/// `getU0`, `getU1`, `getV0`, `getV1` within the sprite.
pub uv: [f32; 4],
/// `getLightCoords(0.5)` over full sky light and no block light.
pub light: u32,
}
/// World access for particle physics.
pub struct ParticleLevel<'a> {
pub world: &'a World,
@@ -734,7 +803,17 @@ impl ParticleLevel<'_> {
pub struct ParticleEngine {
particles: Vec<Particle>,
pending: Vec<Particle>,
/// `ParticleEngine.random`, handed to every `ParticleProvider`.
random: LegacyRandom,
/// `ClientLevel.random` as particle constructors use it (`level.getRandom()`).
level_random: LegacyRandom,
/// `SpellParticle.RANDOM`.
spell_random: LegacyRandom,
/// Seeds for each particle's own random (`RandomSource.create()`).
seeds: LegacyRandom,
/// When set, particles ask the level for other particles here instead
/// (type, position, velocity), as the parity probe's stand-in level does.
pub requested: Option<Vec<(ParticleOptions, [f64; 3], [f64; 3])>>,
names: Vec<String>,
rects: Vec<Option<Rect>>,
atlas: HashMap<String, Rect>,
@@ -757,6 +836,10 @@ impl ParticleEngine {
particles: Vec::new(),
pending: Vec::new(),
random: LegacyRandom::new(0x7061_7274),
level_random: LegacyRandom::new(0x6c65_7665),
spell_random: LegacyRandom::new(0x7370_656c),
seeds: LegacyRandom::new(0x7365_6564),
requested: None,
names: Vec::new(),
rects: Vec::new(),
atlas: atlas.clone(),
@@ -847,6 +930,10 @@ impl ParticleEngine {
pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
let c = self.camera;
let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2);
if let Some(requested) = &mut self.requested {
requested.push((options.clone(), p, v));
return;
}
if !options.ty.override_limiter() && d2 > 1024.0 {
return;
}
@@ -982,10 +1069,76 @@ impl ParticleEngine {
}
/// `ParticleEngine.createParticle`: always spawned.
pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) {
if let Some(particle) = self.make(options, p, v) {
let seed = self.seeds.next_long();
if let Some(particle) = self.make(options, p, v, seed) {
self.pending.push(particle);
}
}
/// Parity probes: seed the provider (`ParticleEngine.random`), level and
/// `SpellParticle.RANDOM` generators.
pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) {
self.random = LegacyRandom::new(provider);
self.level_random = LegacyRandom::new(level);
self.spell_random = LegacyRandom::new(spell);
}
/// Parity probes: the next long of the provider, level and spell generators.
pub fn next_randoms(&mut self) -> [i64; 3] {
[
self.random.next_long(),
self.level_random.next_long(),
self.spell_random.next_long(),
]
}
/// Parity probes: `ParticleProvider.createParticle` with the particle's own
/// random seeded `seed`, ticked in its constructor where vanilla does.
pub fn probe_create(
&mut self,
options: &ParticleOptions,
p: [f64; 3],
v: [f64; 3],
seed: i64,
level: &ParticleLevel,
) -> Option<Particle> {
let mut particle = self.make(options, p, v, seed)?;
if particle.pre_tick {
particle.pre_tick = false;
self.tick_particle(&mut particle, level);
particle.after_constructor_tick();
}
Some(particle)
}
/// Parity probes: `Particle.tick`.
pub fn probe_tick(&mut self, particle: &mut Particle, level: &ParticleLevel) {
self.tick_particle(particle, level);
}
/// Parity probes: the state vanilla's particle fields hold.
pub fn snapshot(&self, p: &Particle) -> ParticleSnapshot {
let sprite = match &p.sprite {
Sprite::Index(i) => self.names.get(*i as usize).map_or_else(
|| "-".to_owned(),
|n| n.strip_prefix("particle/").unwrap_or(n).to_owned(),
),
Sprite::Named(n) => n.clone(),
};
let (sky, block) = p.light_coords(0.5, 240, 0);
ParticleSnapshot {
age: p.age,
lifetime: p.lifetime,
removed: p.removed,
on_ground: p.on_ground,
position: p.position,
velocity: p.velocity,
previous: p.previous,
quad: (!p.no_render).then(|| QuadSnapshot {
size: [p.quad_size(0.0), p.quad_size(0.5)],
rgba: p.rgba,
roll: [p.roll, p.o_roll],
sprite,
uv: [p.uv[0], p.uv[2], p.uv[1], p.uv[3]],
light: block | sky << 16,
}),
}
}
/// `SpriteSet.get(random)`.
fn sprite_from_set(&mut self, ty: ParticleType) -> Sprite {
match self.sets.get(&ty) {
@@ -1023,28 +1176,38 @@ impl ParticleEngine {
}
}
#[allow(clippy::too_many_lines)]
fn make(&mut self, o: &ParticleOptions, p: [f64; 3], v: [f64; 3]) -> Option<Particle> {
/// `ParticleProvider.createParticle`: provider draws use the engine's
/// random, constructor and tick draws the particle's own (seeded `seed`).
fn make(
&mut self,
o: &ParticleOptions,
p: [f64; 3],
v: [f64; 3],
seed: i64,
) -> Option<Particle> {
use ParticleType as T;
let ty = o.ty;
let set = self.set_of(ty);
let r = &mut self.random;
let mut local = LegacyRandom::new(seed);
let r = &mut local;
let mut particle = match ty {
T::Block | T::BlockCrumble | T::DustPillar => {
let (sprite, tint) = o.block.clone()?;
let mut q = Particle::terrain(r, p, v, sprite, tint);
q.ty = ty;
let pr = &mut self.random;
if ty == T::BlockCrumble {
q.velocity = [0.0; 3];
q.lifetime = r.next_int_bound(10).unwrap_or(0) + 1;
q.lifetime = pr.next_int_bound(10).unwrap_or(0) + 1;
} else if ty == T::DustPillar {
q.velocity = [
r.next_gaussian() / 30.0,
v[1] + r.next_gaussian() / 2.0,
r.next_gaussian() / 30.0,
pr.next_gaussian() / 30.0,
v[1] + pr.next_gaussian() / 2.0,
pr.next_gaussian() / 30.0,
];
q.lifetime = r.next_int_bound(20).unwrap_or(0) + 20;
q.lifetime = pr.next_int_bound(20).unwrap_or(0) + 20;
}
return Some(q);
q
}
T::FallingDust => {
let (_, tint) = o.block.clone()?;
@@ -1071,13 +1234,17 @@ impl ParticleEngine {
T::LargeSmoke => ([0.1, 0.1, 0.1], 2.5, 0.3, 8, -0.1, true, v),
T::Ash => ([0.1, -0.1, 0.1], 1.0, 0.5, 20, 0.1, false, [0.0; 3]),
_ => {
let xa = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1;
let ya = f64::from(r.next_float())
// WhiteAshParticle.Provider draws the motion.
let pr = &mut self.random;
let xa =
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1;
let ya = f64::from(pr.next_float())
* -0.5
* f64::from(r.next_float())
* f64::from(pr.next_float())
* 0.1
* 5.0;
let za = f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1;
let za =
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1;
([0.1, -0.1, 0.1], 1.0, 0.0, 20, 0.0125, false, [xa, ya, za])
}
};
@@ -1170,7 +1337,10 @@ impl ParticleEngine {
| T::FallingDripstoneWater
| T::DrippingDripstoneLava
| T::FallingDripstoneLava => {
// The provider picks the sprite first (`sprite.get(random)`).
let sprite = self.sprite_from_set(ty);
let mut q = Particle::at(r, ty, p);
q.sprite = sprite;
q.set_size(0.01, 0.01);
q.gravity = 0.06;
let water = [0.2, 0.3, 1.0];
@@ -1306,14 +1476,18 @@ impl ParticleEngine {
q.gravity *= 0.01;
q.lifetime = 100;
}
// Lifetimes the providers draw from their own random.
T::LandingHoney => {
q.lifetime = (128.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32
q.lifetime =
(128.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32
}
T::LandingObsidianTear => {
q.lifetime = (28.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32
q.lifetime =
(28.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32
}
T::FallingNectar => {
q.lifetime = (16.0 / (f64::from(r.next_float()) * 0.8 + 0.2)) as i32;
q.lifetime =
(16.0 / (f64::from(self.random.next_float()) * 0.8 + 0.2)) as i32;
q.gravity = 0.007;
}
T::FallingSporeBlossom => {
@@ -1397,26 +1571,29 @@ impl ParticleEngine {
q
}
T::Underwater | T::CrimsonSpore | T::WarpedSpore | T::SporeBlossomAir => {
// SuspendedParticle; the providers draw motion, then the sprite.
let below = [p[0], p[1] - 0.125, p[2]];
let pr = &mut self.random;
let vel = match ty {
T::CrimsonSpore => [
pr.next_gaussian() * f64::from(1.0e-6f32),
pr.next_gaussian() * f64::from(1.0e-4f32),
pr.next_gaussian() * f64::from(1.0e-6f32),
],
T::WarpedSpore => [
0.0,
f64::from(pr.next_float()) * -1.9 * f64::from(pr.next_float()) * 0.1,
0.0,
],
_ => [0.0, f64::from(-0.8f32), 0.0],
};
let sprite = self.sprite_from_set(ty);
let mut q = if ty == T::Underwater {
let mut q = Particle::at(r, ty, below);
q.set_size(0.01, 0.01);
q.size *= r.next_float() * 0.6 + 0.2;
q
} else {
let vel = match ty {
T::CrimsonSpore => [
r.next_gaussian() * 1.0e-6,
r.next_gaussian() * 1.0e-4,
r.next_gaussian() * 1.0e-6,
],
T::WarpedSpore => [
0.0,
f64::from(r.next_float()) * -1.9 * f64::from(r.next_float()) * 0.1,
0.0,
],
_ => [0.0, f64::from(-0.8f32), 0.0],
};
let mut q = Particle::moving(r, ty, below, vel);
q.set_size(0.01, 0.01);
q.size *= r.next_float() * 0.6 + 0.6;
@@ -1434,11 +1611,12 @@ impl ParticleEngine {
q.set_size(0.001, 0.001);
}
_ => {
q.lifetime = r.next_int_bound(501).unwrap_or(0) + 500;
q.lifetime = self.random.next_int_bound(501).unwrap_or(0) + 500;
q.gravity = 0.01;
q.set_color(0.32, 0.5, 0.22);
}
}
q.sprite = sprite;
q
}
T::Portal | T::ReversePortal => {
@@ -1533,7 +1711,10 @@ impl ParticleEngine {
q
}
T::HappyVillager | T::Composter | T::Mycelium | T::Dolphin | T::EggCrack => {
// SuspendedTownParticle; the provider picks the sprite first.
let sprite = self.sprite_from_set(ty);
let mut q = Particle::moving(r, ty, p, v);
q.sprite = sprite;
let br = r.next_float() * 0.1 + 0.2;
q.set_color(br, br, br);
q.set_size(0.02, 0.02);
@@ -1548,11 +1729,11 @@ impl ParticleEngine {
T::HappyVillager | T::EggCrack => q.set_color(1.0, 1.0, 1.0),
T::Composter => {
q.set_color(1.0, 1.0, 1.0);
q.lifetime = 3 + r.next_int_bound(5).unwrap_or(0);
q.lifetime = 3 + self.level_random.next_int_bound(5).unwrap_or(0);
}
T::Dolphin => {
q.set_color(0.3, 0.5, 1.0);
q.rgba[3] = 1.0 - r.next_float() * 0.7;
q.rgba[3] = 1.0 - self.random.next_float() * 0.7;
q.lifetime /= 2;
}
_ => {}
@@ -1607,7 +1788,7 @@ impl ParticleEngine {
q
}
T::ExplosionEmitter => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
let mut q = Particle::base_moving(r, ty, p, [0.0; 3]);
q.lifetime = 8;
q.no_render = true;
q.behaviour = Behaviour::ExplosionSeed;
@@ -1616,8 +1797,7 @@ impl ParticleEngine {
// GustParticle: a still, bright, opaque quad that animates over
// its 12 to 15 ticks; the small one is scaled to 15%.
T::Gust | T::SmallGust => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
q.velocity = [0.0; 3];
let mut q = Particle::at(r, ty, p);
q.lifetime = 12 + r.next_int_bound(4).unwrap_or(0);
q.size = 1.0;
q.set_size(1.0, 1.0);
@@ -1630,7 +1810,7 @@ impl ParticleEngine {
q
}
T::GustEmitterLarge | T::GustEmitterSmall => {
let mut q = Particle::moving(r, ty, p, [0.0; 3]);
let mut q = Particle::base_moving(r, ty, p, [0.0; 3]);
let (scale, lifetime, delay) = if ty == T::GustEmitterLarge {
(3.0, 7, 0)
} else {
@@ -1670,13 +1850,13 @@ impl ParticleEngine {
}
q.velocity[1] += 0.2;
let color = v[0] as f32;
// `Mth.sin` (the quantized table) of a float angle.
let channel = |offset: f32| {
((color + offset) * std::f32::consts::TAU)
.sin()
.mul_add(0.65, 0.35)
(trig::sin(f64::from((color + offset) * std::f64::consts::TAU as f32)) * 0.65
+ 0.35)
.max(0.0)
};
q.set_color(channel(0.0), channel(1.0 / 3.0), channel(2.0 / 3.0));
q.set_color(channel(0.0), channel(0.333_333_34), channel(0.666_666_7));
q.size *= 1.5;
q.lifetime = 6;
q.size_curve = Size::GrowIn;
@@ -1722,9 +1902,9 @@ impl ParticleEngine {
if ty == T::SculkCharge {
q.roll = o.scale;
q.o_roll = o.scale;
q.lifetime = r.next_int_bound(12).unwrap_or(0) + 8;
q.lifetime = self.random.next_int_bound(12).unwrap_or(0) + 8;
} else {
q.lifetime = r.next_int_bound(4).unwrap_or(0) + 6;
q.lifetime = self.random.next_int_bound(4).unwrap_or(0) + 6;
}
q
}
@@ -1742,7 +1922,6 @@ impl ParticleEngine {
q.behaviour = Behaviour::Shriek {
delay: o.scale as i32,
};
q.set = set;
q
}
T::Dust => {
@@ -1777,6 +1956,7 @@ impl ParticleEngine {
q.size *= 0.75;
q.lifetime = 48 + r.next_int_bound(12).unwrap_or(0);
q.rgba[3] = 0.99;
q.light = Light::FullBright;
q.behaviour = Behaviour::Spark {
fade: None,
trail: false,
@@ -1862,9 +2042,9 @@ impl ParticleEngine {
q
}
T::Effect | T::InstantEffect | T::EntityEffect | T::Witch | T::Infested => {
// SpellParticle: x/z velocity from a shared random, y from the option.
let xa = 0.5 - r.next_double();
let za = 0.5 - r.next_double();
// SpellParticle: x/z velocity from `SpellParticle.RANDOM`, y from the option.
let xa = 0.5 - self.spell_random.next_double();
let za = 0.5 - self.spell_random.next_double();
let mut q = Particle::moving(r, ty, p, [xa, v[1], za]);
q.friction = 0.96;
q.gravity = -0.1;
@@ -1879,7 +2059,7 @@ impl ParticleEngine {
q.has_physics = false;
match ty {
T::Witch => {
let b = r.next_float() * 0.5 + 0.35;
let b = self.random.next_float() * 0.5 + 0.35;
q.set_color(b, 0.0, b);
}
T::EntityEffect => {
@@ -1939,13 +2119,17 @@ impl ParticleEngine {
}
T::Trail => {
let (target, duration) = o.trail?;
let mut q = Particle::at(r, ty, p);
let mut q = Particle::moving(r, ty, p, v);
let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25;
let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r));
// `ARGB.scaleRGB` on the 8-bit channels.
let scaled = |c: f32, s: f32| {
((((c * 255.0).round() as i32) as f32 * s) as i32).clamp(0, 255) as f32 / 255.0
};
q.set_color(
(o.color[0] * jr).min(1.0),
(o.color[1] * jg).min(1.0),
(o.color[2] * jb).min(1.0),
scaled(o.color[0], jr),
scaled(o.color[1], jg),
scaled(o.color[2], jb),
);
q.size = 0.26;
q.lifetime = duration;
@@ -1962,6 +2146,7 @@ impl ParticleEngine {
} else if matches!(particle.sprite, Sprite::Index(u32::MAX)) {
particle.sprite = self.sprite_from_set(ty);
}
particle.random = local;
Some(particle)
}
@@ -1977,13 +2162,16 @@ impl ParticleEngine {
trail: bool,
twinkle: bool,
) -> Particle {
let mut q = Particle::at(&mut self.random, ParticleType::Firework, at);
let mut local = LegacyRandom::new(self.seeds.next_long());
let mut q = Particle::at(&mut local, ParticleType::Firework, at);
q.velocity = v;
q.gravity = 0.1;
q.friction = 0.91;
q.size *= 0.75;
q.lifetime = 48 + self.random.next_int_bound(12).unwrap_or(0);
q.lifetime = 48 + local.next_int_bound(12).unwrap_or(0);
q.random = local;
q.rgba = [rgba[0], rgba[1], rgba[2], 0.99];
q.light = Light::FullBright;
q.behaviour = Behaviour::Spark {
fade,
trail,
@@ -2181,6 +2369,7 @@ impl ParticleEngine {
if p.pre_tick {
p.pre_tick = false;
self.tick_particle(&mut p, level);
p.after_constructor_tick();
}
// ParticleGroup.add: the last quarter fills with decreasing probability.
let size = self.particles.len();
@@ -2215,7 +2404,7 @@ impl ParticleEngine {
p.base_tick(level);
if !p.removed {
let odds = p.age as f32 / p.lifetime as f32;
if self.random.next_float() > odds {
if p.random.next_float() > odds {
self.add(
&ParticleOptions::simple(ParticleType::Smoke),
p.position,
@@ -2271,7 +2460,7 @@ impl ParticleEngine {
self.add(&ParticleOptions::simple(next), p.position, [0.0; 3]);
}
if let Some(sound) = sound {
let volume = self.random.next_float() * 0.7 + 0.3;
let volume = p.random.next_float() * 0.7 + 0.3;
self.sounds.push((sound, p.position, volume, 1.0));
}
}
@@ -2305,7 +2494,7 @@ impl ParticleEngine {
*c *= f64::from(0.98f32);
}
if p.on_ground {
if self.random.next_float() < 0.5 {
if p.random.next_float() < 0.5 {
p.removed = true;
}
p.velocity[0] *= f64::from(0.7f32);
@@ -2448,7 +2637,6 @@ impl ParticleEngine {
p.behaviour = Behaviour::Shriek { delay: delay - 1 };
} else {
p.base_tick(level);
self.sprite_from_age(p);
}
}
Behaviour::Vibration {
@@ -2490,9 +2678,10 @@ impl ParticleEngine {
p.removed = true;
return;
}
let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1));
// `Mth.lerp(1.0 / ticksRemaining, x, target)`, infinite on the last tick.
let alpha = 1.0 / f64::from(p.lifetime - p.age);
for i in 0..3 {
p.position[i] += (target[i] - p.position[i]) * alpha;
p.position[i] += alpha * (target[i] - p.position[i]);
}
}
Behaviour::HugeExplosion => {
@@ -2508,7 +2697,7 @@ impl ParticleEngine {
Behaviour::GustSeed { scale, delay } => {
if p.age % (delay + 1) == 0 {
for _ in 0..3 {
let r = &mut self.random;
let r = &mut p.random;
let at = [
p.position[0] + (r.next_double() - r.next_double()) * scale,
p.position[1] + (r.next_double() - r.next_double()) * scale,
@@ -2530,7 +2719,7 @@ impl ParticleEngine {
}
Behaviour::ExplosionSeed => {
for _ in 0..6 {
let r = &mut self.random;
let r = &mut p.random;
let at = [
p.position[0] + (r.next_double() - r.next_double()) * 4.0,
p.position[1] + (r.next_double() - r.next_double()) * 4.0,
@@ -2553,7 +2742,7 @@ impl ParticleEngine {
let age = p.age;
p.age += 1;
if age < p.lifetime && p.rgba[3] > 0.0 {
let r = &mut self.random;
let r = &mut p.random;
let dx = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 };
p.velocity[0] += f64::from(dx);
let dz = r.next_float() / 5000.0 * if r.next_boolean() { 1.0 } else { -1.0 };
@@ -2829,23 +3018,11 @@ impl ParticleEngine {
}
let block = ParticleLevel::block_at(p.position);
let packed = light_at(block);
let (sky, mut block_light) = (u32::from(packed >> 4) * 16, u32::from(packed & 15) * 16);
let mut sky_light = sky;
let t = ((p.age as f32 + partial) / p.lifetime as f32).clamp(0.0, 1.0);
match p.light {
Light::World => {}
Light::FullBright => {
block_light = 240;
sky_light = 240;
}
Light::Block15 => block_light = 240,
Light::AgeEmission => block_light = (block_light + (t * 240.0) as u32).min(240),
Light::AgeEmission4 => {
let b = p.age as f32 / p.lifetime as f32;
let b = (b * b) * (b * b);
block_light = (block_light + (b.clamp(0.0, 1.0) * 240.0) as u32).min(240);
}
}
let (sky_light, block_light) = p.light_coords(
partial,
u32::from(packed >> 4) * 16,
u32::from(packed & 15) * 16,
);
let light = sky_light | block_light << 8;
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0) as u32;
let color = c(alpha) << 24 | c(rgb[2]) << 16 | c(rgb[1]) << 8 | c(rgb[0]);
@@ -0,0 +1,292 @@
package dev.horizonlab.parity;
import com.google.gson.*;
import com.mojang.blaze3d.platform.NativeImage;
import java.io.InputStreamReader;
import java.lang.reflect.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import net.minecraft.SharedConstants;
import net.minecraft.client.Minecraft;
import net.minecraft.client.color.block.BlockColors;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.particle.*;
import net.minecraft.client.renderer.block.BlockStateModelSet;
import net.minecraft.client.renderer.item.ItemModelResolver;
import net.minecraft.client.renderer.item.ItemStackRenderState;
import net.minecraft.client.renderer.texture.*;
import net.minecraft.client.resources.metadata.animation.FrameSize;
import net.minecraft.client.resources.model.ModelManager;
import net.minecraft.client.resources.model.sprite.Material;
import net.minecraft.core.BlockPos;
import net.minecraft.core.particles.*;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.Bootstrap;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.sounds.SoundSource;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.ItemOwner;
import net.minecraft.world.item.ItemDisplayContext;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemStackTemplate;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.gameevent.BlockPositionSource;
import net.minecraft.world.level.levelgen.LegacyRandomSource;
import net.minecraft.world.level.levelgen.RandomSupport;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.Vec3;
import org.jspecify.annotations.Nullable;
/** Builds each particle through its real registered ParticleProvider (the real
* ParticleResources, sprite sets bound to stand-in sprites named after the
* vanilla particles/*.json textures) in a stand-in ClientLevel (air, an
* optional stone floor at y 63, no fluids), then ticks it and records its
* state, the particles and sounds it asks the level for, tick by tick.
*
* Each vanilla Particle owns a RandomSource.create() random seeded from the
* clock; its seed is recovered after construction (the SEED_UNIQUIFIER value
* and the System.nanoTime window around the call, checked against the
* random's state stepped back over its draws) and printed first so the probe
* can replay the same draws. The provider random, the level random and
* SpellParticle.RANDOM are seeded from the case. */
public final class VanillaParticleProvidersOracle {
private static Object unsafe;
private static Method allocate;
private static final long MULTIPLIER = 0x5DEECE66DL, MASK = (1L << 48) - 1, INVERSE = 0xDFE05BCB1365L;
static Field field(Class<?> type, String name) throws Exception {
var f = type.getDeclaredField(name); f.setAccessible(true); return f;
}
static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); }
static final class Level0 extends ClientLevel {
boolean floor;
List<String> events;
Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); }
@Override public BlockState getBlockState(BlockPos p) {
return floor && p.getY() == 63 ? Blocks.STONE.defaultBlockState() : Blocks.AIR.defaultBlockState();
}
@Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); }
@Override public @Nullable BlockGetter getChunkForCollisions(int x, int z) { return this; }
@Override public boolean hasChunkAt(BlockPos p) { return false; }
@Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
events.add("+ " + name(o) + " " + d(x) + " " + d(y) + " " + d(z) + " " + d(xd) + " " + d(yd) + " " + d(zd));
}
@Override public void addParticle(ParticleOptions o, boolean override, boolean always, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void addAlwaysVisibleParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void addAlwaysVisibleParticle(ParticleOptions o, boolean override, double x, double y, double z, double xd, double yd, double zd) {
addParticle(o, x, y, z, xd, yd, zd);
}
@Override public void playLocalSound(double x, double y, double z, SoundEvent sound, SoundSource source, float volume, float pitch, boolean delay) {
events.add("~ " + sound.location() + " " + d(x) + " " + d(y) + " " + d(z) + " " + f(volume) + " " + f(pitch));
}
@Override public net.minecraft.world.entity.player.@Nullable Player getNearestPlayer(double x, double y, double z, double distance, boolean creative) { return null; }
}
static String name(ParticleOptions o) { return BuiltInRegistries.PARTICLE_TYPE.getKey(o.getType()).getPath(); }
static String d(double v) { return String.format("%016x", Double.doubleToRawLongBits(v)); }
static String f(float v) { return String.format("%08x", Float.floatToRawIntBits(v)); }
static final class Sprite extends TextureAtlasSprite {
Sprite(Identifier atlas, Identifier name) { super(atlas, new SpriteContents(name, new FrameSize(16, 16), new NativeImage(16, 16, true)), 16, 16, 0, 0, 0); }
}
static final Map<String, TextureAtlasSprite> SPRITES = new HashMap<>();
static TextureAtlasSprite sprite(Identifier atlas, String name) {
return SPRITES.computeIfAbsent(name, n -> new Sprite(atlas, Identifier.withDefaultNamespace(n)));
}
static final class Models extends BlockStateModelSet {
Models() { super(Map.of(), null); }
@Override public Material.Baked getParticleMaterial(BlockState state) {
return new Material.Baked(sprite(TextureAtlas.LOCATION_BLOCKS, "terrain"), false);
}
}
/** Every item resolves to one layer whose particle sprite is named after the item. */
static final class Items0 extends ItemModelResolver {
Items0() { super(null); }
@Override public void updateForTopItem(ItemStackRenderState out, ItemStack item, ItemDisplayContext context, @Nullable Level level, @Nullable ItemOwner owner, int seed) {
out.clear();
out.newLayer().setParticleMaterial(new Material.Baked(sprite(TextureAtlas.LOCATION_BLOCKS, "item_" + BuiltInRegistries.ITEM.getKey(item.getItem()).getPath()), false));
}
}
static ParticleOptions options(JsonObject c) {
var id = Identifier.withDefaultNamespace(c.get("type").getAsString());
ParticleType<?> type = BuiltInRegistries.PARTICLE_TYPE.getValue(id);
if (type == null) throw new AssertionError("unknown particle " + id);
var o = c.has("options") ? c.getAsJsonObject("options") : new JsonObject();
if (type instanceof SimpleParticleType simple) return simple;
@SuppressWarnings("unchecked") var any = (ParticleType<ParticleOptions>) (ParticleType<?>) type;
int color = o.has("color") ? (int) o.get("color").getAsLong() : 0xFFFFFFFF;
float scale = o.has("scale") ? o.get("scale").getAsFloat() : 1.0F;
if (type == ParticleTypes.DUST) return new DustParticleOptions(color, scale);
if (type == ParticleTypes.DUST_COLOR_TRANSITION) return new DustColorTransitionOptions(color, (int) o.get("to").getAsLong(), scale);
if (type == ParticleTypes.EFFECT || type == ParticleTypes.INSTANT_EFFECT)
return SpellParticleOption.create(castSpell(type), color, scale);
if (type == ParticleTypes.DRAGON_BREATH) return PowerParticleOption.create(ParticleTypes.DRAGON_BREATH, scale);
if (type == ParticleTypes.SCULK_CHARGE) return new SculkChargeParticleOptions(scale);
if (type == ParticleTypes.SHRIEK) return new ShriekParticleOption((int) scale);
if (type == ParticleTypes.ITEM)
return new ItemParticleOption(ParticleTypes.ITEM, new ItemStackTemplate(BuiltInRegistries.ITEM.getValue(Identifier.parse(o.get("item").getAsString()))));
if (type == ParticleTypes.TRAIL) {
var t = o.getAsJsonArray("target");
return new TrailParticleOption(new Vec3(t.get(0).getAsDouble(), t.get(1).getAsDouble(), t.get(2).getAsDouble()), color, o.get("duration").getAsInt());
}
if (type == ParticleTypes.VIBRATION) {
var t = o.getAsJsonArray("target");
return new VibrationParticleOption(new BlockPositionSource(new BlockPos(t.get(0).getAsInt(), t.get(1).getAsInt(), t.get(2).getAsInt())), o.get("duration").getAsInt());
}
if (o.has("state")) return new BlockParticleOption(castBlock(type), Block.stateById(o.get("state").getAsInt()));
if (o.has("color")) return ColorParticleOption.create(castColor(type), color);
throw new AssertionError("no options for " + id);
}
@SuppressWarnings("unchecked") static ParticleType<SpellParticleOption> castSpell(ParticleType<?> t) { return (ParticleType<SpellParticleOption>) t; }
@SuppressWarnings("unchecked") static ParticleType<BlockParticleOption> castBlock(ParticleType<?> t) { return (ParticleType<BlockParticleOption>) t; }
@SuppressWarnings("unchecked") static ParticleType<ColorParticleOption> castColor(ParticleType<?> t) { return (ParticleType<ColorParticleOption>) t; }
static Field X, Y, Z, XO, YO, ZO, XD, YD, ZD, AGE, LIFETIME, REMOVED, ON_GROUND, RANDOM, SEED;
static Field QUAD, R, G, B, A, ROLL, O_ROLL, SPRITE;
static Method U0, U1, V0, V1, LIGHT;
static String state(Particle p) throws Exception {
var s = new StringBuilder();
s.append(AGE.getInt(p)).append(' ').append(LIFETIME.getInt(p)).append(' ').append(REMOVED.getBoolean(p) ? 1 : 0)
.append(' ').append(ON_GROUND.getBoolean(p) ? 1 : 0);
for (var f : new Field[] {X, Y, Z, XD, YD, ZD, XO, YO, ZO}) s.append(' ').append(d(f.getDouble(p)));
if (p instanceof SingleQuadParticle q) {
s.append(" | ").append(f(q.getQuadSize(0.0F))).append(' ').append(f(q.getQuadSize(0.5F)));
for (var f : new Field[] {R, G, B, A, ROLL, O_ROLL}) s.append(' ').append(f(f.getFloat(q)));
var sprite = (TextureAtlasSprite) SPRITE.get(q);
s.append(' ').append(sprite == null ? "-" : sprite.contents().name().getPath());
for (var m : new Method[] {U0, U1, V0, V1}) s.append(' ').append(f((float) m.invoke(q)));
s.append(' ').append(Integer.toHexString((int) LIGHT.invoke(q, 0.5F)));
}
return s.toString();
}
/** Recover the seed of RandomSource.create() that made `random`, which was
* created after `before` was the uniquifier and inside [t0, t1]. */
static long recover(LegacyRandomSource random, long before, long t0, long t1) throws Exception {
long end = ((AtomicLong) SEED.get(random)).get();
var back = new HashMap<Long, Integer>();
long s = end;
for (int k = 0; k <= 4096; k++) { back.putIfAbsent(s, k); s = ((s - 0xBL) * INVERSE) & MASK; }
long u = before;
Long found = null;
for (int j = 0; j < 8 && found == null; j++) {
u *= 1181783497276652981L;
for (long t = t0; t <= t1; t++) {
long seed = u ^ t;
if (back.containsKey((seed ^ MULTIPLIER) & MASK)) {
if (found != null && ((found ^ MULTIPLIER) & MASK) != ((seed ^ MULTIPLIER) & MASK)) throw new AssertionError("ambiguous seed");
found = seed;
}
}
}
if (found == null) throw new AssertionError("particle seed not recovered");
return found;
}
public static void main(String[] args) throws Exception {
SharedConstants.tryDetectVersion(); Bootstrap.bootStrap();
var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null); allocate = u.getMethod("allocateInstance", Class.class);
var mc = make(Minecraft.class); field(Minecraft.class, "instance").set(null, mc);
var manager = make(ModelManager.class); field(ModelManager.class, "blockStateModelSet").set(manager, new Models());
field(Minecraft.class, "modelManager").set(mc, manager); field(Minecraft.class, "blockColors").set(mc, new BlockColors());
field(Minecraft.class, "itemModelResolver").set(mc, new Items0());
var level = make(Level0.class); level.events = new ArrayList<>(); field(ClientLevel.class, "minecraft").set(level, mc);
field(Minecraft.class, "particleEngine").set(mc, new ParticleEngine(level, null));
X = field(Particle.class, "x"); Y = field(Particle.class, "y"); Z = field(Particle.class, "z");
XO = field(Particle.class, "xo"); YO = field(Particle.class, "yo"); ZO = field(Particle.class, "zo");
XD = field(Particle.class, "xd"); YD = field(Particle.class, "yd"); ZD = field(Particle.class, "zd");
AGE = field(Particle.class, "age"); LIFETIME = field(Particle.class, "lifetime"); REMOVED = field(Particle.class, "removed");
ON_GROUND = field(Particle.class, "onGround"); RANDOM = field(Particle.class, "random"); SEED = field(LegacyRandomSource.class, "seed");
QUAD = field(SingleQuadParticle.class, "quadSize"); R = field(SingleQuadParticle.class, "rCol"); G = field(SingleQuadParticle.class, "gCol");
B = field(SingleQuadParticle.class, "bCol"); A = field(SingleQuadParticle.class, "alpha"); ROLL = field(SingleQuadParticle.class, "roll");
O_ROLL = field(SingleQuadParticle.class, "oRoll"); SPRITE = field(SingleQuadParticle.class, "sprite");
U0 = SingleQuadParticle.class.getDeclaredMethod("getU0"); U1 = SingleQuadParticle.class.getDeclaredMethod("getU1");
V0 = SingleQuadParticle.class.getDeclaredMethod("getV0"); V1 = SingleQuadParticle.class.getDeclaredMethod("getV1");
LIGHT = Particle.class.getDeclaredMethod("getLightCoords", float.class);
for (var m : new Method[] {U0, U1, V0, V1, LIGHT}) m.setAccessible(true);
var uniquifier = (AtomicLong) field(RandomSupport.class, "SEED_UNIQUIFIER").get(null);
// Initialise SpellParticle first: its static initializer would replace a seeded RANDOM.
Class.forName(SpellParticle.class.getName(), true, SpellParticle.class.getClassLoader());
var spellRandom = field(SpellParticle.class, "RANDOM");
var unsafeObject = unsafe;
var staticBase = u.getMethod("staticFieldBase", Field.class).invoke(unsafeObject, spellRandom);
long staticOffset = (long) u.getMethod("staticFieldOffset", Field.class).invoke(unsafeObject, spellRandom);
var putObject = u.getMethod("putObject", Object.class, long.class, Object.class);
// The real providers, their sprite sets bound to one stand-in sprite per listed texture.
var resources = new ParticleResources();
@SuppressWarnings("unchecked") var sets = (Map<Identifier, Object>) field(ParticleResources.class, "spriteSets").get(resources);
for (var e : sets.entrySet()) {
var stream = Minecraft.class.getResourceAsStream("/assets/minecraft/particles/" + e.getKey().getPath() + ".json");
var sprites = new ArrayList<TextureAtlasSprite>();
if (stream != null) {
try (var reader = new InputStreamReader(stream, StandardCharsets.UTF_8)) {
for (var t : JsonParser.parseReader(reader).getAsJsonObject().getAsJsonArray("textures"))
sprites.add(sprite(TextureAtlas.LOCATION_PARTICLES, Identifier.parse(t.getAsString()).getPath()));
}
}
if (sprites.isEmpty()) sprites.add(sprite(TextureAtlas.LOCATION_PARTICLES, "missingno"));
var rebind = e.getValue().getClass().getDeclaredMethod("rebind", List.class); rebind.setAccessible(true);
rebind.invoke(e.getValue(), sprites);
}
var providers = resources.getProviders();
// Warm up the classes the providers touch so the clock window stays small.
for (int i = 0; i < 3; i++) RandomSource.create();
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 options = options(c);
@SuppressWarnings("unchecked") var provider = (ParticleProvider<ParticleOptions>) providers.get(BuiltInRegistries.PARTICLE_TYPE.getId(options.getType()));
if (provider == null) { output.write("no provider"); output.newLine(); continue; }
long seed = c.get("seed").getAsLong();
RandomSource random = null;
level.floor = c.get("floor").getAsBoolean();
level.events.clear();
var p = c.getAsJsonArray("pos"); var v = c.getAsJsonArray("vel");
Particle particle = null;
long before = 0, t0 = 0, t1 = 0;
for (int attempt = 0; attempt < 4; attempt++) {
level.events.clear();
random = RandomSource.create(seed);
field(Level.class, "random").set(level, RandomSource.create(seed ^ 0x6C6576656CL));
putObject.invoke(unsafeObject, staticBase, staticOffset, RandomSource.create(seed ^ 0x7370656C6CL));
before = uniquifier.get(); t0 = System.nanoTime();
particle = provider.createParticle(options, level, p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble(),
v.get(0).getAsDouble(), v.get(1).getAsDouble(), v.get(2).getAsDouble(), random);
t1 = System.nanoTime();
if (t1 - t0 < 50_000_000L) break;
}
if (particle == null) { output.write("null " + random.nextLong()); output.newLine(); continue; }
long local = recover((LegacyRandomSource) RANDOM.get(particle), before, t0, t1);
output.write("seed " + local + " " + particle.getClass().getSimpleName()); output.newLine();
output.write("next " + random.nextLong() + " " + level.getRandom().nextLong() + " "
+ ((RandomSource) spellRandom.get(null)).nextLong()); output.newLine();
output.write("0 " + state(particle)); output.newLine();
for (var e : level.events) { output.write(e); output.newLine(); }
int ticks = c.get("ticks").getAsInt();
for (int t = 1; t <= ticks && particle.isAlive(); t++) {
level.events.clear();
particle.tick();
output.write(t + " " + state(particle)); output.newLine();
for (var e : level.events) { output.write(e); output.newLine(); }
}
}
}
}
}
+218
View File
@@ -0,0 +1,218 @@
#!/usr/bin/env python3
"""Compare Horizon's ParticleEngine with the pinned client's ParticleProviders:
every supported particle type is built through its real registered provider
(real ParticleResources, sprite sets bound to stand-in sprites named after the
vanilla particles/*.json textures) in a stand-in ClientLevel (air, optionally a
stone floor at y 63), then ticked; position, motion, age, lifetime, size,
colour, roll, sprite, UVs and light are compared tick by tick, with the
particles and sounds each one asks the level for and every random draw.
Each vanilla Particle owns a clock-seeded RandomSource.create(); the oracle
recovers that seed and runs first, and the probe replays the same seed."""
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
STONE = 1 # Block.stateById(1) in 26.3
# Types Horizon implements, with the options each is built with.
SIMPLE = """angry_villager ash bubble bubble_column_up bubble_pop campfire_cosy_smoke campfire_signal_smoke
cherry_leaves cloud composter crimson_spore crit current_down damage_indicator dolphin dripping_dripstone_lava
dripping_dripstone_water dripping_honey dripping_lava dripping_obsidian_tear dripping_water egg_crack enchant
enchanted_hit end_rod explosion explosion_emitter falling_dripstone_lava falling_dripstone_water falling_honey
falling_lava falling_nectar falling_obsidian_tear falling_spore_blossom falling_water firework flame copper_fire_flame
gust gust_emitter_large gust_emitter_small happy_villager heart infested landing_honey landing_lava
landing_obsidian_tear large_smoke lava mycelium nautilus note pale_oak_leaves poof portal rain reverse_portal
sculk_charge_pop sculk_soul smoke small_flame small_gust sneeze snowflake sonic_boom soul soul_fire_flame splash
spore_blossom_air totem_of_undying underwater vault_connection warped_spore white_ash white_smoke witch""".split()
def options(kind, rng):
if kind in ('block', 'block_crumble', 'dust_pillar', 'falling_dust'):
return dict(state=STONE)
if kind == 'dust':
return dict(color=rng.choice([0xFF0000, 0x3A9E2C, 0xFFFFFF]), scale=rng.choice([1.0, 0.5, 2.0]))
if kind == 'dust_color_transition':
return dict(color=0x39D7E0, to=0xFF0000, scale=rng.choice([1.0, 2.0]))
if kind in ('effect', 'instant_effect'):
return dict(color=rng.choice([0xFFFFFFFF, 0xFF3366CC]), scale=rng.choice([1.0, 0.5, 2.5]))
if kind == 'entity_effect':
return dict(color=rng.choice([0xFF3366CC, 0x26AA00FF]))
if kind == 'tinted_leaves':
return dict(color=0xFF48B518)
if kind == 'dragon_breath':
return dict(scale=rng.choice([1.0, 0.25]))
if kind == 'sculk_charge':
return dict(scale=rng.choice([0.0, 1.5707964, 3.1415927]))
if kind == 'shriek':
return dict(scale=rng.choice([0, 5]))
if kind == 'trail':
return dict(target=[2.5, 67.0, -3.25], color=0x7F3F1F, duration=rng.choice([10, 37]))
return {}
def cases(rng):
kinds = SIMPLE + ['block', 'block_crumble', 'dust_pillar', 'falling_dust', 'dust', 'dust_color_transition', 'effect',
'instant_effect', 'entity_effect', 'tinted_leaves', 'dragon_breath', 'sculk_charge', 'shriek', 'trail']
# Dyadic values: serde_json's decimal parsing may round others a unit off.
starts = [([0.3125, 66.6875, -0.40625], False), ([0.3125, 64.046875, -0.40625], True), ([-5.75, 64.59375, 3.125], True)]
velocities = [[0.0, 0.0, 0.0], [0.078125, 0.125, -0.046875], [0.0, -0.296875, 0.0], [0.5, 0.0, 0.25]]
for kind in kinds:
for (pos, floor) in starts:
for vel in velocities:
yield dict(type=kind, options=options(kind, rng), pos=pos, vel=vel, floor=floor,
seed=rng.randrange(-2**63, 2**63), ticks=80)
def make_cases(build):
path = build / 'cases.jsonl'
count = 0
with path.open('w') as out:
for case in cases(random.Random(0x50415254)):
out.write(json.dumps(case, separators=(',', ':')) + '\n')
count += 1
return path, count
def decode(token):
if len(token) == 16:
try:
return f'{struct.unpack(">d", bytes.fromhex(token))[0]!r}'
except ValueError:
return token
if len(token) == 8:
try:
return f'{struct.unpack(">f", bytes.fromhex(token))[0]!r}'
except ValueError:
return token
return token
# Particles whose tick calls Math.cos/sin/pow. On x86-64 HotSpot's intrinsics
# (Intel's libm) round a fraction of a percent of arguments a unit apart from
# the platform libm horizon_core::jmath uses, so their motion is compared to
# 1e-12 relative error; everything else about them, and every other type, exactly.
LIBM = {'cherry_leaves', 'pale_oak_leaves', 'tinted_leaves'}
def sections(path):
out, name = {}, None
for line in path.read_text(encoding='utf-8', errors='replace').splitlines():
if line.startswith('== '):
name = int(line[3:])
out[name] = []
elif name is not None:
out[name].append(line)
return out
def close(a, b):
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
try:
fx, fy = (struct.unpack('>d', bytes.fromhex(t))[0] for t in (x, y))
except ValueError:
return False
if not abs(fx - fy) <= 1e-12 * max(1.0, abs(fx)):
return False
return True
def tolerated(build, cases_path):
"""Lines of LIBM cases that differ only within the libm tolerance, or None."""
rows = cases_path.read_text().splitlines()
left, right = sections(build / 'client.txt'), sections(build / 'rust.txt')
if left.keys() != right.keys():
return None
count = 0
for name in left:
a, b = left[name], right[name]
if a == b:
continue
if json.loads(rows[name])['type'] not in LIBM or len(a) != len(b):
return None
for x, y in zip(a, b):
if x != y:
if not close(x, y):
return None
count += 1
return count
def explain(build, cases_path):
rows = cases_path.read_text().splitlines()
left, right = sections(build / 'client.txt'), sections(build / 'rust.txt')
report, count, kinds = '', 0, {}
for name in left:
if left[name] != right.get(name):
count += 1
kind = json.loads(rows[name])['type']
kinds[kind] = kinds.get(kind, 0) + 1
if kinds[kind] <= 1:
a, b = left[name], right.get(name, [])
diff = next(((x, y) for x, y in zip(a, b) if x != y), (f'<{len(a)} lines>', f'<{len(b)} lines>'))
pretty = [' '.join(decode(t) for t in s.split()) for s in diff]
report += f'\n case {name} {rows[name][:160]}\n vanilla: {pretty[0]}\n rust: {pretty[1]}'
return f'\n{count} differing cases by type: {kinds}' + report
def main():
lock, jars, _ = base.verify_artifacts()
libraries = baking.client_libraries()
name, oracle, probe = 'particle-providers-parity', 'VanillaParticleProvidersOracle', 'particle_providers_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_particle_providers_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, libraries, lock['minecraft']['java_major'])
binary = harness.build_probe(build, probe)
# The oracle runs first: the probe replays the particle seeds it recovered.
harness.java_run(build, classes, dependencies, oracle, [cases_path, build / 'client.txt'], 'client')
harness.run_logged([binary, cases_path, build / 'client.txt', build / 'rust.txt'], build, 'rust')
tolerance = 0
try:
matched = base.compare(build / 'client.txt', build / 'rust.txt')
except AssertionError as error:
tolerance = tolerated(build, cases_path)
if tolerance is None:
raise AssertionError(str(error) + explain(build, cases_path)) from None
matched = sum(len(v) + 1 for v in sections(build / 'client.txt').values())
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=matched,
output_sha256=lab.digest(build / 'rust.txt', 'sha256'), libm_tolerated_lines=tolerance,
scope=('Real ParticleResources providers for every type Horizon implements, ticked in an air level with an optional '
'stone floor: construction (provider, level, SpellParticle and particle-local random draws), per-tick '
'position, previous position, motion, age, lifetime, removal, onGround, quad size at partial 0 and 0.5, '
'colour, alpha, roll, sprite, UVs and light at partial 0.5 (unloaded chunk), and the particles and sounds '
'requested from the level. Fluids, block light, render layers/facing and the ParticleEngine group limits '
'are not exercised.')))
print(f'{units:,} particle cases match the pinned client ({matched:,} output lines, {tolerance} within '
f'the libm tolerance): {report}', flush=True)
if __name__ == '__main__':
main()