From b723ef98282004a2b88bba90c8abc7086e478080 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:34:26 +0200 Subject: [PATCH 01/13] Rain and snow: tile the weather texture like WeatherEffectRenderer (#71) Horizon stretched a quarter of rain.png over each whole column, up to 20 blocks tall, so streaks were about five times too long. Vanilla advances v by a quarter per block and lets the sampler repeat, so the texture repeats every 4 blocks. Port createRainColumnInstance, createSnowColumnInstance and prepareInstances exactly (seeded column speed, game-time scroll, snow drift and brightening, camera-block size table, square radius from the Weather Radius option, alpha falloff, precipitation at the camera's y), and split each quad at the texture seams so the atlas sprite repeats. tools/test_weather_render_parity.py compares the columns and quads with the shipped renderer. Co-Authored-By: Claude Opus 5.5 --- .../examples/weather_fixture.rs | 59 ++++ crates/horizon-client/src/game.rs | 120 ++++---- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/weather.rs | 273 ++++++++++++++++++ .../parity/VanillaWeatherRenderOracle.java | 87 ++++++ tools/test_weather_render_parity.py | 39 +++ 6 files changed, 517 insertions(+), 62 deletions(-) create mode 100644 crates/horizon-client/examples/weather_fixture.rs create mode 100644 crates/horizon-client/src/weather.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWeatherRenderOracle.java create mode 100644 tools/test_weather_render_parity.py diff --git a/crates/horizon-client/examples/weather_fixture.rs b/crates/horizon-client/examples/weather_fixture.rs new file mode 100644 index 000000000..15aab6bdb --- /dev/null +++ b/crates/horizon-client/examples/weather_fixture.rs @@ -0,0 +1,59 @@ +//! WeatherEffectRenderer column instances and quads, without a GPU. +use horizon_client::weather; +use std::{fmt::Write, fs}; +fn bits(value: f32) -> String { + if value.is_nan() { + "nan".into() + } else { + format!("{:x}", value.to_bits()) + } +} +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let mut output = String::new(); + for (case, line) in fs::read_to_string(&args[1])?.lines().enumerate() { + let p: Vec<&str> = line.split_whitespace().collect(); + let int = |i: usize| p[i].parse::().unwrap(); + let kind = int(0); + let ticks: i64 = p[1].parse()?; + let (x, bottom, top, z, light) = (int(2), int(3), int(4), int(5), int(6)); + let partial: f32 = p[7].parse()?; + let camera = [p[8].parse()?, p[9].parse()?, p[10].parse()?]; + let radius = int(11); + let intensity: f32 = p[12].parse()?; + let mut random = weather::column_random(x, z); + let column = if kind == 0 { + weather::rain_column(&mut random, ticks, x, bottom, top, z, light, partial) + } else { + weather::snow_column(&mut random, ticks, x, bottom, top, z, light, partial) + }; + write!( + output, + "{case} {} {} {} {} {} {} {}", + column.x, + column.z, + column.bottom_y, + column.top_y, + bits(column.u_offset), + bits(column.v_offset), + column.light_coords + )?; + let max_alpha = if kind == 0 { 1.0 } else { 0.8 }; + for v in weather::column_quad(&column, camera, max_alpha, radius, intensity) { + write!( + output, + " |{},{},{},{},{},{:x},{}", + bits(v.pos[0]), + bits(v.pos[1]), + bits(v.pos[2]), + bits(v.uv[0]), + bits(v.uv[1]), + v.color, + v.light_coords + )?; + } + output.push('\n'); + } + fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..1b05c0781 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6693,10 +6693,11 @@ impl Game<'_> { } } } - /// WeatherEffectRenderer: rain/snow columns within 10 blocks. + /// WeatherEffectRenderer: rain and snow columns within the weather radius. fn weather_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let (rain, _) = self.world.weather.levels(alpha as f32); - if rain <= 0.0 { + use horizon_client::weather; + let (intensity, _) = self.world.weather.levels(alpha as f32); + if intensity <= 0.0 { return; } let atlas = &self.res.atlas; @@ -6711,76 +6712,71 @@ impl Game<'_> { camera.y.floor() as i32, camera.z.floor() as i32, ); - let radius = 10; - let time = self.ticks as f32 + alpha as f32; - for dz in -radius..=radius { - for dx in -radius..=radius { - let (x, z) = (cx + dx, cz + dz); - let d2 = (dx * dx + dz * dz) as f32; - if d2 > (radius * radius) as f32 { - continue; - } + let radius = self.settings.weather_radius; + let ticks = self.world.game_time; + let partial = alpha as f32; + let eye = [camera.x, camera.y, camera.z]; + // Vanilla draws every rain column before the snow ones. + let mut columns = (Vec::new(), Vec::new()); + for z in cz - radius..=cz + radius { + for x in cx - radius..=cx + radius { let top = self.rain_height(x, z, cy + radius + 10); let y0 = (cy - radius).max(top); let y1 = (cy + radius).max(top); - if y0 >= y1 { + if y1 == y0 { continue; } - let Some(snow) = self.precipitation(x, top, z) else { + let Some(snow) = self.precipitation(x, cy, z) else { continue; }; - let hash = (x - .wrapping_mul(x) - .wrapping_mul(3121) - .wrapping_add(x.wrapping_mul(45_238_971)) - ^ z.wrapping_mul(z) - .wrapping_mul(418_711) - .wrapping_add(z.wrapping_mul(13761))) - & 31; - let r = if snow { snow_tex } else { rain_tex }; - // Columns face the camera horizontally. - let (fx, fz) = (f64::from(x) + 0.5 - camera.x, f64::from(z) + 0.5 - camera.z); - let len = (fx * fx + fz * fz).sqrt().max(1e-3); - let (sx, sz) = ((-fz / len * 0.5) as f32, (fx / len * 0.5) as f32); - let center = glam::Vec3::new(fx as f32, 0.0, fz as f32); - let scroll = if snow { - (time / 512.0 + hash as f32 / 32.0) % 1.0 - } else { - ((time + hash as f32) / 32.0 * (3.0 + (hash % 5) as f32 * 0.25)) % 1.0 - }; - let fade = ((1.0 - d2 / (radius * radius) as f32) * 0.5 + 0.5) * rain; - let a = (fade.clamp(0.0, 1.0) * 255.0) as u32; - let color = a << 24 | 0xFF_FFFF; + let mut random = weather::column_random(x, z); let light = self.world.light(x, top.max(cy), z); - let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let (b, t) = ( - (f64::from(y0) - camera.y) as f32, - (f64::from(y1) - camera.y) as f32, - ); - let vh = r.v1 - r.v0; - let corners = [ - center + glam::Vec3::new(-sx, b, -sz), - center + glam::Vec3::new(sx, b, sz), - center + glam::Vec3::new(sx, t, sz), - center + glam::Vec3::new(-sx, t, -sz), - ]; - // The rain texture is a vertical strip; sample a scrolling window of it. - let s0 = scroll * 0.75; - let uv0 = r.v0 + vh * s0; - let uv1 = r.v0 + vh * (s0 + 0.25); - let uvs = [[r.u0, uv1], [r.u1, uv1], [r.u1, uv0], [r.u0, uv0]]; - for (p, uv) in corners.iter().zip(uvs) { - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 0, - color, - light: packed, - }); + let coords = i32::from(light & 15) << 4 | i32::from(light >> 4) << 20; + if snow { + columns.1.push(weather::snow_column( + &mut random, + ticks, + x, + y0, + y1, + z, + coords, + partial, + )); + } else { + columns.0.push(weather::rain_column( + &mut random, + ticks, + x, + y0, + y1, + z, + coords, + partial, + )); } } } + let rain = columns.0.iter().map(|c| (c, 1.0, rain_tex)); + let snow = columns.1.iter().map(|c| (c, 0.8, snow_tex)); + for (column, max_alpha, r) in rain.chain(snow) { + let quad = weather::column_quad(column, eye, max_alpha, radius, intensity); + let color = quad[0].color; + let lc = quad[0].light_coords; + let light = ((lc >> 20 & 15) * 16) as u32 | (((lc >> 4 & 15) * 16) as u32) << 8; + weather::tile(&quad, |pos, uvs| { + for (p, [u, v]) in pos.into_iter().zip(uvs) { + out.push(Vertex { + normal: [0; 4], + pos: p, + uv: [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v], + layer: 0, + color, + light, + }); + } + }); + } } /// Player.startSleepInBed: night or thunder, no monsters within 8 blocks; /// the bed becomes the respawn point either way. diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index e5c753c09..044ee3304 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -130,6 +130,7 @@ pub mod title; pub mod ui; pub mod ui_theme; pub mod vanillagen; +pub mod weather; pub mod widgets; pub mod window; pub mod world; diff --git a/crates/horizon-client/src/weather.rs b/crates/horizon-client/src/weather.rs new file mode 100644 index 000000000..71892686c --- /dev/null +++ b/crates/horizon-client/src/weather.rs @@ -0,0 +1,273 @@ +//! Rain and snow columns around the camera (`WeatherEffectRenderer`). +//! +//! Vanilla draws each column as one camera-facing quad whose texture +//! coordinates run past 0..1 (`v` advances a quarter of the texture per block, +//! so `rain.png` repeats every 4 blocks) and relies on a repeating sampler. +//! Horizon samples the sprite from its atlas, so [`tile`] splits a quad at +//! every whole texture repeat into pieces that stay inside the sprite. +use horizon_core::random::{LegacyRandom, RandomSource}; + +/// `WeatherEffectRenderer.ColumnInstance`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Column { + pub x: i32, + pub z: i32, + pub bottom_y: i32, + pub top_y: i32, + pub u_offset: f32, + pub v_offset: f32, + /// Vanilla packed light (`LightCoordsUtil.pack`: block << 4 | sky << 20). + pub light_coords: i32, +} + +/// One vertex of a column quad, in vanilla's emission order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct ColumnVertex { + /// Camera-relative position. + pub pos: [f32; 3], + /// Texture coordinates before wrapping (the sampler repeats). + pub uv: [f32; 2], + /// ARGB (`ARGB.white(alpha)`). + pub color: u32, + pub light_coords: i32, +} + +/// The random seed of a column (`extractRenderState`). +pub fn column_seed(x: i32, z: i32) -> i32 { + (x.wrapping_mul(x) + .wrapping_mul(3121) + .wrapping_add(x.wrapping_mul(45_238_971))) + ^ (z.wrapping_mul(z) + .wrapping_mul(418_711) + .wrapping_add(z.wrapping_mul(13761))) +} + +/// The column's random source, seeded as `random.setSeed(seed)`. +pub fn column_random(x: i32, z: i32) -> LegacyRandom { + LegacyRandom::new(i64::from(column_seed(x, z))) +} + +/// `createRainColumnInstance`. +#[allow(clippy::too_many_arguments)] +pub fn rain_column( + random: &mut impl RandomSource, + ticks: i64, + x: i32, + bottom_y: i32, + top_y: i32, + z: i32, + light_coords: i32, + partial: f32, +) -> Column { + let wrapped_ticks = (ticks & 131_071) as i32; + let tick_offset = x + .wrapping_mul(x) + .wrapping_mul(3121) + .wrapping_add(x.wrapping_mul(45_238_971)) + .wrapping_add(z.wrapping_mul(z).wrapping_mul(418_711)) + .wrapping_add(z.wrapping_mul(13761)) + & 0xFF; + let speed = 3.0 + random.next_float(); + let offset = -((wrapped_ticks + tick_offset) as f32 + partial) / 32.0 * speed; + Column { + x, + z, + bottom_y, + top_y, + u_offset: 0.0, + v_offset: offset % 32.0, + light_coords, + } +} + +/// `createSnowColumnInstance`: snow drifts sideways and is brightened. +#[allow(clippy::too_many_arguments)] +pub fn snow_column( + random: &mut impl RandomSource, + ticks: i64, + x: i32, + bottom_y: i32, + top_y: i32, + z: i32, + light_coords: i32, + partial: f32, +) -> Column { + let wrapped_ticks = (ticks & 131_071) as i32; + let time = wrapped_ticks as f32 + partial; + let u = random.next_double(); + let u = (u + f64::from(time * 0.01 * random.next_gaussian() as f32)) as f32; + let v = random.next_double(); + let v = (v + f64::from(time * random.next_gaussian() as f32 * 0.001)) as f32; + let v_offset = -((ticks & 511) as f32 + partial) / 512.0; + let (block, sky) = (light_coords >> 4 & 15, light_coords >> 20 & 15); + Column { + x, + z, + bottom_y, + top_y, + u_offset: u, + v_offset: v_offset + v, + light_coords: ((block * 3 + 15) / 4) << 4 | ((sky * 3 + 15) / 4) << 20, + } +} + +/// The constructor's 32x32 table of horizontal column half-widths, indexed +/// relative to the camera block. The camera's own column divides 0 by 0. +fn column_size(index: usize) -> (f32, f32) { + let delta_x = (index % 32) as f32 - 16.0; + let delta_z = (index / 32) as f32 - 16.0; + let distance = f64::from(delta_x * delta_x + delta_z * delta_z).sqrt() as f32; + (-delta_z / distance, delta_x / distance) +} + +/// `prepareInstances` for one column: rain uses `max_alpha` 1, snow 0.8. +pub fn column_quad( + column: &Column, + camera: [f64; 3], + max_alpha: f32, + radius: i32, + intensity: f32, +) -> [ColumnVertex; 4] { + let radius_sq = (radius * radius) as f32; + let relative_x = (f64::from(column.x) + 0.5 - camera[0]) as f32; + let relative_z = (f64::from(column.z) + 0.5 - camera[2]) as f32; + let distance_sq = relative_x * relative_x + relative_z * relative_z; + let t = (distance_sq / radius_sq).min(1.0); + let alpha = (max_alpha + t * (0.5 - max_alpha)) * intensity; + let color = ((alpha * 255.0).floor() as i32 as u32) << 24 | 0xFF_FFFF; + let index = + (column.z - camera[2].floor() as i32 + 16) * 32 + column.x - camera[0].floor() as i32 + 16; + let (size_x, size_z) = column_size(index as usize); + let (half_x, half_z) = (size_x / 2.0, size_z / 2.0); + let (x0, x1) = (relative_x - half_x, relative_x + half_x); + let y1 = (f64::from(column.top_y) - camera[1]) as f32; + let y0 = (f64::from(column.bottom_y) - camera[1]) as f32; + let (z0, z1) = (relative_z - half_z, relative_z + half_z); + let (u0, u1) = (column.u_offset, column.u_offset + 1.0); + let v0 = column.bottom_y as f32 * 0.25 + column.v_offset; + let v1 = column.top_y as f32 * 0.25 + column.v_offset; + let vertex = |pos, uv| ColumnVertex { + pos, + uv, + color, + light_coords: column.light_coords, + }; + [ + vertex([x0, y1, z0], [u0, v0]), + vertex([x1, y1, z1], [u1, v0]), + vertex([x1, y0, z1], [u1, v1]), + vertex([x0, y0, z0], [u0, v1]), + ] +} + +/// Split a column quad (vertices as [`column_quad`] emits them: top edge +/// `u0..u1` at `v0`, bottom edge at `v1`) at every whole texture repeat. +/// Each piece gets positions on the quad and texture coordinates in `0..=1` +/// of one repeat, ready to map onto an atlas sprite. +pub fn tile(quad: &[ColumnVertex; 4], mut emit: impl FnMut([[f32; 3]; 4], [[f32; 2]; 4])) { + let [u0, v0] = quad[0].uv; + let [u1, v1] = quad[2].uv; + let (top_left, top_right) = (quad[0].pos, quad[1].pos); + let (bottom_right, bottom_left) = (quad[2].pos, quad[3].pos); + let lerp3 = |a: [f32; 3], b: [f32; 3], t: f32| -> [f32; 3] { + std::array::from_fn(|i| a[i] + (b[i] - a[i]) * t) + }; + // Position at fraction s across (u) and t down (v) the quad. + let at = |s: f32, t: f32| { + lerp3( + lerp3(top_left, top_right, s), + lerp3(bottom_left, bottom_right, s), + t, + ) + }; + let cuts = |a: f32, b: f32| { + let mut cuts = vec![a]; + let mut k = a.floor() + 1.0; + while k < b { + cuts.push(k); + k += 1.0; + } + cuts.push(b); + cuts + }; + if !(u1 > u0 && v1 > v0) { + return; + } + let (us, vs) = (cuts(u0, u1), cuts(v0, v1)); + for v in vs.windows(2) { + let repeat_v = v[0].floor(); + let (ta, tb) = ((v[0] - v0) / (v1 - v0), (v[1] - v0) / (v1 - v0)); + let (la, lb) = (v[0] - repeat_v, v[1] - repeat_v); + for u in us.windows(2) { + let repeat_u = u[0].floor(); + let (sa, sb) = ((u[0] - u0) / (u1 - u0), (u[1] - u0) / (u1 - u0)); + let (ka, kb) = (u[0] - repeat_u, u[1] - repeat_u); + emit( + [at(sa, ta), at(sb, ta), at(sb, tb), at(sa, tb)], + [[ka, la], [kb, la], [kb, lb], [ka, lb]], + ); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rain_repeats_every_four_blocks() { + let column = Column { + x: 3, + z: 0, + bottom_y: 60, + top_y: 80, + u_offset: 0.0, + v_offset: 0.0, + light_coords: 15 << 20, + }; + let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0); + // 20 blocks of rain: five repeats of the texture, split at each seam. + let mut pieces = Vec::new(); + tile(&quad, |pos, uv| pieces.push((pos, uv))); + assert_eq!(pieces.len(), 5); + for (pos, uv) in &pieces { + assert!(((pos[0][1] - pos[3][1]) - 4.0).abs() < 1e-4); + assert_eq!(uv[0], [0.0, 0.0]); + assert_eq!(uv[2], [1.0, 1.0]); + } + } + + #[test] + fn snow_drifts_across_one_seam() { + let column = Column { + x: 3, + z: 2, + bottom_y: 64, + top_y: 66, + u_offset: 0.25, + v_offset: 0.0, + light_coords: 0, + }; + let quad = column_quad(&column, [0.5, 70.0, 0.5], 0.8, 10, 1.0); + let mut pieces = Vec::new(); + tile(&quad, |pos, uv| pieces.push((pos, uv))); + assert_eq!(pieces.len(), 2); + assert_eq!(pieces[0].1[0], [0.25, 0.0]); + assert_eq!(pieces[1].1[2], [0.25, 0.5]); + } + + #[test] + fn camera_column_is_degenerate() { + let column = Column { + x: 0, + z: 0, + bottom_y: 60, + top_y: 80, + u_offset: 0.0, + v_offset: 0.0, + light_coords: 0, + }; + let quad = column_quad(&column, [0.5, 70.0, 0.5], 1.0, 10, 1.0); + assert!(quad[0].pos[0].is_nan()); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWeatherRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWeatherRenderOracle.java new file mode 100644 index 000000000..fccd3083e --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWeatherRenderOracle.java @@ -0,0 +1,87 @@ +package dev.horizonlab.parity; + +import com.mojang.blaze3d.vertex.VertexConsumer; +import java.lang.reflect.Proxy; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import net.minecraft.client.renderer.WeatherEffectRenderer; +import net.minecraft.util.RandomSource; +import net.minecraft.world.phys.Vec3; + +/** Build rain and snow column quads with the shipped renderer, without a GPU or a level. */ +public final class VanillaWeatherRenderOracle { + public static void main(String[] args) throws Exception { + Class unsafeClass = Class.forName("sun.misc.Unsafe"); + var theUnsafe = unsafeClass.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + Object renderer = unsafeClass.getMethod("allocateInstance", Class.class) + .invoke(theUnsafe.get(null), WeatherEffectRenderer.class); + // The constructor's column table, built the same way before it reaches Minecraft.getInstance(). + float[] sizeX = new float[1024], sizeZ = new float[1024]; + for (int z = 0; z < 32; z++) { + for (int x = 0; x < 32; x++) { + float deltaX = x - 16, deltaZ = z - 16; + float distance = net.minecraft.util.Mth.length(deltaX, deltaZ); + sizeX[z * 32 + x] = -deltaZ / distance; + sizeZ[z * 32 + x] = deltaX / distance; + } + } + for (String name : new String[]{"columnSizeX", "columnSizeZ"}) { + var field = WeatherEffectRenderer.class.getDeclaredField(name); + field.setAccessible(true); + field.set(renderer, name.endsWith("X") ? sizeX : sizeZ); + } + var rain = WeatherEffectRenderer.class.getDeclaredMethod("createRainColumnInstance", + RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class); + var snow = WeatherEffectRenderer.class.getDeclaredMethod("createSnowColumnInstance", + RandomSource.class, long.class, int.class, int.class, int.class, int.class, int.class, float.class); + var prepare = WeatherEffectRenderer.class.getDeclaredMethod("prepareInstances", + VertexConsumer.class, List.class, Vec3.class, float.class, int.class, float.class); + rain.setAccessible(true); + snow.setAccessible(true); + prepare.setAccessible(true); + StringBuilder output = new StringBuilder(); + int index = 0; + for (String line : Files.readAllLines(Path.of(args[0]))) { + String[] p = line.split(" "); + int kind = Integer.parseInt(p[0]); + long ticks = Long.parseLong(p[1]); + int x = Integer.parseInt(p[2]), bottom = Integer.parseInt(p[3]), top = Integer.parseInt(p[4]); + int z = Integer.parseInt(p[5]), light = Integer.parseInt(p[6]); + float partial = Float.parseFloat(p[7]); + Vec3 camera = new Vec3(Double.parseDouble(p[8]), Double.parseDouble(p[9]), Double.parseDouble(p[10])); + int radius = Integer.parseInt(p[11]); + float intensity = Float.parseFloat(p[12]); + // extractRenderState: the column random is reseeded per column. + RandomSource random = RandomSource.createThreadLocalInstance(0L); + random.setSeed(x * x * 3121 + x * 45238971 ^ z * z * 418711 + z * 13761); + Object column = (kind == 0 ? rain : snow).invoke(renderer, random, ticks, x, bottom, top, z, light, partial); + var record = (WeatherEffectRenderer.ColumnInstance) column; + output.append(index++).append(' ').append(record.x()).append(' ').append(record.z()).append(' ') + .append(record.bottomY()).append(' ').append(record.topY()).append(' ') + .append(bits(record.uOffset())).append(' ').append(bits(record.vOffset())).append(' ') + .append(record.lightCoords()); + StringBuilder vertices = new StringBuilder(); + VertexConsumer consumer = (VertexConsumer) Proxy.newProxyInstance( + VertexConsumer.class.getClassLoader(), new Class[]{VertexConsumer.class}, (proxy, method, a) -> { + switch (method.getName()) { + case "addVertex" -> vertices.append(" |").append(bits((Float) a[0])).append(',') + .append(bits((Float) a[1])).append(',').append(bits((Float) a[2])); + case "setUv" -> vertices.append(',').append(bits((Float) a[0])).append(',').append(bits((Float) a[1])); + case "setColor" -> vertices.append(',').append(Integer.toHexString((Integer) a[0])); + case "setLight" -> vertices.append(',').append((Integer) a[0]); + default -> throw new IllegalStateException("unexpected " + method); + } + return proxy; + }); + prepare.invoke(renderer, consumer, List.of(column), camera, kind == 0 ? 1.0F : 0.8F, radius, intensity); + output.append(vertices).append('\n'); + } + Files.writeString(Path.of(args[1]), output); + } + + private static String bits(float value) { + return Float.isNaN(value) ? "nan" : Integer.toHexString(Float.floatToRawIntBits(value)); + } +} diff --git a/tools/test_weather_render_parity.py b/tools/test_weather_render_parity.py new file mode 100644 index 000000000..af713ec80 --- /dev/null +++ b/tools/test_weather_render_parity.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Compare rain and snow column instances and quads (positions, texture coordinates, alpha, light) with 26.3.""" +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(71) + cases = [] + for kind in (0, 1): + for ticks in (0, 1, 511, 512, 131071, 131072, 24000 * 37 + 5, 9_000_000_123): + for x, z in ((0, 0), (1, 0), (0, -1), (3, 7), (-10, 10), (10, -10), (-4, -9), (1_000_003, -2_000_011)): + for bottom, top in ((60, 80), (64, 65), (-64, -44), (300, 310)): + light = (rng.randrange(16) << 4) | (rng.randrange(16) << 20) + partial = rng.choice(("0.0", "0.5", "0.999", f"{rng.random():.6f}")) + cam = (x + rng.uniform(-10.5, 10.5), rng.uniform(bottom - 5, top + 5), z + rng.uniform(-10.5, 10.5)) + camera = " ".join(f"{c:.9f}" for c in cam) + radius = rng.choice((3, 5, 10)) + intensity = rng.choice(("1.0", "0.25", f"{rng.random():.6f}")) + cases.append(f"{kind} {ticks} {x} {bottom} {top} {z} {light} {partial} {camera} {radius} {intensity}\n") + # The camera's own column: the size table divides 0 by 0. + cases.append("0 100 5 60 80 5 240 0.0 5.5 70.0 5.5 10 1.0\n") + inputs = build / "inputs.txt" + inputs.write_text("".join(cases)) + return inputs, len(cases) + + +def main(): + harness.differential("weather-render-parity", "VanillaWeatherRenderOracle", "weather_fixture", make_input, + "Rain/snow column instances and quad vertices; not full framebuffer parity.", + sources=[lab.ROOT / "crates/horizon-client/src/weather.rs"]) + + +if __name__ == "__main__": + main() From 8c0586db4b290a66a7e3adb52cee143378ccbff8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:34:32 +0200 Subject: [PATCH 02/13] Furnaces keep their cooking progress across menu clicks A click in the furnace menu reset the cooking timer whatever it did. AbstractFurnaceBlockEntity.setItem restarts cooking only when the input slot gets something other than the same item with the same components, and menu clicks that take part of the input or merge into it never call it. Furnace::input_clicked applies that after each click, with the new input's total cook time. test_menu_click_parity gains furnace_be, blast_furnace_be and smoker_be: the server's furnace menus over real block entities, comparing the cooking data slots after every click. Fixes #69 Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 38 +++++++++++++++++-- crates/horizon-client/src/containers.rs | 26 +++++++++++++ crates/horizon-client/src/game.rs | 23 +++++------ .../horizonlab/parity/VanillaMenuOracle.java | 28 ++++++++++++++ tools/test_menu_click_parity.py | 25 ++++++++++-- 5 files changed, 123 insertions(+), 17 deletions(-) diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 2434a5b5d..863e3786e 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -1,9 +1,11 @@ //! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per //! line (menu, creative, slots, carried, data, ops) and prints the oracle's -//! state lines after every click. +//! state lines after every click. The `*_be` furnace menus run over a furnace +//! block entity: its data slots follow `Furnace::input_clicked`. //! //! usage: menu_fixture RESOURCES INPUT OUTPUT use horizon_client::{ + containers::{Furnace, FurnaceKind}, crafting::Recipes, item_data::{canon_stack, parse_stack}, items::Items, @@ -46,7 +48,20 @@ fn main() -> horizon_client::Result<()> { let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; - let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?; + let name = case["menu"].as_str().unwrap_or_default(); + // FurnaceMenu over the server's AbstractFurnaceBlockEntity. + let furnace_kind = match name { + "furnace_be" => Some(FurnaceKind::Furnace), + "blast_furnace_be" => Some(FurnaceKind::BlastFurnace), + "smoker_be" => Some(FurnaceKind::Smoker), + _ => None, + }; + let kind = Kind::parse( + name.strip_suffix("_be") + .filter(|_| furnace_kind.is_some()) + .unwrap_or(name), + ) + .ok_or("menu kind")?; let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { @@ -57,6 +72,15 @@ fn main() -> horizon_client::Result<()> { for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { menu.data[i] = v.as_i64().unwrap_or(0) as i32; } + let mut furnace = furnace_kind.map(|kind| Furnace { + kind, + items: [0, 1, 2].map(|i| menu.slot(i).cloned()), + lit_remaining: menu.data[0], + lit_total: menu.data[1], + cooking_timer: menu.data[2], + cooking_total: menu.data[3], + speed: 1.0, + }); menu.drops.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { @@ -80,7 +104,15 @@ fn main() -> horizon_client::Result<()> { _ => {} } let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; - match menu.click(&env, slot, button, kind) { + let clicked = menu.click(&env, slot, button, kind); + if let Some(f) = furnace.as_mut() { + let before = f.items[0].clone(); + f.items = [0, 1, 2].map(|i| menu.slot(i).cloned()); + f.input_clicked(&recipes, before); + menu.data[2] = f.cooking_timer; + menu.data[3] = f.cooking_total; + } + match clicked { Ok(()) => out += &format!("{}\n", state(&menu)), Err(name) => out += &format!("error {name}\n"), } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index abb72583d..9688af5eb 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -427,6 +427,32 @@ fn remainder(item: &str) -> Option<&'static str> { } } impl Furnace { + /// `AbstractFurnaceBlockEntity.setItem` on the input slot: anything but + /// the same item with the same components restarts cooking, with the + /// total time of the new input's recipe (200 ticks without one). + pub fn set_input(&mut self, recipes: &Recipes, stack: Option) { + let same = match (&self.items[0], &stack) { + (Some(old), Some(new)) => old.same_item_same_components(new), + _ => false, + }; + self.items[0] = stack; + if !same { + self.cooking_total = self.items[0] + .as_ref() + .and_then(|input| recipes.cook(self.kind.recipe_type(), input)) + .map_or(200, |recipe| total_time(recipe.time, self.speed)); + self.cooking_timer = 0; + } + } + /// A menu click wrote its slots into `items`, and `before` was the input + /// slot until then: the menu called `setItem` on it only if it changed + /// (`Slot.setByPlayer`; partial takes and merges keep the stack). + pub fn input_clicked(&mut self, recipes: &Recipes, before: Option) { + if self.items[0] != before { + let after = std::mem::replace(&mut self.items[0], before); + self.set_input(recipes, after); + } + } /// One server tick. Returns `Some(lit)` when the LIT block state must change. pub fn tick( &mut self, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..b1eb2b0c0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4015,7 +4015,8 @@ impl Game<'_> { .container .and_then(|k| self.world.block_entities.get_mut(&k)) { - f.cooking_timer = 0; + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(&self.res.recipes, before[0].clone()); } self.apply_equipment(); true @@ -4205,15 +4206,8 @@ impl Game<'_> { } return; } - if is_furnace - && slot == 300 - && let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - // Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem). - f.cooking_timer = 0; - } + // Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem). + let furnace_input = (is_furnace && slot == 300).then(|| self.slot_mut(300).clone()); if slot == 200 { // ResultSlot: take the crafted stack and consume one of each ingredient. let mut crafted = 0; @@ -4324,8 +4318,15 @@ impl Game<'_> { } (Some(c), Some(s)) => (Some(c), Some(s)), }; - *self.slot_mut(slot) = new_slot; self.carried = new_carried; + *self.slot_mut(slot) = new_slot; + if let Some(before) = furnace_input + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.input_clicked(&self.res.recipes, before); + } } /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index f6d0c41ef..8a5adc5c2 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -82,6 +82,9 @@ public final class VanillaMenuOracle { @Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { } @Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; } @Override public void gameEvent(net.minecraft.core.Holder e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + // BlockEntity.setChanged of the "*_be" furnaces: no chunks here. + @Override public void blockEntityChanged(BlockPos pos) { } + @Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) { } } static final class FakePlayer extends ServerPlayer { @@ -145,6 +148,31 @@ public final class VanillaMenuOracle { throw new AssertionError(e); } } + case "furnace_be", "blast_furnace_be", "smoker_be" -> { + // The server's menu: the block entity is the container and its data, + // so AbstractFurnaceBlockEntity.setItem restarts cooking. + net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity be = switch (kind) { + case "furnace_be" -> new net.minecraft.world.level.block.entity.FurnaceBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.FURNACE.defaultBlockState()); + case "blast_furnace_be" -> new net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.BLAST_FURNACE.defaultBlockState()); + default -> new net.minecraft.world.level.block.entity.SmokerBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.SMOKER.defaultBlockState()); + }; + be.setLevel(player.world); + try { + Field data = net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity.class.getDeclaredField("dataAccess"); + data.setAccessible(true); + ContainerData furnaceData = (ContainerData) data.get(be); + yield switch (kind) { + case "furnace_be" -> new FurnaceMenu(0, inv, be, furnaceData); + case "blast_furnace_be" -> new BlastFurnaceMenu(0, inv, be, furnaceData); + default -> new SmokerMenu(0, inv, be, furnaceData); + }; + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } case "loom" -> new LoomMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 3a02efdb1..b6e43e020 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -8,7 +8,9 @@ sequences covering every ContainerInput (pickup, quick move, swap, clone, throw, the three quick craft drags, pickup all) over the player inventory, crafting table, chests, hopper, dispenser, shulker box, the furnaces, the brewing stand, the crafter (the client's menu, and the server's over the block -entity with slot state packets) and the loom (with its pattern buttons). After +entity with slot state packets), the loom (with its pattern buttons) and the +server's furnace menus over their block entities (`*_be`: a new input restarts +cooking, other clicks keep its progress). After every click the slots, carried stack, data slots and drops are compared. """ import argparse @@ -22,8 +24,9 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, - 'crafter_be': 46, 'loom': 40} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1} + 'crafter_be': 46, 'loom': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, + 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] PATTERNS = ['minecraft:' + p for p in ('base', 'square_bottom_left', 'stripe_bottom', 'cross', 'border', 'gradient', @@ -180,13 +183,29 @@ def main(): slots[0] = '-' if menu in ('inventory', 'crafting') and rng.random() < 0.6: g.recipe(slots, 2 if menu == 'inventory' else 3) + if menu.endswith('_be') and menu != 'crafter_be' and rng.random() < 0.7: + # Mostly something cooking: a smeltable input, the same in the + # inventory and in hand, so merges and partial takes happen. + food = snbt('minecraft:' + rng.choice(['raw_iron', 'beef', 'potato', 'sand', 'cobblestone', 'oak_log']), + rng.choice([1, 2, 5, 32, 64])) + slots[0] = food + for i in rng.sample(range(3, size), 4): + slots[i] = food if rng.random() < 0.6 else g.stack() + carried_food = food if rng.random() < 0.5 else None + else: + carried_food = None def datum(i): + if menu.endswith('_be') and menu != 'crafter_be': + # litTimeRemaining, litTotalTime, cookingTimer, cookingTotalTime + return [rng.choice([0, 37, 1600]), 1600, rng.choice([0, 1, 57, 199]), rng.choice([200, 100])][i] if menu in ('crafter', 'crafter_be'): return rng.choice([0, 0, 1]) if menu == 'loom': return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) return 0 carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-' + if carried_food is not None: + carried = carried_food cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, 'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))], 'ops': g.ops(size, menu)}) From 12eca8a5c139f4f47711b45101279b8417763ea7 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:38:52 +0200 Subject: [PATCH 03/13] Clouds: draw to the Cloud Distance option, not the render distance (#67) The cloud mesh radius came from the render distance, the far plane was capped at max(4 x render distance, 1024) and the cloud fog end was a constant 2048, so lowering the render distance cut the clouds short. Vanilla ties all three to options.cloudRange: CloudRenderer.prepare builds ceil(range * 16 / 12) cells, Camera.depthFar is max(4 x render distance, range * 16) (also the hand projection, the frustum and the world border), and AtmosphericFogEnvironment ends cloud fog at min(range * 16, visual/cloud_fog_end_distance). The cloud render harness now checks the radius for Cloud Distance 2..128 against the shipped mesh builder, and the environment harness covers visual/cloud_fog_end_distance. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/cloud_fixture.rs | 7 ++++- .../examples/environment_fixture.rs | 4 +++ crates/horizon-client/src/camera.rs | 13 +++++++++ crates/horizon-client/src/clouds.rs | 12 ++++++++ crates/horizon-client/src/environment.rs | 6 ++++ crates/horizon-client/src/fog.rs | 28 ++++++++++++++++++- crates/horizon-client/src/game.rs | 11 ++++++-- crates/horizon-client/src/game/render_tick.rs | 1 + crates/horizon-client/src/gfx.rs | 13 +++++---- .../parity/VanillaCloudRenderOracle.java | 8 ++++-- tools/test_cloud_render_parity.py | 6 +++- 11 files changed, 95 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/examples/cloud_fixture.rs b/crates/horizon-client/examples/cloud_fixture.rs index e21f3386e..7c00bfb3a 100644 --- a/crates/horizon-client/examples/cloud_fixture.rs +++ b/crates/horizon-client/examples/cloud_fixture.rs @@ -20,10 +20,15 @@ fn main() -> Result<(), Box> { write!(output, " {x},{z},{direction},{}", u8::from(inside)).unwrap(); } }; + let radius = if *kind == 2 { + clouds::radius_cells(*x) + } else { + *x + }; if *kind == 0 { cell(*x, *z, *neighbors); } else { - for (x, z) in clouds::cells(*x) { + for (x, z) in clouds::cells(radius) { cell(x, z, 0); } } diff --git a/crates/horizon-client/examples/environment_fixture.rs b/crates/horizon-client/examples/environment_fixture.rs index 3300df232..d92123a2c 100644 --- a/crates/horizon-client/examples/environment_fixture.rs +++ b/crates/horizon-client/examples/environment_fixture.rs @@ -64,6 +64,10 @@ fn main() -> horizon_client::Result<()> { ); put("visual/fog_start_distance", format!("{:?}", sky.fog_start)); put("visual/fog_end_distance", format!("{:?}", sky.fog_end)); + put( + "visual/cloud_fog_end_distance", + format!("{:?}", sky.cloud_fog_end), + ); out.push_str(&row); out.push_str("}\n"); } diff --git a/crates/horizon-client/src/camera.rs b/crates/horizon-client/src/camera.rs index f74f083cd..17b68ccb9 100644 --- a/crates/horizon-client/src/camera.rs +++ b/crates/horizon-client/src/camera.rs @@ -590,6 +590,12 @@ impl Camera { modify_fov_based_on_death_or_fluid(partial, 70.0, effect_scale, dead, fluid) } } +/// `Camera.update`: the far plane covers four times the render distance and +/// the whole cloud range (`depthFar`). +pub fn depth_far(render_distance_chunks: i32, cloud_range_chunks: i32) -> f32 { + (render_distance_chunks as f32 * 16.0 * 4.0).max((cloud_range_chunks * 16) as f32) +} + /// `Projection.getMatrix` for a perspective set up by `setupPerspective`: /// JOML's `Matrix4f.setPerspective(fov * DEG_TO_RAD, width / height, near, /// far, zZeroToOne)`, column-major. Vanilla passes its planes reversed @@ -768,6 +774,13 @@ pub fn bob_matrix(state: &BobState, damage_tilt_strength: f64, bob_view_option: #[cfg(test)] mod tests { + #[test] + fn depth_far_covers_the_cloud_range() { + // renderDistance 2 with the default Cloud Distance (128 chunks). + assert_eq!(super::depth_far(2, 128), 2048.0); + assert_eq!(super::depth_far(32, 2), 2048.0); + assert_eq!(super::depth_far(12, 12), 768.0); + } use super::*; #[test] fn view_keeps_yaw_at_vertical_pitch_limits() { diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 161edb168..b29fdf7ee 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -32,6 +32,12 @@ pub fn faces(mask: u16) -> impl Iterator { ) } +/// `CloudRenderer.prepare`: the cell radius for the Cloud Distance option +/// (in chunks), independent of the render distance. +pub fn radius_cells(cloud_range_chunks: i32) -> i32 { + ((cloud_range_chunks * 16) as f32 / 12.0).ceil() as i32 +} + /// CloudRenderer builds cells in expanding Manhattan rings, nearest first. pub fn cells(radius: i32) -> impl Iterator { (0..=2 * radius).flat_map(move |ring| { @@ -71,6 +77,12 @@ mod tests { assert_eq!(face_mask(2, 2, 0.0, [false; 4]), 3); } #[test] + fn cloud_distance_sets_the_radius() { + assert_eq!(radius_cells(2), 3); + assert_eq!(radius_cells(12), 16); + assert_eq!(radius_cells(128), 171); + } + #[test] fn connected_cells_have_no_exterior_walls() { assert_eq!(face_mask(2, 2, 10.0, [false; 4]), 1); } diff --git a/crates/horizon-client/src/environment.rs b/crates/horizon-client/src/environment.rs index 43c48af4e..ee2c921d0 100644 --- a/crates/horizon-client/src/environment.rs +++ b/crates/horizon-client/src/environment.rs @@ -139,6 +139,8 @@ pub struct Sky { /// Environmental fog (`visual/fog_start_distance` / `fog_end_distance`). pub fog_start: f32, pub fog_end: f32, + /// `visual/cloud_fog_end_distance`. + pub cloud_fog_end: f32, } impl Environment { pub fn load(root: &Path) -> Result { @@ -299,6 +301,10 @@ impl Environment { .base .get("minecraft:visual/fog_end_distance") .map_or(1024.0, |v| v[0]), + cloud_fog_end: self + .base + .get("minecraft:visual/cloud_fog_end_distance") + .map_or(2048.0, |v| v[0]), } } } diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index dffcf7280..835a36a90 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -196,6 +196,8 @@ pub struct FogInputs<'a> { pub water_fog_color: [f32; 3], pub biome: u16, pub render_distance_chunks: i32, + /// The Cloud Distance option, in chunks. + pub cloud_range_chunks: i32, pub camera_y: f64, pub min_y: i32, /// Flat worlds use a 1-block void darkness range. @@ -335,7 +337,7 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog let min_end = sky.fog_end.min(96.0); fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier); fog.sky_end = rd.min(512.0); - fog.cloud_end = 2048.0f32.min(128.0 * 16.0); + fog.cloud_end = ((input.cloud_range_chunks * 16) as f32).min(sky.cloud_fog_end); } } let span = (rd / 10.0).clamp(4.0, 64.0); @@ -373,6 +375,7 @@ mod tests { water_fog_color: [0.0, 0.0, 0.2], biome: 0, render_distance_chunks: 12, + cloud_range_chunks: 128, camera_y: 70.0, min_y: -64, flat: false, @@ -402,6 +405,29 @@ mod tests { assert_eq!(fog.sky_end, 192.0); } #[test] + fn cloud_fog_ends_at_the_cloud_distance() { + let sky = Sky { + fog_end: 1024.0, + cloud_fog_end: 2048.0, + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.0], + }; + let mut input = inputs(&sky); + input.render_distance_chunks = 2; + input.cloud_range_chunks = 64; + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).cloud_end, + 1024.0 + ); + input.cloud_range_chunks = 128; + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).cloud_end, + 2048.0 + ); + } + #[test] fn water_vision_ramps() { let mut s = FogState::default(); for _ in 0..100 { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..b0c1d1e5a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5090,7 +5090,8 @@ impl Game<'_> { let z_in = (cloud_z - cell_z as f64 * 12.0) as f32; let bottom = (cloud_height - camera.y) as f32; let filled = |cx: i64, cz: i64| cells[(cz.rem_euclid(h) * w + cx.rem_euclid(w)) as usize]; - let radius = (self.streaming.radius * 16 + 11) / 12; + // The Cloud Distance option, not the render distance. + let radius = horizon_client::clouds::radius_cells(self.settings.cloud_range); let c = sky.cloud_color; let color = |shade: f32| { let ch = |v: f32| ((v * shade).clamp(0.0, 1.0) * 255.0) as u32; @@ -7319,10 +7320,12 @@ impl Game<'_> { self.bob_matrix(alpha as f32) }; let distance = (self.streaming.radius * 16) as f32; + let depth_far = + horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range); self.view_frustum = self .renderer .as_ref() - .map(|r| r.camera_frustum(fov_degrees, yaw, pitch, bob, distance)); + .map(|r| r.camera_frustum(fov_degrees, yaw, pitch, bob, depth_far)); let mut entities = if title { Vec::new() } else { @@ -7394,6 +7397,7 @@ impl Game<'_> { bob, sky, distance, + depth_far, underwater, title: title && !live, skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, @@ -7480,7 +7484,8 @@ impl Game<'_> { &mut self.border_state, ); // Camera.depthFar, as the renderer's far plane. - let depth_far = (distance as f32 * 4.0).max(1024.0); + let depth_far = + horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range); if !self .border_renderer .prepare(&self.border_state, camera, distance, depth_far) diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index dd45ef053..50ca678c0 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -83,6 +83,7 @@ impl Game<'_> { ], biome, render_distance_chunks: self.streaming.radius, + cloud_range_chunks: self.settings.cloud_range, camera_y: camera.y, min_y: MIN_Y, flat: false, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index cceedd4c5..f5b92d30b 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -123,6 +123,8 @@ pub struct Frame<'a> { pub sky: Sky, /// Render distance in blocks (fog end). pub distance: f32, + /// `Camera.depthFar`: the far plane (`crate::camera::depth_far`). + pub depth_far: f32, pub underwater: bool, /// Skip sections the camera cannot see through open faces (vanilla's /// occlusion graph; off in spectator-like views inside blocks). @@ -1614,7 +1616,7 @@ impl Renderer { frame.yaw, frame.pitch, frame.bob, - frame.distance, + frame.depth_far, ) } /// The view frustum `render` will cull with, for culling geometry built @@ -1625,15 +1627,14 @@ impl Renderer { yaw: f32, pitch: f32, bob: Mat4, - distance: f32, + depth_far: f32, ) -> Frustum { Frustum { - planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, distance)), + planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, depth_far)), } } - fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, distance: f32) -> Mat4 { + fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, far: f32) -> Mat4 { let aspect = self.config.width as f32 / self.config.height.max(1) as f32; - let far = (distance * 4.0).max(1024.0); Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far) * bob * crate::camera::view_matrix(yaw, pitch) @@ -1865,7 +1866,7 @@ impl Renderer { frame.hand_fov_degrees, self.config.width as f32, self.config.height.max(1) as f32, - (frame.distance * 4.0).max(1024.0), + frame.depth_far, )); let hand_globals = Globals { view_proj: (hand_projection * frame.bob * view).to_cols_array_2d(), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java index c9666e931..e27bf819a 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCloudRenderOracle.java @@ -29,13 +29,17 @@ public final class VanillaCloudRenderOracle { int kind = Integer.parseInt(parts[0]), x = Integer.parseInt(parts[1]), z = Integer.parseInt(parts[2]); int bottom = Integer.parseInt(parts[3]), neighbors = Integer.parseInt(parts[4]); Object pos = positions[bottom > 0 ? 2 : bottom + 4 < 0 ? 0 : 1]; - ByteBuffer buffer = ByteBuffer.allocate(100000); + ByteBuffer buffer = ByteBuffer.allocate(kind == 2 ? 4_000_000 : 100000); if (kind == 0) { long flags = ((neighbors & 1) != 0 ? 8 : 0) | ((neighbors & 2) != 0 ? 2 : 0) | ((neighbors & 4) != 0 ? 1 : 0) | ((neighbors & 8) != 0 ? 4 : 0); cell.invoke(renderer, pos, buffer, x, z, 0xfffffff0L | flags); - } else { + } else if (kind == 1) { mesh.invoke(renderer, pos, buffer, 0, 0, true, x); + } else { + // prepare(..., range, ...): radiusCells from the Cloud Distance option. + int radiusBlocks = x * 16; + mesh.invoke(renderer, pos, buffer, 0, 0, true, net.minecraft.util.Mth.ceil(radiusBlocks / 12.0F)); } output.append(index++); buffer.flip(); diff --git a/tools/test_cloud_render_parity.py b/tools/test_cloud_render_parity.py index 4df4d1668..91f740f91 100644 --- a/tools/test_cloud_render_parity.py +++ b/tools/test_cloud_render_parity.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 -"""Compare fancy cloud exterior/interior faces and nearest-first mesh traversal with 26.3.""" +"""Compare fancy cloud exterior/interior faces, nearest-first mesh traversal and the +cell radius of the Cloud Distance option (independent of the render distance) with 26.3.""" try: from . import lab, oracle_harness as harness except ImportError: @@ -16,6 +17,9 @@ def make_input(build): for radius in range(11): for bottom in (-5, -4, 0, 1): cases.append(f"1 {radius} 0 {bottom} 0\n") + # CloudRenderer.prepare: radius from options.cloudRange (2..128 chunks). + for cloud_range in (2, 3, 4, 7, 8, 12, 32, 64, 127, 128): + cases.append(f"2 {cloud_range} 0 -5 0\n") inputs = build / "inputs.txt" inputs.write_text("".join(cases)) return inputs, len(cases) From 0d3628a0350e6055c0fa7b52fafb92d45312d67f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:00:41 +0200 Subject: [PATCH 04/13] Composters take compostable items by hand, from hoppers and from droppers Right-clicking a composter with wheat (or any compostable item) did nothing: ComposterBlock.useItemOn wasn't implemented, only emptying a full composter. Hoppers and droppers didn't see the composter as a container either, and a hopper under one sucked items through it. - useItemOn: below level 7 a compostable item adds a layer with the chance of its compostable component's provider (evaluated in the block-interaction loot context, drawing from the level random), then level event 1500, the used statistic and one item consumed (none in creative); level 7 still consumes the action; a full composter falls through to useWithoutItem and empties. - Level event 1500 (handleFill): composter.fill(_success) and ten composter particles above the compost. - getContainer: the input container takes one compostable item from above (hoppers, droppers, crafters), the output container gives a hopper below the bone meal of a full composter, emptying it twice as vanilla's setChanged calls do (and losing it when the hopper is full); levels 7 and other faces refuse. tools/test_composter_parity.py runs right-clicks, hoppers above and below, and droppers into composters at every level through VanillaDispenserOracle (new "use" and "hopper" actions) and the game's dispense fixture. Fixes #70 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 10 ++ crates/horizon-client/src/game/commands.rs | 2 +- crates/horizon-client/src/game/composter.rs | 122 ++++++++++++++ .../src/game/dispense_fixture.rs | 63 +++++++ crates/horizon-client/src/game/machines.rs | 64 +++++++- crates/horizon-client/src/items.rs | 3 + crates/horizon-world/src/level/interact.rs | 51 ++++++ .../parity/VanillaBlockUpdateOracle.java | 5 + .../parity/VanillaDispenserOracle.java | 59 +++++++ tools/test_composter_parity.py | 155 ++++++++++++++++++ 10 files changed, 531 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-client/src/game/composter.rs create mode 100644 tools/test_composter_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..a0b563ee3 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -19,6 +19,7 @@ mod chat; mod combat; mod command_harness; mod commands; +mod composter; mod control; mod copper_golems; mod creaking; @@ -1551,6 +1552,11 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + LevelEvent::LevelEvent { + id: 1500, + pos, + data, + } => self.composter_fill_event(pos, data == 1), LevelEvent::LevelEvent { id, pos, .. } => { let c = Some([ f64::from(pos.x) + 0.5, @@ -2023,6 +2029,10 @@ impl Game<'_> { self.swing_arm(); return Ok(()); } + if self.use_composter(hit.pos, held.as_ref()) { + self.swing_arm(); + return Ok(()); + } let face = match hit.face { [0, 1, 0] => Direction::Up, [0, -1, 0] => Direction::Down, diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index bab24eff8..77bd44325 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,6 +1,6 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. -mod compute; +pub(super) mod compute; mod data; mod effects; pub(super) mod execute; diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs new file mode 100644 index 000000000..942e02eda --- /dev/null +++ b/crates/horizon-client/src/game/composter.rs @@ -0,0 +1,122 @@ +//! `ComposterBlock`: compostable items go in by hand (`useItemOn`) or +//! through its input container (hoppers, droppers, crafters above), and the +//! fill feedback of level event 1500 (`handleFill`). Emptying a full +//! composter by hand is `useWithoutItem` in horizon-world. +use super::{Game, commands::compute::ComputeContext}; +use horizon_client::{ + items::ItemStack, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{position::BlockPos, random::RandomSource}; + +impl Game<'_> { + /// The composter's `level` at `pos`, None when it isn't a composter. + pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option { + let state = self.world.block(pos[0], pos[1], pos[2]); + let s = self.res.assets.registry.state(state)?; + if &*s.name != "minecraft:composter" { + return None; + } + s.properties.get("level")?.parse().ok() + } + /// The item's `compostable` layers provider. + fn compostable(&self, stack: &ItemStack) -> Option { + self.res.items.get(&stack.item)?.compostable.clone() + } + /// `ComposterBlock.addLayer` and level event 1500: the provider is + /// evaluated in the composter's block-interaction loot context (its + /// state; the level random), then the layer is added. True when it was. + fn composter_add(&mut self, pos: [i32; 3], layers: &serde_json::Value) -> bool { + let context = ComputeContext { + block: Some(pos), + target: None, + }; + let layers = self.provider_int(layers, &context, 0).unwrap_or(0); + let before = self.world.block(pos[0], pos[1], pos[2]); + let at = BlockPos::new(pos[0], pos[1], pos[2]); + let after = self.with_level(|b, level, ticks| b.composter_insert(level, ticks, at, layers)); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + // The game event and level event 1500 happen here, before the caller goes on. + let _ = self.process_level_events(); + after != before + } + /// `ComposterBlock.useItemOn` with the main-hand stack: true when it + /// consumed the action (SUCCESS; a full composter falls through to + /// `useWithoutItem`, which empties it). + pub(super) fn use_composter(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { + let Some(level) = self.composter_level(pos) else { + return false; + }; + let Some(stack) = held else { + return false; + }; + let Some(layers) = self.compostable(stack) else { + return false; + }; + if level >= 8 { + return false; + } + if level < 7 { + self.composter_add(pos, &layers); + self.stats.add("used", &stack.item, 1); + self.consume_held(); + } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, stack); + true + } + /// `HopperBlockEntity.addItem` into the composter's `InputContainer` + /// (levels 0 to 6; one item, compostable, from above): the remainder. + pub(super) fn composter_container_insert( + &mut self, + pos: [i32; 3], + mut stack: ItemStack, + from_above: bool, + ) -> Option { + let level = self.composter_level(pos)?; + if !from_above || level >= 7 { + return Some(stack); + } + let Some(layers) = self.compostable(&stack) else { + return Some(stack); + }; + // InputContainer.getMaxStackSize is 1: one item goes in, and its + // setChanged composts it at once. + stack.count -= 1; + self.composter_add(pos, &layers); + (stack.count > 0).then_some(stack) + } + /// `ComposterBlock.handleFill` (level event 1500) on the client: the + /// fill sound and ten composter particles above the compost. + pub(super) fn composter_fill_event(&mut self, pos: BlockPos, success: bool) { + let center = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let sound = if success { + "minecraft:block.composter.fill_success" + } else { + "minecraft:block.composter.fill" + }; + self.audio.play(sound, Some(center), 1.0, 1.0); + // getShape(..).max(Y, 0.5, 0.5): the compost surface (SHAPES[8] = SHAPES[7]). + let level = self.composter_level([pos.x, pos.y, pos.z]).unwrap_or(0); + let height = f64::from((1 + level.min(7) * 2).clamp(2, 16)) / 16.0 + 0.03125; + let options = ParticleOptions::simple(ParticleType::Composter); + for _ in 0..10 { + let r = self.particles.random(); + let v = [ + r.next_gaussian() * 0.02, + r.next_gaussian() * 0.02, + r.next_gaussian() * 0.02, + ]; + let p = [ + f64::from(pos.x) + 0.1875 + 0.625 * f64::from(r.next_float()), + f64::from(pos.y) + height + f64::from(r.next_float()) * (1.0 - height), + f64::from(pos.z) + 0.1875 + 0.625 * f64::from(r.next_float()), + ]; + self.particles.add(&options, p, v); + } + } +} diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 5d2a9c91f..c92f88505 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -131,6 +131,8 @@ impl Game<'_> { self.level_events.clear(); self.orbs.clear(); self.falling.clear(); + // Hopper cooldowns of an earlier case. + self.hoppers.clear(); self.ui.rules = Default::default(); // The oracle level plays on normal difficulty. self.ui.difficulty = 2; @@ -260,8 +262,15 @@ impl Game<'_> { pos[2].as_i64().unwrap_or(0) as i32, ); let state = self.world.block(origin.x, origin.y, origin.z); + let mut used = Vec::new(); if let Some(op) = case.get("remove") { self.fixture_remove(origin, op)?; + } else if let Some(op) = case.get("use") { + used = self.fixture_use(origin, op)?; + } else if case.get("hopper").is_some() { + // HopperBlockEntity.pushItemsTick, once. + self.hopper_try_move_items((origin.x, origin.y, origin.z)); + self.process_level_events()?; } else { self.dispense_from(origin, state)?; // CrafterBlockEntity.serverTick, the crafting animation running down. @@ -335,10 +344,64 @@ impl Game<'_> { for (sound, at, _, _) in self.audio.capture.take().unwrap_or_default() { out.push(format!("S {} {sound}", floor_pos(at))); } + out.extend(used); out.push(format!("rng {}", self.world.random.next_long())); Ok(out) } + /// A player holding the case's item right-clicks the block at `pos` + /// (`use_item_as_player`'s block steps): the statistics, the result + /// and the held stack, as `VanillaDispenserOracle.use` prints them. + fn fixture_use(&mut self, pos: BlockPos, op: &Value) -> Result> { + let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?; + self.creative = op["creative"].as_bool().unwrap_or(false); + self.inventory[self.selected] = stack.clone(); + let used_before = stack + .as_ref() + .map_or(0, |s| self.stats.get("used", &s.item)); + let at = [pos.x, pos.y, pos.z]; + let mut consumed = self.use_composter(at, stack.as_ref()); + if !consumed { + let player = horizon_world::level::PlayerContext { + yaw: 0.0, + pitch: 90.0, + may_build: true, + can_eat: self.creative, + game_master: false, + }; + let hit = horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 0.5, + ); + let result = self.with_level(|b, level, ticks| { + b.use_without_item( + level, + ticks, + pos, + horizon_core::geometry::Direction::Up, + hit, + player, + ) + }); + consumed = result.consumes_action(); + } + self.process_level_events()?; + let mut out = Vec::new(); + if let Some(s) = &stack { + let used = self.stats.get("used", &s.item) - used_before; + if used != 0 { + out.push(format!("stat {} minecraft:used {used}", s.item)); + } + } + out.push(format!( + "use {} held {}", + if consumed { "consumed" } else { "pass" }, + canon_stack(self.inventory[self.selected].as_ref()) + )); + Ok(out) + } + /// A stack in a block entity's slot: a container's, a jukebox's record, a /// lectern's book, or the items of a block entity Horizon keeps as saved. fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 386b6a7bb..31affaa3f 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -41,6 +41,9 @@ enum Kind { Crafter, /// `BrewingStandBlockEntity` (a `WorldlyContainer`). Brewing, + /// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder` + /// without a block entity): input below 7, empty at 7, bone meal at 8. + Composter(i32), } /// A container: one block entity, or a double chest (`CompoundContainer`). @@ -71,6 +74,9 @@ impl View { (Kind::Brewing, Some(Direction::Up)) => vec![3], (Kind::Brewing, Some(Direction::Down)) => vec![0, 1, 2, 3], (Kind::Brewing, Some(_)) => vec![0, 1, 2, 4], + (Kind::Composter(8), Some(Direction::Down)) => vec![0], + (Kind::Composter(level), Some(Direction::Up)) if level < 7 => vec![0], + (Kind::Composter(_), _) => vec![], _ => (0..self.len()).collect(), } } @@ -119,6 +125,8 @@ struct Containers<'a> { registry: &'static horizon_world::registry::BlockRegistry, /// Brewing recipes, for what a brewing stand accepts (not needed for signals). brewing: Option<&'a horizon_client::brewing::Brewing>, + /// The stack of a full composter's `OutputContainer`. + bone_meal: ItemStack, } impl Containers<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option<&str> { @@ -141,9 +149,16 @@ impl Containers<'_> { /// first). `blocked_chests`: `ChestBlock.getContainer(.., false)` returns /// nothing for a chest under a redstone conductor. fn view(&self, pos: Pos, blocked_chests: bool) -> Option { - let entity = self.world.block_entities.get(&pos)?; let state = self.world.block(pos.0, pos.1, pos.2); let name = self.name(state); + if name == "minecraft:composter" { + let level = self.prop(state, "level").and_then(|l| l.parse().ok())?; + return Some(View { + parts: vec![(pos, usize::from(level != 7))], + kind: Kind::Composter(level), + }); + } + let entity = self.world.block_entities.get(&pos)?; let kind = match (entity, name) { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, @@ -202,6 +217,10 @@ impl Containers<'_> { }) } fn get(&self, view: &View, slot: usize) -> Option<&ItemStack> { + if let Kind::Composter(level) = view.kind { + // OutputContainer holds one bone meal; InputContainer composts at once. + return (level == 8 && slot == 0).then_some(&self.bone_meal); + } let (pos, i) = view.locate(slot)?; self.world .block_entities @@ -264,6 +283,10 @@ impl Containers<'_> { } /// `canTakeItemThroughFace` (furnaces and brewing stands restrict it). fn can_take(&self, view: &View, slot: usize, stack: &ItemStack, face: Direction) -> bool { + if let Kind::Composter(level) = view.kind { + // OutputContainer.canTakeItemThroughFace. + return level == 8 && face == Direction::Down && &*stack.item == "minecraft:bone_meal"; + } if view.kind == Kind::Brewing { return slot != 3 || &*stack.item == "minecraft:glass_bottle"; } @@ -300,6 +323,15 @@ impl Containers<'_> { } } +fn bone_meal() -> ItemStack { + ItemStack { + item: "minecraft:bone_meal".into(), + count: 1, + damage: 0, + extra: None, + } +} + /// Comparator input from a container block entity (0 when there is none). pub(super) fn container_signal( world: &World, @@ -314,8 +346,10 @@ pub(super) fn container_signal( items, registry, brewing: None, + bone_meal: bone_meal(), }; c.view((pos.x, pos.y, pos.z), true) + .filter(|v| !matches!(v.kind, Kind::Composter(_))) .map_or(0, |v| c.signal(&v)) } @@ -327,6 +361,7 @@ impl Game<'_> { items: &self.res.items, registry: self.res.assets.registry, brewing: Some(&self.res.stations.brewing), + bone_meal: bone_meal(), } } fn slot_mut_at(&mut self, view: &View, slot: usize) -> Option<&mut Option> { @@ -339,6 +374,10 @@ impl Game<'_> { } /// `BlockEntity.setChanged` for every block entity of a container. fn view_changed(&mut self, view: &View) { + // A composter's containers change its block state instead. + if let Kind::Composter(_) = view.kind { + return; + } for &(pos, _) in &view.parts { self.container_changed(pos); } @@ -415,6 +454,10 @@ impl Game<'_> { stack: ItemStack, face: Option, ) -> Option { + if let Kind::Composter(_) = view.kind { + let (x, y, z) = view.parts[0].0; + return self.composter_container_insert([x, y, z], stack, face == Some(Direction::Up)); + } let slots = if matches!(view.kind, Kind::Furnace | Kind::Brewing) && face.is_some() { view.slots_for_face(face) } else { @@ -482,7 +525,7 @@ impl Game<'_> { Ok(()) } /// `HopperBlockEntity.tryMoveItems` with `suckInItems`. - fn hopper_try_move_items(&mut self, pos: Pos) { + pub(super) fn hopper_try_move_items(&mut self, pos: Pos) { let state = self.world.block(pos.0, pos.1, pos.2); let c = self.containers(); let enabled = c.prop(state, "enabled") != Some("false"); @@ -540,6 +583,23 @@ impl Game<'_> { let above = (pos.0, pos.1 + 1, pos.2); let c = self.containers(); if let Some(source) = c.view(above, false) { + if let Kind::Composter(level) = source.kind { + if level != 8 { + return false; + } + // tryTakeInItemFromSlot on the OutputContainer: removeItem calls + // its setChanged, which empties the composter, and so does the + // second setChanged after the move or, when the hopper has no + // room, the setItem putting the bone meal back into the detached + // container (whose bone meal is lost with it). + let bone_meal = c.bone_meal.clone(); + let at = BlockPos::new(above.0, above.1, above.2); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + let moved = self.add_item(None, hopper, bone_meal, None).is_none(); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + self.world.modified.insert((above.0 >> 4, above.2 >> 4)); + return moved; + } let source_hopper = (source.kind == Kind::Hopper).then_some(above); for slot in source.slots_for_face(Some(Direction::Down)) { let c = self.containers(); diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index abba286f1..8c9bc2e02 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -35,6 +35,8 @@ pub struct ItemInfo { pub fuel: Option<(Value, Value)>, /// `brewing_fuel`: uses and speed-multiplier provider references. pub brewing_fuel: Option<(Value, Value)>, + /// `compostable.layers`: the layers provider (`ComposterBlock.addLayer`). + pub compostable: Option, /// Item left behind after crafting/fuel use (e.g. bucket). pub remainder: Option, /// `equippable.slot` (head, chest, legs, feet, ...). @@ -442,6 +444,7 @@ impl Items { brewing_fuel: c .get("minecraft:brewing_fuel") .map(|f| (f["uses"].clone(), f["speed_multiplier"].clone())), + compostable: c.get("minecraft:compostable").map(|f| f["layers"].clone()), remainder: c["minecraft:use_remainder"]["id"] .as_str() .or(c["minecraft:crafting_remainder"]["id"].as_str()) diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 227615366..0d761c7c6 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -435,6 +435,25 @@ impl Sim<'_, L> { InteractionResult::Success } + /// `ComposterBlock.addLayer` once its `compostable` provider gave + /// `layers`: the new state (the old one when no layer is added). + fn composter_add_layer(&mut self, pos: BlockPos, layers: i32) -> BlockStateId { + let b = self.b; + let state = self.state(pos); + if layers <= 0 { + return state; + } + let level = b.table.int(state, b.props.level); + let next_level = (level + layers).clamp(0, 7); + let next = b.table.set_int(state, b.props.level, next_level); + self.set_block_and_update(pos, next); + self.game_event_state(pos, "minecraft:block_change", next); + if next_level == 7 { + self.schedule_tick(pos, b.block(state), 20); + } + next + } + /// `DragonEggBlock.teleport`. fn dragon_egg_teleport(&mut self, pos: BlockPos, state: BlockStateId) { let b = self.b; @@ -462,6 +481,38 @@ impl Sim<'_, L> { } impl Behaviours { + /// `ComposterBlock.addLayer` at `pos` with the layers its item's + /// `compostable` provider gave, followed by level event 1500 (fill + /// particles and sound; data 1 when a layer was added) as every caller + /// does: `useItemOn` and the hopper input container. The new state. + pub fn composter_insert( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + layers: i32, + ) -> BlockStateId { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let next = sim.composter_add_layer(pos, layers); + sim.level_event(1500, pos, i32::from(next != state)); + next + } + + /// `ComposterBlock.empty`: the hopper output container took the bone meal. + pub fn composter_empty( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + ) { + let mut sim = self.sim(level, ticks); + let state = sim.state(pos); + let next = self.table.set_int(state, self.props.level, 0); + sim.set_block_and_update(pos, next); + sim.game_event_state(pos, "minecraft:block_change", next); + } + /// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and /// absolute hit location as in `BlockHitResult`). pub fn use_without_item( diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java index 5fcf0250d..8d9cde712 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaBlockUpdateOracle.java @@ -432,6 +432,11 @@ public final class VanillaBlockUpdateOracle { world.emit("D " + id.identifier()); return delegate != null ? delegate.getLootTable(id) : net.minecraft.world.level.storage.loot.LootTable.EMPTY; } + /** The registries loot contexts resolve providers in (a composter's compostable layers). */ + @Override + public net.minecraft.core.HolderLookup.Provider lookup() { + return delegate != null ? delegate.lookup() : ParityData.lookup; + } } static final class Server extends net.minecraft.server.MinecraftServer { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index bc859b283..89dda66f6 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -51,6 +51,7 @@ public final class VanillaDispenserOracle { case 1051 -> "minecraft:entity.wind_charge.throw"; case 1505 -> "minecraft:item.bone_meal.use"; case 1501 -> "minecraft:block.lava.extinguish"; + case 1500 -> data == 1 ? "minecraft:block.composter.fill_success" : "minecraft:block.composter.fill"; case 1009 -> data == 0 ? "minecraft:block.fire.extinguish" : data == 1 ? "minecraft:block.generic.extinguish_fire" : null; case 2001 -> { BlockState state = Block.stateById(data); @@ -289,8 +290,15 @@ public final class VanillaDispenserOracle { List targets = List.copyOf(w.entities); BlockPos origin = VanillaBlockUpdateOracle.readPos(f.getAsJsonArray("pos")); BlockState state = w.getBlockState(origin); + List used = new ArrayList<>(); if (f.has("remove")) { remove(w, origin, f.getAsJsonObject("remove")); + } else if (f.has("use")) { + used = use(w, origin, f.getAsJsonObject("use")); + } else if (f.has("hopper")) { + // HopperBlockEntity.pushItemsTick, once. + var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); + net.minecraft.world.level.block.entity.HopperBlockEntity.pushItemsTick(w, origin, state, hopper); } else if (state.getBlock() instanceof CrafterBlock) { Method craft = CrafterBlock.class.getDeclaredMethod("dispenseFrom", BlockState.class, ServerLevel.class, BlockPos.class); craft.setAccessible(true); @@ -348,9 +356,60 @@ public final class VanillaDispenserOracle { } } result.addAll(w.blockEvents); + result.addAll(used); result.add("rng " + w.rng.nextLong()); } + /** The player of a "use" case: its main hand, game mode and the statistics it is awarded. */ + static final class User extends net.minecraft.server.level.ServerPlayer { + VanillaBlockUpdateOracle.World world; + boolean creative; + ItemStack hand; + List stats; + User() { + super(null, null, null, null); + } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public boolean isSpectator() { return false; } + @Override public EntityType getType() { return EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY; + } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { + stats.add("stat " + key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); + } + static String key(net.minecraft.stats.Stat stat) { + return String.valueOf(stat.getType().getRegistry().getKey(stat.getValue())); + } + } + + /** + * ServerPlayerGameMode.useItemOn by a player holding the case's item on the + * block at `pos` (not sneaking): `useItemOn`, then `useWithoutItem` when the + * block asks to try with an empty hand. The held stack and statistics follow. + */ + static List use(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception { + User player = (User) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, User.class); + player.world = w; + player.creative = use.has("creative") && use.get("creative").getAsBoolean(); + player.hand = stack(use.get("item").getAsString()); + player.stats = new ArrayList<>(); + var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0), + net.minecraft.core.Direction.UP, pos, false); + BlockState state = w.getBlockState(pos); + var hand = net.minecraft.world.InteractionHand.MAIN_HAND; + var result = state.useItemOn(player.getItemInHand(hand), w, player, hand, hit); + if (result instanceof net.minecraft.world.InteractionResult.TryEmptyHandInteraction) { + result = state.useWithoutItem(w, player, hit); + } + List out = new ArrayList<>(player.stats); + out.add("use " + (result.consumesAction() ? "consumed" : "pass") + " held " + ParityData.canon(player.hand)); + return out; + } + /** The level's block entity positions by x, y, z. */ static List sortedEntities(VanillaBlockUpdateOracle.World w) { List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); diff --git a/tools/test_composter_parity.py b/tools/test_composter_parity.py new file mode 100644 index 000000000..e632527ce --- /dev/null +++ b/tools/test_composter_parity.py @@ -0,0 +1,155 @@ +#!/usr/bin/env python3 +"""Compare vanilla composters with Horizon's: by hand, through hoppers and from droppers. + +Every case has a composter at a random level and runs one action over the +headless level of the dispenser harness (`VanillaDispenserOracle` against +`HORIZON_DISPENSE_FIXTURE`): + +- `use`: a player (survival or creative) right-clicks the composter holding a + compostable item, another item or nothing (`ComposterBlock.useItemOn`, then + `useWithoutItem`, which empties a full composter); +- `hopper` above: a hopper facing down (or past it) pushes its items into the + composter's input container; +- `hopper` below: a hopper under the composter pulls the bone meal out of its + output container (nothing from the other levels); +- `dispense`: a dropper facing the composter puts one item in from above, or + is refused from the side. + +Both sides print block changes, container contents, spawned items, level +events with the sounds the client plays for them, sounds, game events, the +player's statistics and held stack, and the level random afterwards (the +compostable providers draw from it). +""" +import json +import os +import random +try: + from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base +except ImportError: + import block_update_harness as h + import lab + import test_dispenser_parity as d + import test_rust_parity as base + +OTHERS = ['stick', 'stone', 'bone_meal', 'diamond_sword', 'water_bucket', 'cobblestone', 'egg'] +SIDES = ['north', 'south', 'west', 'east'] + + +def stack(rng, items, compostable, others_odds=0.25): + if rng.random() < others_odds: + name = rng.choice(OTHERS) + else: + name = rng.choice(compostable) + top = items['minecraft:' + name].get('minecraft:max_stack_size', 64) + return d.plain(name, min(top, rng.choice([1, 1, 2, 16, 64]))) + + +def composter(states, rng): + level = rng.choice([0, 0, 1, 3, 5, 6, 6, 7, 8, 8]) + return states.get('composter', level=str(level)) + + +def cases(facts, items, count, seed): + rng = random.Random(seed) + states = d.States(facts) + compostable = sorted(k.split(':')[1] for k, v in items.items() if 'minecraft:compostable' in v) + modes = ['use', 'use', 'hopper_in', 'hopper_out', 'dispense'] + for n in range(count): + mode = modes[n % len(modes)] + case = {**h.environment(rng), 'pos': [0, 0, 0]} + case.pop('raining', None) + case.pop('thundering', None) + cells = [] + items_in = [] + if mode == 'use': + cells.append([0, 0, 0, composter(states, rng)]) + held = '-' if rng.random() < 0.1 else stack(rng, items, compostable) + case['use'] = {'item': held, 'creative': rng.random() < 0.2} + elif mode == 'hopper_in': + facing = 'down' if rng.random() < 0.8 else rng.choice(SIDES) + cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')]) + target = {'down': (0, -1, 0), 'north': (0, 0, -1), 'south': (0, 0, 1), 'west': (-1, 0, 0), 'east': (1, 0, 0)}[facing] + cells.append([*target, composter(states, rng)]) + for slot in rng.sample(range(5), rng.choice([1, 1, 2, 3, 5])): + items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.4)]) + case['hopper'] = True + elif mode == 'hopper_out': + facing = rng.choice(['down', 'down'] + SIDES) + cells.append([0, 0, 0, states.get('hopper', facing=facing, enabled='true')]) + level = 8 if rng.random() < 0.7 else rng.choice([0, 3, 7]) + cells.append([0, 1, 0, states.get('composter', level=str(level))]) + roll = rng.random() + if roll < 0.3: + # Full of something else: the bone meal can't go in. + for slot in range(5): + items_in.append([0, 0, 0, slot, d.plain('stone', 64)]) + elif roll < 0.5: + items_in.append([0, 0, 0, rng.randrange(5), d.plain('bone_meal', rng.choice([1, 63, 64]))]) + case['hopper'] = True + else: + facing = 'down' if rng.random() < 0.75 else rng.choice(SIDES + ['up']) + cells.append([0, 0, 0, states.get('dropper', facing=facing, triggered='false')]) + dx, dy, dz = d.STEP[facing] + cells.append([dx, dy, dz, composter(states, rng)]) + slots = rng.sample(range(9), rng.choice([1, 1, 2, 9])) + for slot in slots: + items_in.append([0, 0, 0, slot, stack(rng, items, compostable, 0.3)]) + case['cells'] = cells + case['items'] = items_in + case['mode'] = 'dispense' + case['action'] = mode + yield case + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 3000 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + items = json.loads((resources / 'items.json').read_text()) + work = lab.LOCAL / 'composter-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, items, args.count, args.seed)) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + java_root = lab.ROOT / 'mods/horizon/src/test/java' + d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn', + '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) + d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) + d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) + native = h.split_cases((work / 'native.txt').read_text(), ignore) + rust = h.split_cases((work / 'rust.txt').read_text(), ignore) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + for case, a, b in zip(all_cases, native, rust): + if a and a[0].startswith('error'): + errors.setdefault(a[0], []).append(case) + continue + if not d.same(a, b): + groups.setdefault(case['action'], []).append((case, a, b)) + for kind, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {kind}') + for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): + print(f'{name}: {len(entries)} differing') + for case, a, b in entries[:args.show]: + print(' case ' + d.describe(case, facts) + (' use=' + json.dumps(case['use']) if 'use' in case else '')) + print(' native ' + ' | '.join(sorted(a))) + print(' rust ' + ' | '.join(sorted(b))) + total = sum(len(v) for v in groups.values()) + skipped = sum(len(v) for v in errors.values()) + print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors)') + h.finish(total + skipped) + + +if __name__ == '__main__': + main() From f1cc118df0570604b1db2828da20cd67c39411a6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:10:25 +0200 Subject: [PATCH 05/13] Feeding sounds: each animal's own eating sound, or none, as in vanilla Animal.mobInteract plays playEatingSound(), which is empty in Animal and overridden only by armadillos, cats, foxes, frogs, goats, pigs, sniffers and sulfur cubes (plus nautili). Horizon fell back to entity.generic.eat for every other animal (cows, sheep, chickens, rabbits, turtles, bees...), with a level random pitch instead of each class's volume and pitch. - mobs::ai::eating_sound: the overrides with their exact volume and pitch (makeSound with the voice pitch, playSound(1, 1), or Level.playSound with Mth.randomBetween(0.8, 1.2)); silent otherwise. - mobs::ai::feed_animal: Animal.mobInteract's food part, shared by the game and the mob AI probe; Strider.mobInteract adds entity.strider.eat. - AgeableMob.ageUp(seconds, true): forcedAge and the forced-age particle timer, whose positions draw from the mob's random on the server. - Tame wolves and cats healed with food: TamableAnimal.feed (wolves silent). - Parrots: Parrot.isFood is false; wild ones take parrot food with entity.parrot.eat and a one-in-ten taming chance. - Baby pigs and chickens use their sound variant's baby_sounds. The mob AI harness gains a `feed TICK MOB ITEM` event (the oracle calls the real Animal.mobInteract) and feeding scenarios for adult and baby cows, pigs, sheep and chickens. Fixes #68 Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/mob_ai_probe.rs | 17 +++ crates/horizon-client/src/entity_nbt.rs | 2 + crates/horizon-client/src/game/creatures.rs | 76 +++++++----- crates/horizon-client/src/game/nautili.rs | 4 +- crates/horizon-client/src/mobs.rs | 5 + crates/horizon-client/src/mobs/ai.rs | 110 +++++++++++++++++- .../horizonlab/parity/VanillaMobAiOracle.java | 15 +++ tools/test_mob_ai_parity.py | 10 ++ 8 files changed, 205 insertions(+), 34 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 40527b810..f90fbfc3e 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -56,6 +56,9 @@ struct Scenario { spawning: bool, /// The player hits a mob for 1 at the start of a tick: (tick, mob index). hurts: Vec<(i32, usize)>, + /// The player feeds an animal at the start of a tick (Animal.mobInteract): + /// (tick, mob index); the scenario only feeds each animal its food. + feeds: Vec<(i32, usize)>, hand: Option, mobs: Vec, } @@ -92,6 +95,7 @@ fn parse(text: &str) -> Vec { } "heart" => s.hearts.push(f.iter().map(|x| (*x).to_owned()).collect()), "hurt" => s.hurts.push((f[1].parse().unwrap(), f[2].parse().unwrap())), + "feed" => s.feeds.push((f[1].parse().unwrap(), f[2].parse().unwrap())), "player" => { s.player = Some([ f[1].parse().unwrap(), @@ -893,6 +897,9 @@ fn main() -> horizon_client::Result<()> { } }); let mut scratch = LegacyRandom::new(0); + // The level's random for eating sounds: only goats and sniffers draw + // from it, and the scenarios feed neither. + let mut level_random = LegacyRandom::new(0); for (i, m) in mobs.iter().enumerate() { print(&mut out, 0, i, m, s.creative); } @@ -996,6 +1003,16 @@ fn main() -> horizon_client::Result<()> { } events.append(&mut mobs[i].outbox); } + for &(tick, i) in &s.feeds { + if tick != t || i >= mobs.len() || mobs[i].removed { + continue; + } + if let Some(Some((name, volume, pitch))) = + horizon_client::mobs::ai::feed_animal(&mut mobs[i], &mut level_random) + { + events.push(MobEvent::Sound(name, [0.0; 3], volume, pitch)); + } + } #[allow(unused_mut)] // filled only with the rng-trace feature let mut traces: Vec = Vec::new(); let mut pushes = Vec::new(); diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 64cbe15ba..51948cc72 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -156,6 +156,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { if m.kind.category == "creature" && aged { map.insert("Age".into(), Tag::Int(m.extra.age)); map.insert("AgeLocked".into(), Tag::Byte(i8::from(m.extra.age_locked))); + map.insert("ForcedAge".into(), Tag::Int(m.extra.forced_age)); for (key, value) in [ ("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), @@ -589,6 +590,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.custom_name = custom_name(tag); if m.kind.category == "creature" { m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32; + m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } m.name_visible = flag(tag, "CustomNameVisible"); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 27b48a15f..82338433d 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -11,6 +11,7 @@ use horizon_client::{ mesher::Vertex, mobs::{ Damage, DamageKind, Mob, MobEvent, MobWorld, PlayerView, Seen, SpawnSetup, Species, Who, + ai::{eating_sound, feed_animal}, farm::Climate, spawning::{self, BiomeFacts}, }, @@ -1844,6 +1845,9 @@ impl Game<'_> { let mut consume = false; let mut give: Option<&str> = None; let mut sound: Option<&str> = None; + // Sounds played as vanilla plays them: (event, volume, pitch) at the feet. + let mut eat: Option<(&'static str, f32, f32)> = None; + let feet = [m.position.x, m.position.y, m.position.z]; let mut handled = true; let mut drops: Vec<(String, u32)> = Vec::new(); let is_food = m.kind.food.contains(&item); @@ -1919,9 +1923,9 @@ impl Game<'_> { .get(&item) .and_then(|i| i.food.as_ref()) .map_or(2.0, |f| f.0 as f32); + // TamableAnimal.feed: playEatingSound, which wolves leave empty. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; - sound = Some("entity.wolf.eat"); } Species::Wolf if m.extra.tame @@ -2023,9 +2027,10 @@ impl Game<'_> { .get(&item) .and_then(|i| i.food.as_ref()) .map_or(1.0, |f| f.0 as f32); + // TamableAnimal.feed. m.health = (m.health + heal).min(m.attrs.max_health); consume = true; - sound = Some("entity.cat.eat"); + eat = eating_sound(m, &mut self.world.random); } Species::Cat if m.extra.tame && !(is_food && m.extra.age == 0 && m.extra.in_love <= 0) => @@ -2038,7 +2043,6 @@ impl Game<'_> { } Species::Cat if !m.extra.tame && is_food => { consume = true; - sound = Some("entity.cat.eat"); m.persistent = true; let at = [ m.position.x, @@ -2051,6 +2055,7 @@ impl Game<'_> { m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); m.extra.sitting = true; } + 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 }])?; if tamed { @@ -2076,25 +2081,45 @@ impl Game<'_> { sound = Some("item.flintandsteel.use"); self.damage_held_tool(); } + // Parrot.mobInteract: parrot food may tame a wild one (one time in + // ten); a parrot never takes it as Animal food (isFood is false). + Species::Parrot if !m.extra.tame && is_food => { + consume = true; + if !m.silent { + 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 }])?; + if tamed { + let view = self.mob_entity(&self.mobs[index]); + self.trigger_entity("minecraft:tame_animal", "entity", &view); + } + } // HappyGhast.canFallInLove: never, so only a ghastling takes food. _ if is_food && m.kind.flags.animal + && species != Species::Parrot && (species != Species::HappyGhast || m.is_baby()) => { - // Animal.mobInteract: breed adults, speed up babies. - if m.extra.age == 0 && m.extra.in_love <= 0 { - m.extra.in_love = 600; - m.extra.love_player = true; - consume = true; - sound = Some(eat_sound(species)); - } else if m.extra.age < 0 { - // AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age)) = 10%. - let secs = (-m.extra.age / 20) as f32 * 0.1; - m.extra.age = (m.extra.age + (secs as i32) * 20).min(0); - consume = true; - sound = Some(eat_sound(species)); - } else { - handled = false; + // Animal.mobInteract: breed adults, speed up babies, then + // playEatingSound (silent unless the species overrides it). + match feed_animal(m, &mut self.world.random) { + Some(sound) => { + consume = true; + eat = sound; + } + None => handled = false, } } _ => handled = false, @@ -2109,6 +2134,10 @@ impl Game<'_> { self.audio .play(&format!("minecraft:{s}"), Some(center), 1.0, pitch); } + if let Some((s, volume, pitch)) = eat { + self.audio + .play(&format!("minecraft:{s}"), Some(feet), volume, pitch); + } if consume && !creative && let Some(stack) = self.inventory[selected].as_mut() @@ -2485,19 +2514,6 @@ impl Game<'_> { } } } -fn eat_sound(s: Species) -> &'static str { - match s { - Species::Pig => "entity.pig.eat", - Species::Horse | Species::Donkey | Species::Mule => "entity.horse.eat", - Species::Llama | Species::TraderLlama => "entity.llama.eat", - Species::Goat => "entity.goat.eat", - Species::Sniffer => "entity.sniffer.eat", - Species::Fox => "entity.fox.eat", - Species::Cat => "entity.cat.eat", - Species::Panda => "entity.panda.eat", - _ => "entity.generic.eat", - } -} /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index 2a7687dc3..592416630 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -59,8 +59,8 @@ impl Game<'_> { } let m = &mut self.mobs[index]; if !m.extra.age_locked { - let secs = (-m.extra.age / 20) as f32 * 0.1; - m.extra.age = (m.extra.age + (secs as i32) * 20).min(0); + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + horizon_client::mobs::ai::age_up(m, secs, true); } let sound = nautilus::eat_sound(m); self.use_nautilus_food(item); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index f8ebca55c..195bf536f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -619,6 +619,11 @@ pub struct Extra { pub age: i32, /// `AgeLocked` (tadpoles fed a slime ball... and ageable mobs). pub age_locked: bool, + /// AgeableMob.forcedAge: the age fed food added, restored as the age + /// when it reaches 0 (`ForcedAge`). + pub forced_age: i32, + /// AgeableMob.forcedAgeTimer: ticks of happy villager particles left. + pub forced_age_timer: i32, pub in_love: i32, pub love_player: bool, /// Texture/model variant index (cat type, horse colour, rabbit type...). diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index a0338c6b1..f3045a8b1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -555,7 +555,7 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec) { Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry", Species::Piglin if m.ai.target.is_some() => "entity.piglin.angry", Species::Hoglin if m.ai.target.is_some() => "entity.hoglin.angry", - _ => m.kind.sounds[0], + _ => voice_sounds(m)[0], }; let _ = w; if !sound.is_empty() { @@ -617,7 +617,23 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: & if m.kind.flags.climber { m.climbing = m.horizontal_collision; } - // AgeableMob.aiStep + // AgeableMob.aiStep: a forced age-up's particles (positions drawn on the + // server too), then the age. + if m.extra.forced_age_timer > 0 { + if m.extra.forced_age_timer % 4 == 0 { + let (w, h) = (f64::from(m.width()), f64::from(m.height())); + let r = &mut m.random; + 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 { + kind: "happy_villager", + at: [x, y, z], + count: 1, + }); + } + m.extra.forced_age_timer -= 1; + } if m.alive() { if m.extra.age < 0 { let (bw, bh, _) = m.dims(); @@ -977,9 +993,99 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] { match m.species() { Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m), Species::SulfurCube => super::sulfur_cube::sounds(m), + // The sound variant's baby_sounds (classic sets, like the rest here). + Species::Pig if m.is_baby() => [ + "entity.baby_pig.ambient", + "entity.baby_pig.hurt", + "entity.baby_pig.death", + ], + Species::Chicken if m.is_baby() => [ + "entity.baby_chicken.ambient", + "entity.baby_chicken.hurt", + "entity.baby_chicken.death", + ], _ => m.kind.sounds, } } +/// `Animal.mobInteract` with its food in hand: an adult that can fall in +/// love does, a baby grows up by a tenth, and either plays its eating sound +/// (`Strider.mobInteract` plays its own afterwards). `None` when the animal +/// does not take the food; otherwise the sound to play, if any. +pub fn feed_animal( + m: &mut Mob, + level: &mut impl RandomSource, +) -> Option> { + if m.extra.age == 0 && m.extra.in_love <= 0 { + m.extra.in_love = 600; + m.extra.love_player = true; + } else if m.extra.age < 0 { + // AgeableMob.ageUp(getSpeedUpSecondsWhenFeeding(-age), true): a tenth. + let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32; + age_up(m, secs, true); + } else { + return None; + } + let mut sound = eating_sound(m, level); + if m.species() == Species::Strider && !m.silent { + let pitch = 1.0 + (m.random.next_float() - m.random.next_float()) * 0.2; + sound = Some(("entity.strider.eat", 1.0, pitch)); + } + Some(sound) +} +/// `AgeableMob.ageUp(seconds, forced)`. +pub fn age_up(m: &mut Mob, seconds: i32, forced: bool) { + let age = m.extra.age; + let grown = (age + seconds * 20).min(0); + m.extra.age = grown; + if forced { + m.extra.forced_age += grown - age; + if m.extra.forced_age_timer == 0 { + m.extra.forced_age_timer = 40; + } + } + if m.extra.age == 0 { + m.extra.age = m.extra.forced_age; + } +} +/// `Animal.playEatingSound` (empty) and its overrides, as (sound, volume, +/// pitch); `level` is the level's random. Pigs and cats use the classic sound +/// set, like their other sounds here. +pub fn eating_sound( + m: &mut Mob, + level: &mut impl RandomSource, +) -> Option<(&'static str, f32, f32)> { + let baby = m.is_baby(); + // Mth.randomBetween(level.getRandom(), 0.8, 1.2). + let mut between = || level.next_float() * 0.4 + 0.8; + let (sound, volume, pitch, entity_sound) = match m.species() { + // makeSound: getSoundVolume, getVoicePitch. + Species::Armadillo | Species::Pig | Species::SulfurCube => { + let sound = match m.species() { + Species::Armadillo => "entity.armadillo.eat", + Species::Pig if baby => "entity.baby_pig.eat", + Species::Pig => "entity.pig.eat", + _ => "entity.small_sulfur_cube.eat", + }; + let pitch = m.voice_pitch(); + (sound, sound_volume(m), pitch, true) + } + // playSound(sound, 1, 1). + Species::Cat if baby => ("entity.baby_cat.eat", 1.0, 1.0, true), + Species::Cat => ("entity.cat.eat", 1.0, 1.0, true), + Species::Fox => ("entity.fox.eat", 1.0, 1.0, true), + // level().playSound(null, this, sound, NEUTRAL, volume, pitch). + Species::Frog => ("entity.frog.eat", 2.0, 1.0, false), + Species::Goat if m.extra.screaming => ("entity.goat.screaming.eat", 1.0, between(), false), + Species::Goat => ("entity.goat.eat", 1.0, between(), false), + Species::Sniffer => ("entity.sniffer.eat", 1.0, between(), false), + _ => return None, + }; + // Entity.playSound is skipped for a silent entity. + if entity_sound && m.silent { + return None; + } + Some((sound, volume, pitch)) +} pub fn sound_volume(m: &Mob) -> f32 { match m.species() { Species::Ghast => 5.0, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java index 1b57e7690..6b034411b 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java @@ -184,6 +184,9 @@ public final class VanillaMobAiOracle { boolean spawning; /** The player hits a mob for 1 at the start of a tick: {tick, mob index}. */ List hurts = new ArrayList<>(); + /** The player feeds an animal at the start of a tick (Animal.mobInteract with the item in + * its main hand): {tick, mob index, item id}. */ + List feeds = new ArrayList<>(); } static void parse(Path path) throws Exception { @@ -220,6 +223,7 @@ public final class VanillaMobAiOracle { } case "heart" -> s.hearts.add(f); case "hurt" -> s.hurts.add(new int[] {Integer.parseInt(f[1]), Integer.parseInt(f[2])}); + case "feed" -> s.feeds.add(new Object[] {Integer.parseInt(f[1]), Integer.parseInt(f[2]), f[3]}); case "player" -> { s.player = new double[] {Double.parseDouble(f[1]), Double.parseDouble(f[2]), Double.parseDouble(f[3])}; for (int i = 4; i < f.length; i++) { @@ -713,6 +717,17 @@ public final class VanillaMobAiOracle { if (hurt[0] == t && hurt[1] < ENTS.size() && ENTS.get(hurt[1]) instanceof LivingEntity hurtMob && !hurtMob.isRemoved()) hurtMob.hurtServer(level, level.damageSources().playerAttack(player), 1.0F); } + for (Object[] feed : s.feeds) { + int index = (Integer) feed[1]; + if ((Integer) feed[0] != t || index >= ENTS.size() + || !(ENTS.get(index) instanceof net.minecraft.world.entity.animal.Animal animal) || animal.isRemoved()) continue; + var hand = net.minecraft.world.InteractionHand.MAIN_HAND; + var held = player.getItemInHand(hand); + player.setItemInHand(hand, new net.minecraft.world.item.ItemStack( + BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse((String) feed[2])), 64)); + animal.mobInteract(player, hand); + player.setItemInHand(hand, held); + } for (Entity e : List.copyOf(ENTS)) { if (e.isRemoved()) continue; e.checkDespawn(); diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 524d69d3f..d2f69c07e 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -208,6 +208,16 @@ def scenarios(): add('golem_part_full', 500, [chest(-3, 1, 'cobblestone*60,cobblestone*64,-,cobblestone*63'), 'mob minecraft:copper_golem 0.5 -60 0.5 0 117 persistent cooldown=0 hand=cobblestone*16']) add('golem_idle', 400, ['player 4.5 -60 2.5', 'mob minecraft:copper_golem 0.5 -60 0.5 0 118 persistent']) + # The player feeds animals their food (Animal.mobInteract): an adult falls in love once, a baby + # grows each time, and each plays its own eating sound or none (Animal.playEatingSound). + for species, food, seed in [('cow', 'wheat', 120), ('pig', 'carrot', 121), ('sheep', 'wheat', 122), + ('chicken', 'wheat_seeds', 123)]: + for baby in ('', ' baby'): + add(f'feed_{species}{baby.replace(" ", "_")}', 80, [ + 'player 3.5 -60 0.5', + f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent{baby}', + f'feed 20 0 minecraft:{food}', f'feed 40 0 minecraft:{food}', + ]) return s From 9bbb674184d4a92823db37ee2ebb4cce14311931 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:16:32 +0200 Subject: [PATCH 06/13] Game rules: save them with the world once, as they are now; save on Quit Game rules lived twice: Level (loaded when the world opened, written to data/minecraft/game_rules.dat by Level::write) and the rules the game and /gamerule use. Every save wrote the file first with the rules loaded at open, then again with the current ones; a failed second write (on Windows a file just renamed into place can be held briefly by the indexer or an antivirus) was only logged, leaving the old rules on disk, so the world opened with them again. - sync_level copies the current rules into Level, and Level::write is the only writer of game_rules.dat (written as vanilla writes saved data: `_new`, then renamed over the old file). - The world is saved when the application ends without a window close (ApplicationHandler::exiting): on macOS, Quit (Cmd+Q) ends the application through applicationWillTerminate, while vanilla's GLFW window turns it into a window close and Minecraft.stop saves the world. Window close, `horizon-ctl quit` and exiting share save_for_exit, which saves once. Tests: a unit test writes changed rules through Level::write and reads them back (GameRules::load and Level::read); the save round-trip harness has Horizon's player change a rule with /gamerule before saving and requires the new value in the world vanilla then loads. Fixes #74 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 35 ++++++++++++++++----- crates/horizon-client/src/game/chat.rs | 7 ++--- crates/horizon-client/src/game/control.rs | 9 +----- crates/horizon-client/src/gamerules.rs | 37 +++++++++++++++++++++++ tools/test_save_roundtrip_parity.py | 14 ++++++++- 5 files changed, 82 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 56af58e7d..4984b13c6 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -819,6 +819,8 @@ struct Game<'a> { /// This world is open to the network (game/lan.rs). lan: Option, world_options: Option, + /// The world was saved for the application ending (`save_for_exit`). + saved_for_exit: bool, /// The block a guest is acting on (game/lan_actions.rs). forced_hit: Option, /// Level events of this tick for the guests, and the guest acting now. @@ -5714,6 +5716,20 @@ impl Game<'_> { } Ok(()) } + /// Leaving the game with a world open (window closed, Quit, `quit`): + /// menu items go back (Player.closeContainer), then the world is saved, + /// once. + pub(super) fn save_for_exit(&mut self) -> Result<()> { + if self.title.is_some() || self.saved_for_exit { + return Ok(()); + } + self.saved_for_exit = true; + self.close_container(); + if self.remote.is_none() { + self.stats.custom("leave_game", 1); + } + self.save_game() + } fn close_world(&mut self) -> Result<()> { self.ambience.clear(&mut self.audio); // updateLevelInEngines(null): every sound stops; the music manager @@ -7113,6 +7129,8 @@ impl Game<'_> { } /// Copy the live player and world state into the `Level` that gets saved. pub(super) fn sync_level(&mut self) { + // Level.write saves the game rules (game_rules.dat) with the rest. + self.level.game_rules = self.ui.rules.by_name(); self.level.selected_slot = self.selected as i32; let mode = self.mode_id(); let level = &mut self.level; @@ -7824,13 +7842,7 @@ impl ApplicationHandler for Game<'_> { let result: Result<()> = (|| { match event { WindowEvent::CloseRequested => { - if self.title.is_none() { - self.close_container(); - if self.remote.is_none() { - self.stats.custom("leave_game", 1); - } - self.save_game()?; - } + self.save_for_exit()?; event_loop.exit(); } WindowEvent::Resized(size) => { @@ -8344,6 +8356,14 @@ impl ApplicationHandler for Game<'_> { } event_loop.set_control_flow(ControlFlow::Poll); } + /// The application is ending. On macOS, Quit (Cmd+Q) ends it through + /// applicationWillTerminate without a CloseRequested; vanilla's GLFW + /// window turns it into a window close, so Minecraft.stop saves the world. + fn exiting(&mut self, _event_loop: &ActiveEventLoop) { + if let Err(e) = self.save_for_exit() { + eprintln!("Horizon: failed to save the world on exit: {e}"); + } + } } pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { @@ -8699,6 +8719,7 @@ pub fn run() -> Result<()> { remote: None, lan: None, world_options: None, + saved_for_exit: false, forced_hit: None, lan_events: Vec::new(), lan_acting: None, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index d560df45e..0e063abc2 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -642,14 +642,13 @@ impl Game<'_> { self.build_registries(); self.sync_rules(); } - /// Save game rules, the clock and the difficulty beside level.dat. + /// Save the clock and the difficulty beside level.dat (Level.write saves + /// the game rules: a second writer of game_rules.dat could leave it with + /// the rules loaded when the world opened). pub(super) fn save_world_state(&mut self) { if self.world_root.as_os_str().is_empty() { return; } - if let Err(e) = self.ui.rules.save(&self.world_root) { - eprintln!("Horizon: failed to save game rules: {e}"); - } use horizon_world::nbt::Tag; let c = self.ui.clock; // The other clocks stay as saved; the overworld one keeps the fields Horizon diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 0522bef10..1e299bbd3 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -480,14 +480,7 @@ impl Game<'_> { ok() } "quit" => { - if self.title.is_none() { - // Player.closeContainer: menu items go back before saving. - self.close_container(); - if self.remote.is_none() { - self.stats.custom("leave_game", 1); - } - self.save_game()?; - } + self.save_for_exit()?; event_loop.exit(); ok() } diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client/src/gamerules.rs index 92815e908..20bc9fcba 100644 --- a/crates/horizon-client/src/gamerules.rs +++ b/crates/horizon-client/src/gamerules.rs @@ -164,6 +164,20 @@ impl GameRules { } ok } + /// Every rule's value by name without namespace, as `save::Level` holds + /// them (booleans as 0 or 1). + pub fn by_name(&self) -> BTreeMap { + RULES + .iter() + .map(|r| { + let v = match self.values.get(r.name).copied().unwrap_or(r.default) { + Value::Bool(b) => i32::from(b), + Value::Int(i) => i, + }; + (r.name.to_owned(), v) + }) + .collect() + } /// GameRuleMap codec: `{data: {"minecraft:": value...}, DataVersion}`. pub fn to_nbt(&self) -> NamedTag { let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES @@ -253,4 +267,27 @@ mod tests { assert_eq!(GameRules::load(&dir), rules); let _ = fs::remove_dir_all(dir); } + /// The world's save (Level.write) writes the rules as they are now, and a + /// world opened again reads them back (#74). + #[test] + fn level_save_keeps_changed_rules() { + let dir = + std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + let mut level = crate::save::Level::default(); + level.write(&dir).unwrap(); + // Rules changed while playing, then saved and loaded again. + let mut rules = GameRules::load(&dir); + assert_eq!(rules, GameRules::default()); + assert!(rules.set("advance_time", Value::Bool(false))); + assert!(rules.set("advance_weather", Value::Bool(false))); + assert!(rules.set("random_tick_speed", Value::Int(0))); + level.game_rules = rules.by_name(); + level.write(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let read = crate::save::Level::read(&dir).unwrap(); + assert_eq!(read.game_rules, rules.by_name()); + assert_eq!(read.game_rule("advance_time"), 0); + let _ = fs::remove_dir_all(dir); + } } diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 317956a40..7c1cbaa6a 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -46,6 +46,10 @@ SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar' RUN = LOCAL / 'save-roundtrip' / 'run' PORT = 25000 + (os.getpid() % 5000) + 1000 +# Game rules Horizon's player changes before saving: rule -> (vanilla's value, Horizon's). +# The new value must be in Horizon's save, and nothing else may differ (#74). +HORIZON_RULES = {'max_entity_cramming': (24, 30)} + # Differences that do not change what vanilla reads: path pattern (list indices as []) # -> reason. Anything else is a failure. IGNORED = { @@ -335,7 +339,9 @@ def horizon_resave(source, destination, bin_dir): print(launch.stdout.strip()) if launch.returncode: sys.exit('horizon failed to launch: ' + launch.stdout + launch.stderr) - steps = [['wait-ready', '240'], ['save-all'], ['quit']] + steps = [['wait-ready', '240']] + steps += [['chat', f'/gamerule {rule} {new}'] for rule, (_, new) in HORIZON_RULES.items()] + steps += [['save-all'], ['quit']] for step in steps: result = subprocess.run(ctl + step, cwd=destination, env=env, capture_output=True, text=True) print(' '.join(step), '->', result.stdout.strip() or result.stderr.strip()) @@ -545,6 +551,12 @@ def compare_worlds(vanilla, horizon): if rel.endswith('scoreboard.dat'): va, hb = normalize_scoreboard(va), normalize_scoreboard(hb) compare_dat(rel, va, hb, report) + for rule, (old, new) in HORIZON_RULES.items(): + changed = (f'data/minecraft/game_rules.dat.data.minecraft:{rule}', old, new) + if changed in report: + report.remove(changed) + else: + report.append((changed[0], f'{new} set in Horizon', 'not saved')) return report From 162e3d36f7c00ffc7d34fcfed157c7635b4cd9d4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:27:13 +0200 Subject: [PATCH 07/13] Give the fire charge's use sound its own pitch Placing fire with a fire charge played item.firecharge.use at the flint and steel's pitch (nextFloat * 0.4 + 0.8, one draw). FireChargeItem.playSound uses (nextFloat - nextFloat) * 0.2 + 1.0, two draws from the level random. The pitch is now horizon_client::items::fire_starter_pitch, checked against the real FireChargeItem.playSound by tools/test_fire_starter_sound_parity.py. Co-Authored-By: Claude Opus 5.5 --- .../examples/fire_starter_sound_probe.rs | 32 +++++++++ crates/horizon-client/src/game.rs | 15 ++--- crates/horizon-client/src/items.rs | 21 ++++++ .../parity/VanillaFireStarterSoundOracle.java | 66 +++++++++++++++++++ tools/test_fire_starter_sound_parity.py | 32 +++++++++ 5 files changed, 156 insertions(+), 10 deletions(-) create mode 100644 crates/horizon-client/examples/fire_starter_sound_probe.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFireStarterSoundOracle.java create mode 100644 tools/test_fire_starter_sound_parity.py diff --git a/crates/horizon-client/examples/fire_starter_sound_probe.rs b/crates/horizon-client/examples/fire_starter_sound_probe.rs new file mode 100644 index 000000000..62fab117a --- /dev/null +++ b/crates/horizon-client/examples/fire_starter_sound_probe.rs @@ -0,0 +1,32 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_fire_starter_sound_parity.py's level random seeds through +//! the fire charge's use sound (`horizon_client::items::fire_starter_pitch`). +use horizon_client::{ + Result, + items::{fire_starter_pitch, fire_starter_sound}, +}; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for line in input.lines() { + let mut random = LegacyRandom::new(line?.trim().parse()?); + let pitch = fire_starter_pitch(true, &mut random); + writeln!( + out, + "{} {} {} {}", + fire_starter_sound(true), + 1.0f32.to_bits() as i32, + pitch.to_bits() as i32, + random.next_long() + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 56af58e7d..c888850c2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6267,17 +6267,12 @@ impl Game<'_> { if !self.try_light_portal(target)? { self.set_state_named(target, "minecraft:fire", &[])?; } - let sound = if item == "fire_charge" { - "minecraft:item.firecharge.use" - } else { - "minecraft:item.flintandsteel.use" - }; - self.audio.play( - sound, - Some(at(target)), - 1.0, - self.world.random.next_float() * 0.4 + 0.8, + let sound = horizon_client::items::fire_starter_sound(item == "fire_charge"); + let pitch = horizon_client::items::fire_starter_pitch( + item == "fire_charge", + &mut self.world.random, ); + self.audio.play(sound, Some(at(target)), 1.0, pitch); if item == "fire_charge" { self.consume_held(); } else { diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8c9bc2e02..8a71b77ab 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -12,6 +12,27 @@ use std::{ sync::Arc, }; +/// A fire starter's use sound: `SoundEvents.FIRECHARGE_USE` or +/// `FLINTANDSTEEL_USE`. +pub fn fire_starter_sound(fire_charge: bool) -> &'static str { + if fire_charge { + "minecraft:item.firecharge.use" + } else { + "minecraft:item.flintandsteel.use" + } +} + +/// The pitch of a fire starter's use sound, from the level's random: +/// `FlintAndSteelItem.useOn`'s `nextFloat() * 0.4 + 0.8`, or +/// `FireChargeItem.playSound`'s `(nextFloat() - nextFloat()) * 0.2 + 1.0`. +pub fn fire_starter_pitch(fire_charge: bool, random: &mut impl RandomSource) -> f32 { + if fire_charge { + (random.next_float() - random.next_float()) * 0.2 + 1.0 + } else { + random.next_float() * 0.4 + 0.8 + } +} + #[derive(Clone, Debug)] pub struct ToolRule { pub blocks: Vec, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFireStarterSoundOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFireStarterSoundOracle.java new file mode 100644 index 000000000..276a0aae3 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFireStarterSoundOracle.java @@ -0,0 +1,66 @@ +package dev.horizonlab.parity; + +import java.io.*; +import java.lang.reflect.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.util.RandomSource; +import net.minecraft.world.item.FireChargeItem; +import net.minecraft.world.item.Items; +import net.minecraft.world.level.Level; + +/** + * Original oracle for the fire charge's use sound: the real private + * FireChargeItem.playSound (used for both a lit campfire or candle and a + * placed fire) on a level stand-in whose random is seeded from the case, + * recording the sound, its volume and pitch and the level random's next long + * (which shows how many values the sound drew). + */ +public final class VanillaFireStarterSoundOracle { + static final StringBuilder sounds = new StringBuilder(); + + static final class World extends ServerLevel { + World() { + super(null, null, null, null, null, null, false, 0L, List.of(), false); + } + @Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, + net.minecraft.core.Holder s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { + sounds.append(s.unwrapKey().orElseThrow().identifier()).append(' ') + .append(Float.floatToIntBits(v)).append(' ').append(Float.floatToIntBits(pitch)); + } + } + + static void put(Object unsafe, Object target, String name, Object value) throws Exception { + Field f = Level.class.getDeclaredField(name); + long offset = (long) unsafe.getClass().getMethod("objectFieldOffset", Field.class).invoke(unsafe, f); + unsafe.getClass().getMethod("putObject", Object.class, long.class, Object.class).invoke(unsafe, target, offset, value); + } + + public static void main(String[] args) throws Exception { + ParityData.init(); + var u = Class.forName("sun.misc.Unsafe"); + Field theUnsafe = u.getDeclaredField("theUnsafe"); + theUnsafe.setAccessible(true); + Object unsafe = theUnsafe.get(null); + World world = (World) u.getMethod("allocateInstance", Class.class).invoke(unsafe, World.class); + Method play = FireChargeItem.class.getDeclaredMethod("playSound", Level.class, BlockPos.class); + play.setAccessible(true); + var item = (FireChargeItem) Items.FIRE_CHARGE; + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (var line : (Iterable) lines::iterator) { + long seed = Long.parseLong(line.trim()); + RandomSource random = RandomSource.create(seed); + put(unsafe, world, "random", random); + put(unsafe, world, "soundSeedGenerator", RandomSource.create(0)); + sounds.setLength(0); + play.invoke(item, world, new BlockPos(3, 64, -7)); + out.println(sounds + " " + random.nextLong()); + } + } + System.exit(0); + } +} diff --git a/tools/test_fire_starter_sound_parity.py b/tools/test_fire_starter_sound_parity.py new file mode 100644 index 000000000..bac04f4aa --- /dev/null +++ b/tools/test_fire_starter_sound_parity.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Compare the fire charge's use sound with the pinned client: the real +FireChargeItem.playSound (lighting a campfire or candle and placing fire both +use it) on level randoms from many seeds, comparing the sound, its volume and +pitch bits, and the level random's next value (how many values it drew).""" +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def make_cases(build): + path = build / 'cases.txt' + rng = random.Random(0x46495245) + seeds = [0, 1, -1, 42, 2**63 - 1, -2**63] + [rng.randrange(-2**63, 2**63) for _ in range(20000)] + path.write_text(''.join(f'{s}\n' for s in seeds)) + return path, len(seeds) + + +def main(): + scope = ('The real private FireChargeItem.playSound on a ServerLevel stand-in with a seeded LegacyRandomSource: ' + 'the sound event, volume, pitch ((nextFloat - nextFloat) * 0.2 + 1) and the random afterwards. ' + 'FireChargeItem.useOn\'s choice between lighting and placing fire is not exercised.') + harness.differential( + 'rust-fire-starter-sound-parity', 'VanillaFireStarterSoundOracle', 'fire_starter_sound_probe', make_cases, + scope, sources=[lab.ROOT / 'crates/horizon-client/src/items.rs']) + + +if __name__ == '__main__': + main() From 84adffc3f227baa6747f7f9bf864181d47ba7ca9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:30:30 +0200 Subject: [PATCH 08/13] Hand sway: the first-person hands lag behind the view, as in vanilla Vanilla keeps xBob and yBob on the LocalPlayer: applyInput eases them halfway to the player's rotation every tick, and FirstPersonHandsAndItemsRenderer turns both hands by (viewXRot - xBob) * 0.1 degrees about X, then (viewYRot - yBob) * 0.1 about Y, before drawing either (FirstPersonHandsAndItems.extractRenderState interpolates the bobs). Horizon drew the hands fixed to the view. - first_person::HandSway: the bobs, applyInput's tick and the rotation. - The game ticks it with the hands and resets it where vanilla makes a new LocalPlayer (joining, respawning, changing dimension, leaving the End); hand_geometry turns the arm, held items and maps by it. The first-person harness's steps can turn the player: the oracle sets the LocalPlayer's rotation and calls the real applyInput, and both sides print xBob, yBob, xBobO and yBobO every tick (turning scenarios plus random turns in the random cases). Fixes #66 Co-Authored-By: Claude Opus 5.5 --- .../examples/first_person_probe.rs | 17 +++++++++-- crates/horizon-client/src/first_person.rs | 29 +++++++++++++++++++ crates/horizon-client/src/game.rs | 12 +++++++- crates/horizon-client/src/game/end.rs | 1 + crates/horizon-client/src/game/hand.rs | 4 +++ crates/horizon-client/src/game/remote.rs | 1 + .../parity/VanillaFirstPersonOracle.java | 17 +++++++++-- tools/test_first_person_parity.py | 26 +++++++++++++---- 8 files changed, 96 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/examples/first_person_probe.rs b/crates/horizon-client/examples/first_person_probe.rs index 3fe203a48..7b1143114 100644 --- a/crates/horizon-client/examples/first_person_probe.rs +++ b/crates/horizon-client/examples/first_person_probe.rs @@ -5,7 +5,7 @@ use horizon_client::{ Result, attack_strength::{AttackStrength, HeldStack}, first_person::{ - Clicks, Hand, HandHeights, HandWorld, Hit, SwingAnimation, SwingState, UseResult, + Clicks, Hand, HandHeights, HandSway, HandWorld, Hit, SwingAnimation, SwingState, UseResult, swing_duration, }, }; @@ -308,6 +308,9 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { let mut strength = AttackStrength::default(); // FirstPersonHandsAndItems' visible items start as ItemStack.EMPTY. let mut visible = [0usize, 0usize]; + // The player's xRot and yRot, and the hands' lag behind them. + let mut rot = [0.0f32; 2]; + let mut sway = HandSway::default(); for (s, step) in case["steps"].as_array().unwrap().iter().enumerate() { probe.step = step; probe.events.clear(); @@ -327,6 +330,10 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { step["ud"].as_bool().unwrap(), ); probe.swing.tick(); + if let Some(r) = step["rot"].as_array() { + rot = [fl(&r[0]), fl(&r[1])]; + } + sway.tick(rot[0], rot[1]); let main = probe.stack(Hand::Main).clone(); strength.tick(held(&main)); // FirstPersonHandsAndItems.tick: shouldInstantlyReplaceVisibleItem @@ -363,7 +370,7 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { let d = &clicks.destroying; writeln!( out, - "tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", + "tick {s} {current} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}", sw.ticks, fb(sw.animation), fb(sw.old_animation), @@ -379,7 +386,11 @@ fn run(case: &Value, out: &mut impl Write) -> Result<()> { clicks.right_click_delay, d.delay, d.active, - fb(d.progress) + fb(d.progress), + fb(sway.x_bob), + fb(sway.y_bob), + fb(sway.x_bob_o), + fb(sway.y_bob_o) )?; } Ok(()) diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 757a93873..170b0417d 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -192,6 +192,35 @@ impl HandHeights { } } +/// `LocalPlayer.xBob` and `yBob`: the hands lag behind the view when it +/// turns. `LocalPlayer.applyInput` eases them halfway to the rotation every +/// tick; `FirstPersonHandsAndItemsRenderer` turns the hands by a tenth of +/// the gap left. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct HandSway { + pub x_bob: f32, + pub y_bob: f32, + pub x_bob_o: f32, + pub y_bob_o: f32, +} +impl HandSway { + /// `LocalPlayer.applyInput` with the player's `getXRot` and `getYRot`. + pub fn tick(&mut self, x_rot: f32, y_rot: f32) { + self.y_bob_o = self.y_bob; + self.x_bob_o = self.x_bob; + self.x_bob += (x_rot - self.x_bob) * 0.5; + self.y_bob += (y_rot - self.y_bob) * 0.5; + } + /// The degrees the hands turn about X, then Y, before either is drawn: + /// `(viewXRot - xBob) * 0.1` and `(viewYRot - yBob) * 0.1`, the bobs + /// interpolated as `extractRenderState` does. + pub fn rotation(&self, partial: f32, view_x_rot: f32, view_y_rot: f32) -> [f32; 2] { + let x_bob = crate::camera::lerp(partial, self.x_bob_o, self.x_bob); + let y_bob = crate::camera::lerp(partial, self.y_bob_o, self.y_bob); + [(view_x_rot - x_bob) * 0.1, (view_y_rot - y_bob) * 0.1] + } +} + /// `HitResult` at the crosshair (`Minecraft.hitResult`). #[derive(Clone, Copy, Debug, PartialEq)] pub enum Hit { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 56af58e7d..edfeb3ff7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -706,6 +706,9 @@ struct Game<'a> { /// The first-person equip heights and the items the hands show (with /// the slot each came from). heights: horizon_client::first_person::HandHeights, + /// The hands' lag behind the view (`LocalPlayer.xBob`, `yBob`); a new + /// LocalPlayer (joining, respawning, changing dimension) starts at 0. + sway: horizon_client::first_person::HandSway, visible_hands: [(usize, Option); 2], /// `Minecraft`'s attack handling, attack clicks since the last tick and /// the attack strength tickers the hand reads. @@ -2585,6 +2588,7 @@ impl Game<'_> { } self.previous_position = feet; self.player = Some(player); + self.sway = Default::default(); self.apply_equipment(); self.eye = 1.62; self.previous_eye = 1.62; @@ -5650,6 +5654,7 @@ impl Game<'_> { player.velocity = Vec3::ZERO; self.previous_position = player.position; self.player = Some(player); + self.sway = Default::default(); self.apply_equipment(); let at = [f64::from(spot[0]), f64::from(spot[1]), f64::from(spot[2])]; self.audio @@ -6526,7 +6531,11 @@ impl Game<'_> { }; let inverse_height = 1.0 - self.heights.interpolated(a)[0]; let view = horizon_client::camera::view_matrix(self.yaw, self.pitch); - let to_world = view.inverse(); + // The hand sway: both hands turn by a tenth of the bobs' lag. + let [sway_x, sway_y] = self.sway.rotation(a, self.pitch, self.yaw); + let to_world = view.inverse() + * glam::Mat4::from_rotation_x(sway_x.to_radians()) + * glam::Mat4::from_rotation_y(sway_y.to_radians()); let eye = self.eye_position().unwrap_or_default(); let light = self.world.light( eye[0].floor() as i32, @@ -8616,6 +8625,7 @@ pub fn run() -> Result<()> { swing: Default::default(), swings_started: 0, heights: Default::default(), + sway: Default::default(), visible_hands: [(0, None), (0, None)], clicks: Default::default(), attack_clicks: 0, diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index b7366a03e..ded41fb3d 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -485,6 +485,7 @@ impl Game<'_> { player.fall_distance = 0.0; self.previous_position = player.position; self.player = Some(player); + self.sway = Default::default(); self.apply_equipment(); let pitch = self.world.random.next_float() * 0.4 + 0.8; self.audio diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index f4c43042c..e414a719b 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -170,6 +170,10 @@ impl Game<'_> { /// strength and item swap tickers (`Player.tick`), then /// `FirstPersonHandsAndItems.tick`. pub(super) fn tick_hand(&mut self) { + // LocalPlayer.applyInput (the camera is the player's own). + if self.player.is_some() { + self.sway.tick(self.pitch, self.yaw); + } self.swing.tick(); let main = self.inventory[self.selected].clone(); self.hand_strength.tick(main.as_ref().map(|s| HeldStack { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3fc55d0b3..8b01953d0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1569,6 +1569,7 @@ impl Game<'_> { let mut player = PlayerMotion::new(self.motion, position)?; player.velocity = delta; self.player = Some(player); + self.sway = Default::default(); self.eye = 1.62; self.previous_eye = 1.62; self.clock.reset(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFirstPersonOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFirstPersonOracle.java index a249c2b17..1ddaa64b7 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFirstPersonOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaFirstPersonOracle.java @@ -50,7 +50,9 @@ import net.minecraft.world.phys.*; * level, connection and item model resolver are shells answering what these * read, and the results of using items on blocks, entities and the air are * scripted. The attack and use part of Minecraft.handleKeybinds and the - * ticker lines of Player.tick are mirrored here in vanilla's order. + * ticker lines of Player.tick are mirrored here in vanilla's order. Steps may + * turn the player; the real LocalPlayer.applyInput moves the hands' xBob and + * yBob after it. */ public final class VanillaFirstPersonOracle { static Object unsafe; @@ -150,6 +152,8 @@ public final class VanillaFirstPersonOracle { } @Override public AttributeMap getAttributes() { return attributes; } + // The shell Minecraft has no game renderer: the player is the camera. + @Override protected boolean isControlledCamera() { return true; } @Override public boolean isEyeInFluid(TagKey type) { return false; } @Override public boolean onGround() { return true; } @Override public boolean isWithinEntityInteractionRange(Entity entity, double buffer) { return inRange; } @@ -274,6 +278,7 @@ public final class VanillaFirstPersonOracle { swingState.set(player, new LivingEntity.SwingState()); lastItem.set(player, ItemStack.EMPTY); hands.set(player, new FirstPersonHandsAndItems()); + player.input = new net.minecraft.client.player.ClientInput(); var effects = new HashMap, MobEffectInstance>(); if (!c.get("haste").isJsonNull()) { effects.put(MobEffects.HASTE, new MobEffectInstance(MobEffects.HASTE, 100000, c.get("haste").getAsInt())); @@ -363,6 +368,13 @@ public final class VanillaFirstPersonOracle { } lastItem.set(player, main.copy()); } + // LocalPlayer.aiStep's applyInput, after the step's turn. + if (step.has("rot") && !step.get("rot").isJsonNull()) { + var rot = step.getAsJsonArray("rot"); + player.setXRot(Float.intBitsToFloat(Integer.parseUnsignedInt(rot.get(0).getAsString(), 16))); + player.setYRot(Float.intBitsToFloat(Integer.parseUnsignedInt(rot.get(1).getAsString(), 16))); + } + player.applyInput(); var fp = (FirstPersonHandsAndItems) hands.get(player); fp.tick(player); for (var ev : events) { @@ -376,7 +388,8 @@ public final class VanillaFirstPersonOracle { + " " + fb(mainHeight.getFloat(fp)) + " " + fb(oMainHeight.getFloat(fp)) + " " + fb(offHeight.getFloat(fp)) + " " + fb(oOffHeight.getFloat(fp)) + " " + missTime.getInt(mc) + " " + rightClickDelay.getInt(mc) + " " + destroyDelay.getInt(gameMode) - + " " + destroying.getBoolean(gameMode) + " " + fb(progress.getFloat(gameMode))); + + " " + destroying.getBoolean(gameMode) + " " + fb(progress.getFloat(gameMode)) + + " " + fb(player.xBob) + " " + fb(player.yBob) + " " + fb(player.xBobO) + " " + fb(player.yBobO)); } } } diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index 84ee250ff..d73262595 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -47,9 +47,12 @@ ITEMS = [None, ['minecraft:diamond_sword', 1], ['minecraft:diamond_pickaxe', 1], TARGETS = [(0, 64, 0), (1, 64, 0), (0, 65, 2)] -def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False, uses=None, shrink=False, set=None): +def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False, uses=None, shrink=False, set=None, + rot=None): + """rot: the player's (xRot, yRot) from this step on (LocalPlayer.applyInput's hand sway).""" return dict(hit=list(hit), ac=ac, uc=uc, ad=ad, ud=ud, busy=busy, using=using, - uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set) + uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set, + rot=None if rot is None else [fbits(rot[0]), fbits(rot[1])]) def case(steps, creative=False, main=None, off=None, blocks=None, haste=None, fatigue=None): @@ -120,12 +123,24 @@ def scenarios(): yield case(steps, True, None, blocks={TARGETS[1]: 'minecraft:dirt'}, haste=haste, fatigue=fatigue) +def turning_cases(): + """The hands lag behind the view: turns, snaps, a yaw past 180 and back, pitch to its limits.""" + for main in (None, ['minecraft:diamond_sword', 1]): + steps = [step(rot=(0.0, 0.0))] + steps += [step(rot=(0.0, 4.5 * i)) for i in range(1, 40)] + steps += [step()] * 6 + steps += [step(rot=(90.0, 179.5)), step(rot=(-90.0, 185.25)), step(rot=(-12.75, 900.0))] + [step()] * 8 + steps += [step(rot=(30.0 - i, -720.0 + 33.3 * i), ac=i % 2, ad=True) for i in range(30)] + [step()] * 4 + yield case(steps, False, main) + + def random_cases(rng): results = ['success', 'server', 'consume', 'pass', 'fail'] for _ in range(3000): blocks = {p: rng.choice(list(BLOCKS) + ['minecraft:air']) for p in TARGETS} steps = [] for _ in range(rng.randrange(5, 80)): + rot = (rng.uniform(-90.0, 90.0), rng.uniform(-1080.0, 1080.0)) if rng.random() < 0.3 else None hit = rng.choice([('miss',), ('entity', rng.random() < 0.7)] + [block_hit(p, rng.randrange(6)) for p in TARGETS] * 2) setting = None if rng.random() < 0.04: @@ -133,7 +148,7 @@ def random_cases(rng): steps.append(step(hit, ac=rng.choice([0] * 6 + [1, 1, 2]), uc=rng.choice([0] * 8 + [1, 2]), ad=rng.random() < 0.5, ud=rng.random() < 0.3, busy=rng.random() < 0.05, using=rng.random() < 0.08, uses=dict(entity=rng.choice(results), block=rng.choice(results), item=rng.choice(results)), - shrink=rng.random() < 0.3, set=setting)) + shrink=rng.random() < 0.3, set=setting, rot=rot)) yield case(steps, rng.random() < 0.4, rng.choice(ITEMS), rng.choice(ITEMS), blocks, rng.choice([None] * 6 + [0, 1, 3]), rng.choice([None] * 6 + [0, 2])) @@ -145,7 +160,7 @@ def make_cases(build): cases.mkdir(exist_ok=True) count = 0 with path.open('w') as out: - for generator in (scenarios(), random_cases(rng)): + for generator in (scenarios(), turning_cases(), random_cases(rng)): for c in generator: text = json.dumps(c, separators=(',', ':')) out.write(text + '\n') @@ -163,7 +178,8 @@ def main(): 'FirstPersonHandsAndItems.tick and itemUsed, on a LocalPlayer shell with a real Inventory, effects and attribute ' 'modifiers, over scripted clicks, held buttons, crosshair targets, item changes and use results. Level effects ' '(particles, game events), packets and the outcome of using items on blocks, entities and the air are scripted ' - 'or absorbed; every vanilla item plays the swap animation unscaled except spears, which are not scripted.') + 'or absorbed; every vanilla item plays the swap animation unscaled except spears, which are not scripted. Steps also ' + 'turn the player: the real LocalPlayer.applyInput moves xBob and yBob, the hands\' lag behind the view.') harness.differential( 'rust-first-person-parity', 'VanillaFirstPersonOracle', 'first_person_probe', make_cases, scope, sources=[lab.ROOT / 'crates/horizon-client/src/first_person.rs', lab.ROOT / 'crates/horizon-client/src/attack_strength.rs', From d75ad778e3d12d7c869e665f7bab4ecf8d417334 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 15:20:30 +0200 Subject: [PATCH 09/13] Read the physical Shift keys in container screens and drop a stack clicked outside Quick move, the recipe book's place-all, its search box and the hold-Shift tooltips read self.keys, which holds remapped and toggled keys: with toggle sneak, a Left Shift press behind a screen is dropped by the sneak mapping and sync_toggle then removes ShiftLeft. Vanilla reads the event's own modifiers (InputWithModifiers.hasShiftDown) or Screen.hasShiftDown: the physical keys. Track them in physical_keys and read them through has_shift_down. Clicking outside the window did nothing. AbstractContainerScreen.mouseClicked sends slot -999 when hasClickedOutside (AbstractRecipeBookScreen's rule when the screen has a book): a held stack starts a quick craft drag whose release sends PICKUP -999, which AbstractContainerMenu.doClick turns into a drop of the stack (left) or one item (right), thrown from the hand with a swing. The mouse handling is now horizon_client::container_screen, checked against the real screens by tools/test_container_screen_parity.py; servers get the same ContainerClick. Co-Authored-By: Claude Opus 5.5 --- .../examples/container_screen_probe.rs | 86 ++++++ crates/horizon-client/src/container_screen.rs | 278 ++++++++++++++++++ crates/horizon-client/src/game.rs | 176 ++++++++++- crates/horizon-client/src/game/control.rs | 4 + crates/horizon-client/src/game/item_draw.rs | 4 +- crates/horizon-client/src/game/recipe_book.rs | 21 +- crates/horizon-client/src/game/remote.rs | 35 ++- .../src/game/station_control.rs | 6 +- crates/horizon-client/src/lib.rs | 1 + .../parity/VanillaContainerScreenOracle.java | 170 +++++++++++ tools/test_container_screen_parity.py | 95 ++++++ 11 files changed, 854 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client/examples/container_screen_probe.rs create mode 100644 crates/horizon-client/src/container_screen.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaContainerScreenOracle.java create mode 100644 tools/test_container_screen_parity.py diff --git a/crates/horizon-client/examples/container_screen_probe.rs b/crates/horizon-client/examples/container_screen_probe.rs new file mode 100644 index 000000000..b89b23a2a --- /dev/null +++ b/crates/horizon-client/examples/container_screen_probe.rs @@ -0,0 +1,86 @@ +#![forbid(unsafe_code)] +//! Runs tools/test_container_screen_parity.py's screens and mouse events +//! through `horizon_client::container_screen`. +use horizon_client::{ + Result, + container_screen::{Book, Button, Clicks, Image, Release, Target, clicked_outside}, + menu::Input, +}; +use serde_json::Value; +use std::{ + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, +}; + +fn input_name(input: Input) -> &'static str { + match input { + Input::Pickup => "PICKUP", + Input::QuickMove => "QUICK_MOVE", + Input::Swap => "SWAP", + Input::Clone => "CLONE", + Input::Throw => "THROW", + Input::QuickCraft => "QUICK_CRAFT", + Input::PickupAll => "PICKUP_ALL", + } +} + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let input = BufReader::new(File::open(&args[1])?); + let mut out = BufWriter::new(File::create(&args[2])?); + for (n, line) in input.lines().enumerate() { + let c: Value = serde_json::from_str(&line?)?; + writeln!(out, "== {n}")?; + let int = |v: &Value| v.as_i64().unwrap() as i32; + let image = Image { + left: int(&c["image"][0]), + top: int(&c["image"][1]), + width: int(&c["image"][2]), + height: int(&c["image"][3]), + }; + let book = c.get("book").map(|b| Book { + visible: b[0].as_bool().unwrap(), + selected_tab_hovered: b[1].as_bool().unwrap(), + }); + let mut clicks = Clicks::default(); + for ev in c["events"].as_array().unwrap() { + let name = ev[0].as_str().unwrap(); + let (x, y) = (ev[1].as_f64().unwrap(), ev[2].as_f64().unwrap()); + let outside = clicked_outside(x, y, image, book); + let mut line = format!("{name} {outside}"); + if name != "point" { + // The case says whether the event is over the menu's slot (7). + let on_slot = ev[6].as_bool().unwrap(); + line += &format!(" {on_slot}"); + let target = Target::of(on_slot.then_some(7), outside); + let button = match ev[3].as_i64().unwrap() { + 1 => Button::Left, + 3 => Button::Right, + _ => Button::Middle, + }; + let shift = ev[4].as_i64().unwrap() & 3 != 0; + let carried_empty = !ev[5].as_bool().unwrap(); + let click = if name == "press" { + clicks.press(&target, button, carried_empty, shift, false) + } else { + match clicks.release(&target, button, carried_empty, false, shift, false) { + Release::Click(input) => Some(input), + Release::QuickCraft => panic!("no drags in these cases"), + Release::Nothing => None, + } + }; + if let Some(input) = click { + let id = match target { + Target::Slot(s) => s, + Target::Outside => -999, + Target::Nothing => -1, + }; + line += &format!(" click {id} {} {}", button.menu_button(), input_name(input)); + } + } + writeln!(out, "{line}")?; + } + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs new file mode 100644 index 000000000..2c490861a --- /dev/null +++ b/crates/horizon-client/src/container_screen.rs @@ -0,0 +1,278 @@ +//! The mouse handling every survival and container screen shares +//! (`AbstractContainerScreen.mouseClicked` / `mouseReleased`): which slot id +//! a click targets (-999 outside the window, `hasClickedOutside` with the +//! recipe book's own rule) and which `ContainerInput` it sends. Shift is +//! the event's own modifiers (`InputWithModifiers.hasShiftDown`: the +//! physical Shift keys, never the remapped or toggled sneak key). + +use crate::menu::Input; + +/// The screen's window: `leftPos`, `topPos`, `imageWidth`, `imageHeight`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Image { + pub left: i32, + pub top: i32, + pub width: i32, + pub height: i32, +} + +/// The recipe book of an `AbstractRecipeBookScreen`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub struct Book { + /// `RecipeBookComponent.isVisible`. + pub visible: bool, + /// `selectedTab.isHoveredOrFocused()`. + pub selected_tab_hovered: bool, +} + +/// `RecipeBookComponent.IMAGE_WIDTH`. +const BOOK_WIDTH: i32 = 147; + +fn outside(mx: f64, my: f64, image: Image) -> bool { + mx < f64::from(image.left) + || my < f64::from(image.top) + || mx >= f64::from(image.left + image.width) + || my >= f64::from(image.top + image.height) +} + +/// `AbstractContainerScreen.hasClickedOutside`, or +/// `AbstractRecipeBookScreen.hasClickedOutside` when the screen has a book +/// (`RecipeBookComponent.hasClickedOutside`: a click on the book, or with +/// its selected tab hovered, is not outside). +pub fn clicked_outside(mx: f64, my: f64, image: Image, book: Option) -> bool { + let out = outside(mx, my, image); + let Some(book) = book else { + return out; + }; + let book_outside = !book.visible || { + let on_book = f64::from(image.left - BOOK_WIDTH) < mx + && mx < f64::from(image.left) + && f64::from(image.top) < my + && my < f64::from(image.top + image.height); + out && !on_book && !book.selected_tab_hovered + }; + book_outside && out +} + +/// What a click points at: a slot, outside the window (slot id -999), or +/// neither (slot id -1). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Target { + Slot(S), + Outside, + Nothing, +} + +impl Target { + /// Outside wins over a hovered slot, as in `mouseClicked`. + pub fn of(slot: Option, outside: bool) -> Self { + match slot { + _ if outside => Self::Outside, + Some(s) => Self::Slot(s), + None => Self::Nothing, + } + } +} + +/// The left, right and middle buttons (SDL's 1, 3 and 2). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Button { + Left, + Right, + Middle, +} + +impl Button { + /// `getContainerClickButton`: the button a menu click carries. + pub fn menu_button(self) -> i32 { + match self { + Self::Left => 0, + Self::Right => 1, + Self::Middle => 2, + } + } +} + +/// The input state `mouseClicked`/`mouseReleased` keep between events. +#[derive(Clone, Debug, Default)] +pub struct Clicks { + /// `isQuickCrafting` with `quickCraftingButton`. + quick_crafting: Option