From 42eda649a8d75e1221a55010297d95ca976d291b Mon Sep 17 00:00:00 2001 From: rdbtCVS <87152661+rdbtCVS@users.noreply.github.com> Date: Wed, 14 Oct 2026 21:45:40 +0100 Subject: [PATCH 1/8] Render Classic menu panorama with vanilla cube-map filtering --- crates/horizon-client/src/game.rs | 91 +---- crates/horizon-client/src/game/packs.rs | 2 + crates/horizon-client/src/gfx.rs | 28 +- crates/horizon-client/src/gfx/panorama.rs | 346 ++++++++++++++++++++ crates/horizon-client/src/gfx/panorama.wgsl | 30 ++ crates/horizon-client/src/hud.rs | 16 +- 6 files changed, 409 insertions(+), 104 deletions(-) create mode 100644 crates/horizon-client/src/gfx/panorama.rs create mode 100644 crates/horizon-client/src/gfx/panorama.wgsl diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2d16d4e28..9a7026d86 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -580,6 +580,7 @@ pub struct Resources { biomes: Arc, environment: Environment, atlas: HudAtlas, + panorama: horizon_client::gfx::panorama::Faces, layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, @@ -6035,91 +6036,6 @@ impl Game<'_> { self.capture(false); Ok(()) } - /// The title panorama as six camera-centred faces (panorama_0..5: - /// front, right, back, left, up, down). - fn panorama_geometry(&self) -> Vec { - let mut out = Vec::new(); - let d = 100.0; - let faces: [(&str, [glam::Vec3; 4]); 6] = [ - ( - "0", - [ - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(-d, -d, -d), - ], - ), - ( - "1", - [ - glam::Vec3::new(d, d, -d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(d, -d, -d), - ], - ), - ( - "2", - [ - glam::Vec3::new(d, d, d), - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, -d, d), - glam::Vec3::new(d, -d, d), - ], - ), - ( - "3", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(-d, d, -d), - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(-d, -d, d), - ], - ), - ( - "4", - [ - glam::Vec3::new(-d, d, d), - glam::Vec3::new(d, d, d), - glam::Vec3::new(d, d, -d), - glam::Vec3::new(-d, d, -d), - ], - ), - ( - "5", - [ - glam::Vec3::new(-d, -d, -d), - glam::Vec3::new(d, -d, -d), - glam::Vec3::new(d, -d, d), - glam::Vec3::new(-d, -d, d), - ], - ), - ]; - for (index, corners) in faces { - let Some(r) = self - .res - .atlas - .sprites - .get(&format!("gui/title/background/panorama_{index}")) - .copied() - else { - continue; - }; - let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]; - for (p, uv) in corners.iter().zip(uv) { - out.push(Vertex { - normal: [0; 4], - pos: p.to_array(), - uv, - layer: 2, - color: 0xFFFF_FFFF, - light: 0, - }); - } - } - out - } /// Equipment attribute modifiers (LivingEntity.collectEquipmentChanges). fn apply_equipment(&mut self) { let Some(player) = self.player.as_mut() else { @@ -6976,6 +6892,7 @@ impl Game<'_> { self.res.atlas.height, ), (&self.res.forcefield.2, self.res.forcefield.0), + &self.res.panorama, )) } fn apply_settings(&mut self) { @@ -7788,7 +7705,7 @@ impl Game<'_> { } } let celestial = if title && !live { - self.panorama_geometry() + Vec::new() } else if self.dim == Dim::Overworld && self.potions.effects.get("darkness").is_none() && self.potions.effects.get("blindness").is_none() @@ -8874,6 +8791,7 @@ pub fn run() -> Result<()> { let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], @@ -8941,6 +8859,7 @@ pub fn run() -> Result<()> { biomes, environment, atlas, + panorama, item_renderer: Arc::new(horizon_client::item_render::ItemRenderer::load(&root)?), layer_names, providers: Providers::load(&root), diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index f1e476f8d..0d3f8a74a 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -112,6 +112,7 @@ impl Game<'_> { fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let assets = std::sync::Arc::new(self.res.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; + let panorama = horizon_client::gfx::panorama::Faces::load(root); atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let item_renderer = horizon_client::item_render::ItemRenderer::load(root)?; @@ -137,6 +138,7 @@ impl Game<'_> { self.res.assets = assets; self.res.context = context.clone(); self.res.atlas = atlas; + self.res.panorama = panorama; self.res.item_renderer = std::sync::Arc::new(item_renderer); self.res.clouds = super::load_clouds(root); self.res.forcefield = super::load_forcefield(root); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 6d8e5384d..698a2528e 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -83,6 +83,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod occlusion; +pub mod panorama; mod timing; mod world_post; @@ -137,7 +138,7 @@ pub struct Frame<'a> { /// Skip sections the camera cannot see through open faces (vanilla's /// occlusion graph; off in spectator-like views inside blocks). pub cave_culling: bool, - /// Title screen: only the panorama (in `celestial`) and the HUD. + /// Title screen: only the dedicated panorama cube map and the HUD. pub title: bool, /// Dimensions without a skybox (the Nether) clear to the fog colour. pub skybox: bool, @@ -246,6 +247,7 @@ pub struct Renderer { additive_pipeline: wgpu::RenderPipeline, celestial_pipeline: wgpu::RenderPipeline, celestial_buffer: wgpu::Buffer, + panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. border_pipeline: wgpu::RenderPipeline, border_group: wgpu::BindGroup, @@ -398,6 +400,7 @@ impl Renderer { animations: &[SpriteAnimation], hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), + panorama_faces: &panorama::Faces, ) -> Result { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); @@ -1357,6 +1360,12 @@ impl Renderer { .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); + let panorama = panorama::Panorama::new( + &device, + &queue, + config.format.remove_srgb_suffix(), + panorama_faces, + ); Ok(Self { instance, surface, @@ -1385,6 +1394,7 @@ impl Renderer { additive_pipeline, celestial_pipeline, celestial_buffer, + panorama, border_pipeline, border_group, border_uniform, @@ -1864,6 +1874,15 @@ impl Renderer { frame.block_flicker, ); let view_proj = self.view_projection(frame); + if frame.title { + self.panorama.prepare( + &self.queue, + self.config.width, + self.config.height, + frame.yaw, + frame.pitch, + ); + } let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let view = crate::camera::view_matrix(frame.yaw, frame.pitch); let sun_angle = frame.sky.sun_angle.to_radians(); @@ -2210,12 +2229,15 @@ impl Renderer { Some(f) => f.sky_end > 2.0, None => !frame.underwater, }; - if sky_visible && (frame.skybox || frame.end_sky) { + if frame.title || (sky_visible && (frame.skybox || frame.end_sky)) { if !frame.title && frame.skybox { pass.set_pipeline(&self.sky); pass.draw(0..3, 0..1); } - if celestial_vertices > 0 { + if frame.title { + self.panorama.draw(&mut pass); + pass.set_bind_group(0, &self.group, &[]); + } else if celestial_vertices > 0 { pass.set_pipeline(&self.celestial_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); diff --git a/crates/horizon-client/src/gfx/panorama.rs b/crates/horizon-client/src/gfx/panorama.rs new file mode 100644 index 000000000..d53cd4501 --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.rs @@ -0,0 +1,346 @@ +//! Vanilla 26.3's CubeMapTexture and CubeMap, separate from the pixel-filtered GUI atlas. +use crate::{Result, hud::decode}; +use glam::Mat4; +use std::path::Path; +use wgpu::util::DeviceExt; + +/// Native cube order: +X, -X, +Y, -Y, +Z, -Z (CubeMapTexture.SUFFIXES). +const FACE_ORDER: [u8; 6] = [1, 3, 5, 4, 0, 2]; + +#[derive(Debug)] +pub struct Faces { + pub size: u32, + pub pixels: Vec, +} + +impl Faces { + pub fn load(root: &Path) -> Self { + Self::try_load(root).unwrap_or_else(|error| { + log::warn!("Horizon: title panorama unavailable ({error})"); + Self { + size: 1, + pixels: [96, 110, 111, 255].repeat(6), + } + }) + } + + fn try_load(root: &Path) -> Result { + let background = root.join("assets/minecraft/textures/gui/title/background"); + let mut size = 0; + let mut pixels = Vec::new(); + for face in FACE_ORDER { + let path = background.join(format!("panorama_{face}.png")); + let (w, h, data) = decode(&path)?; + if w != h || (size != 0 && w != size) { + return Err(format!( + "{}: panorama faces must be equally sized squares", + path.display() + ) + .into()); + } + size = w; + // CubeMapTexture copies each original image with flipY=true. Keep every texel. + for row in data.chunks_exact((w * 4) as usize).rev() { + pixels.extend_from_slice(row); + } + } + Ok(Self { size, pixels }) + } +} + +fn projection(width: u32, height: u32, yaw: f32, pitch: f32) -> Mat4 { + // CubeMap.render: 85-degree FOV, near/far 0.05/10, rotationX(PI), rotateX, rotateY. + Mat4::perspective_rh( + 85.0f32.to_radians(), + width as f32 / height.max(1) as f32, + 0.05, + 10.0, + ) * Mat4::from_rotation_x(std::f32::consts::PI) + * Mat4::from_rotation_x(pitch.to_radians()) + * Mat4::from_rotation_y(yaw.to_radians()) +} + +pub(super) struct Panorama { + pipeline: wgpu::RenderPipeline, + group: wgpu::BindGroup, + uniform: wgpu::Buffer, +} + +impl Panorama { + pub(super) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + format: wgpu::TextureFormat, + faces: &Faces, + ) -> Self { + let texture = device.create_texture_with_data( + queue, + &wgpu::TextureDescriptor { + label: Some("Title panorama cube"), + size: wgpu::Extent3d { + width: faces.size, + height: faces.size, + depth_or_array_layers: 6, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + &faces.pixels, + ); + let view = texture.create_view(&wgpu::TextureViewDescriptor { + dimension: Some(wgpu::TextureViewDimension::Cube), + ..Default::default() + }); + // CubeMapTexture's blur=true metadata: linear minification and magnification, no mips. + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Title panorama linear filtering"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + ..Default::default() + }); + let uniform = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Title panorama projection"), + size: 64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Title panorama bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::VERTEX, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::Cube, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Title panorama resources"), + layout: &layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: uniform.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::TextureView(&view), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: wgpu::BindingResource::Sampler(&sampler), + }, + ], + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Title panorama shader"), + source: wgpu::ShaderSource::Wgsl(include_str!("panorama.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Title panorama layout"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Title panorama"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_panorama"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: None, + ..Default::default() + }, + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::Always), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_panorama"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + group, + uniform, + } + } + + pub(super) fn prepare( + &self, + queue: &wgpu::Queue, + width: u32, + height: u32, + yaw: f32, + pitch: f32, + ) { + queue.write_buffer( + &self.uniform, + 0, + bytemuck::cast_slice(&projection(width, height, yaw, pitch).to_cols_array()), + ); + } + + pub(super) fn draw(&self, pass: &mut wgpu::RenderPass<'_>) { + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &self.group, &[]); + pass.draw(0..36, 0..1); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::{ + fs, + sync::atomic::{AtomicU32, Ordering}, + }; + + struct Fixture(std::path::PathBuf); + impl Fixture { + fn new(size: u32) -> Self { + static NEXT: AtomicU32 = AtomicU32::new(0); + let root = std::env::temp_dir().join(format!( + "horizon-panorama-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed), + )); + let fixture = Self(root); + fs::create_dir_all(fixture.background()).unwrap(); + for face in 0..6 { + fixture.write(face, size, size); + } + fixture + } + fn background(&self) -> std::path::PathBuf { + self.0 + .join("assets/minecraft/textures/gui/title/background") + } + fn write(&self, face: u8, w: u32, h: u32) { + let file = + fs::File::create(self.background().join(format!("panorama_{face}.png"))).unwrap(); + let mut encoder = png::Encoder::new(file, w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels: Vec = (0..h) + .flat_map(|y| { + (0..w).flat_map(move |x| [face, (x % 251) as u8, (y % 253) as u8, 255]) + }) + .collect(); + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + #[test] + fn original_resolution_texels_and_vanilla_cube_orientation_are_preserved() { + let f = Fixture::new(1024); + let faces = Faces::try_load(&f.0).unwrap(); + assert_eq!(faces.size, 1024); + assert_eq!(faces.pixels.len(), 6 * 1024 * 1024 * 4); + // CubeMapTexture's actual layer suffixes, with each source row flipped vertically. + for (layer, source_face) in [1, 3, 5, 4, 0, 2].into_iter().enumerate() { + for y in 0..1024 { + for x in 0..1024 { + let at = ((layer * 1024 + y) * 1024 + x) * 4; + assert_eq!( + faces.pixels[at..at + 4], + [source_face, (x % 251) as u8, ((1023 - y) % 253) as u8, 255] + ); + } + } + } + } + + #[test] + fn placeholders_load_and_incomplete_or_mismatched_cubes_fall_back() { + let f = Fixture::new(1); + assert_eq!(Faces::try_load(&f.0).unwrap().size, 1); + f.write(5, 2, 1); + assert!( + Faces::try_load(&f.0) + .unwrap_err() + .to_string() + .contains("equally sized squares") + ); + let fallback = Faces::load(&f.0); + assert_eq!(fallback.pixels.len(), 24); + f.write(5, 2, 2); + assert!(Faces::try_load(&f.0).is_err()); + fs::remove_file(f.background().join("panorama_5.png")).unwrap(); + assert!(Faces::try_load(&f.0).is_err()); + assert_eq!(Faces::load(&f.0).size, 1); + } + + #[test] + fn cube_shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("panorama.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } + + #[test] + fn vanilla_camera_centres_the_positive_z_face_and_pitches_ten_degrees() { + let straight = projection(1920, 1080, 0.0, 0.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + assert!((straight.x / straight.w).abs() < 1e-6); + assert!((straight.y / straight.w).abs() < 1e-6); + assert!(straight.w > 0.0); + let pitched = projection(1920, 1080, 0.0, 10.0) * glam::Vec4::new(0.0, 0.0, 1.0, 1.0); + let expected_y = 10.0f32.to_radians().tan() / 42.5f32.to_radians().tan(); + assert!((pitched.y / pitched.w - expected_y).abs() < 1e-6); + } +} diff --git a/crates/horizon-client/src/gfx/panorama.wgsl b/crates/horizon-client/src/gfx/panorama.wgsl new file mode 100644 index 000000000..26c53949a --- /dev/null +++ b/crates/horizon-client/src/gfx/panorama.wgsl @@ -0,0 +1,30 @@ +// CubeMap's position-only cube and panorama.vsh/fsh: sample its untransformed direction. +struct Projection { view_proj: mat4x4 } +@group(0) @binding(0) var projection: Projection; +@group(0) @binding(1) var panorama: texture_cube; +@group(0) @binding(2) var panorama_sampler: sampler; +struct Out { + @builtin(position) clip: vec4, + @location(0) direction: vec3, +} +@vertex fn vs_panorama(@builtin(vertex_index) index: u32) -> Out { + let corners = array, 8>( + vec3(-1.0, -1.0, -1.0), vec3(1.0, -1.0, -1.0), + vec3(1.0, 1.0, -1.0), vec3(-1.0, 1.0, -1.0), + vec3(-1.0, -1.0, 1.0), vec3(1.0, -1.0, 1.0), + vec3(1.0, 1.0, 1.0), vec3(-1.0, 1.0, 1.0), + ); + let indices = array( + 4, 7, 6, 4, 6, 5, 5, 6, 2, 5, 2, 1, + 1, 2, 3, 1, 3, 0, 0, 3, 7, 0, 7, 4, + 7, 3, 2, 7, 2, 6, 0, 4, 5, 0, 5, 1, + ); + let position = corners[indices[index]]; + var out: Out; + out.clip = projection.view_proj * vec4(position, 1.0); + out.direction = position; + return out; +} +@fragment fn fs_panorama(in: Out) -> @location(0) vec4 { + return textureSample(panorama, panorama_sampler, in.direction); +} diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 6161160dd..568faa36e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -147,9 +147,7 @@ impl HudAtlas { walk(&textures.join("map"), &mut files); files.retain(|p| { let s = p.to_string_lossy(); - (!s.contains("title/background") || s.contains("panorama_")) - && !s.contains("realms") - && !s.contains("presets") + !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); let decode_one = |path: &PathBuf| -> Option<(String, u32, u32, Vec)> { let name = path @@ -166,18 +164,6 @@ impl HudAtlas { } else { pixels }; - // Title panorama faces are downsampled to 256 for the shared atlas. - if name.contains("panorama_") && w >= 512 && w == h { - let step = (w / 256) as usize; - let mut small = Vec::with_capacity(256 * 256 * 4); - for y in 0..256usize { - for x in 0..256usize { - let i = ((y * step) * w as usize + x * step) * 4; - small.extend_from_slice(&pixels[i..i + 4]); - } - } - return Some((name, 256, 256, small)); - } (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); From dacdf69293785b5728c6eaafaa430a874b79e7a4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:20:06 +0200 Subject: [PATCH 2/8] LAN: offline players get a kept generated name instead of Player (#195) Every offline Horizon player joined as Player, the LAN host's own offline profile, so the host refused every guest with "You logged in from another location". Vanilla's client defaults --username to Player + millis % 1000 and the launcher passes the account's name. Horizon now generates Player + five digits once and keeps it in horizon-player.txt next to options.txt (same name, same offline UUID, same inventory on a friend's world). --name, HORIZON_PLAYER_NAME and a signed-in account still win. tools/test_lan_lifecycle.py: two default guests join one host together, keep their names across rejoins, and a guest named Player is refused. Fixes #195 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 28 +++-- crates/horizon-client/src/game/agent.rs | 5 + crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/offline_name.rs | 122 ++++++++++++++++++++++ tools/test_lan_lifecycle.py | 101 +++++++++++++++--- 6 files changed, 237 insertions(+), 22 deletions(-) create mode 100644 crates/horizon-client/src/offline_name.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..5752d9a57 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -208,12 +208,24 @@ struct Options { offscreen: bool, /// Multiplayer: `--server HOST[:PORT]` joins at start; `--name` is the offline player name. server: Option, - player_name: String, + /// `--name`, `HORIZON_PLAYER_NAME` or the signed-in account's name; else + /// [`Options::player_name`] uses the kept offline name. + player_name: Option, /// `--dedicated`: run as a dedicated server; vanilla's server arguments /// (`--nogui`, `--port`, `--world`, `--universe`, `--initSettings`) follow. dedicated: Option>, } impl Options { + /// The name to join servers with: the one given, else the offline name kept + /// next to options.txt (created on first use). + fn player_name(&self) -> String { + self.player_name.clone().unwrap_or_else(|| { + std::env::current_dir().map_or_else( + |_| horizon_client::offline_name::generate(0), + |dir| horizon_client::offline_name::load_or_create(&dir), + ) + }) + } fn read() -> Result> { let sibling = std::env::current_exe()? .parent() @@ -246,7 +258,9 @@ impl Options { .ok() .and_then(|v| v.parse().ok()), server: None, - player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()), + player_name: std::env::var("HORIZON_PLAYER_NAME") + .ok() + .filter(|n| !n.is_empty()), dedicated: None, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); @@ -255,7 +269,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." + "Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause." ); return Ok(None); } @@ -298,7 +312,7 @@ impl Options { "--screenshot-after" => o.screenshot_after = Some(value.parse()?), "--world" => o.world = Some(value), "--server" => o.server = Some(value), - "--name" => o.player_name = value, + "--name" => o.player_name = Some(value), "--session-file" => session_file = Some(value), "--control-socket" => o.control = Some(value.into()), "--time" => o.time = Some(value.parse()?), @@ -324,7 +338,7 @@ impl Options { if let Some(path) = session_file.filter(|p| !p.is_empty()) { match horizon_client::auth::AuthSession::load(path.as_ref()) { Ok(session) => { - o.player_name = session.name.clone(); + o.player_name = Some(session.name.clone()); horizon_client::auth::set_current(session); } Err(e) => eprintln!("Horizon: not signed in: {e}"), @@ -8444,7 +8458,7 @@ impl ApplicationHandler for Game<'_> { creative, } => self.open_world(&folder, Some(&name), seed, creative)?, Action::Connect { address } => { - self.connect_server(&address, &self.options.player_name.clone())? + self.connect_server(&address, &self.options.player_name())? } Action::None => {} } @@ -9283,7 +9297,7 @@ pub fn run() -> Result<()> { _ if game.options.server.is_some() => { let (address, name) = ( game.options.server.clone().unwrap_or_default(), - game.options.player_name.clone(), + game.options.player_name(), ); game.connect_server(&address, &name)?; if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index e2b02d199..e554cd520 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -506,6 +506,11 @@ impl Game<'_> { Mode::Error { message, .. } => { json!({ "mode": "world-operation-error", "message": message }) } + Mode::Multiplayer(horizon_client::multiplayer::Screen::Disconnected { + reason, .. + }) => { + json!({ "mode": "multiplayer", "disconnected": reason }) + } Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }), } } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 567dd3a72..61c0cce0a 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -484,7 +484,7 @@ impl Game<'_> { } let name = words .get(2) - .map_or_else(|| self.options.player_name.clone(), |n| (*n).to_owned()); + .map_or_else(|| self.options.player_name(), |n| (*n).to_owned()); self.connect_server(arg(1)?, &name)?; ok() } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index cb8fec3a6..1e1aab960 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -100,6 +100,7 @@ pub mod music; pub mod nbt_path; pub mod net; pub mod nether_portal; +pub mod offline_name; pub mod options_file; pub mod options_fixes; pub mod options_horizon; diff --git a/crates/horizon-client/src/offline_name.rs b/crates/horizon-client/src/offline_name.rs new file mode 100644 index 000000000..552f15570 --- /dev/null +++ b/crates/horizon-client/src/offline_name.rs @@ -0,0 +1,122 @@ +//! The offline player name, when neither `--name`, `HORIZON_PLAYER_NAME` nor a +//! signed-in account gives one. Vanilla's client defaults `--username` to +//! `"Player" + System.currentTimeMillis() % 1000` (net.minecraft.client.main.Main) +//! and the official launcher always passes the account's name, so two players +//! rarely share one. Horizon used plain `Player` for everyone, which is also +//! the LAN host's own profile: every guest got the host's offline UUID and was +//! refused with "You logged in from another location". The generated name is +//! kept in `horizon-player.txt` next to `options.txt` so the same player gets +//! the same offline UUID (and inventory on a friend's world) every time. +use std::{fs, path::Path}; + +pub const FILE: &str = "horizon-player.txt"; +const KEY: &str = "name:"; + +/// StringUtil.isValidPlayerName, plus not empty (the login screen sends at least one character). +pub fn is_valid(name: &str) -> bool { + crate::lan::conn::valid_name(name) +} + +/// `Player` and five digits (vanilla's default has three: one shared name in a +/// thousand pairs is too many for a game that keeps it). +pub fn generate(seed: u64) -> String { + format!("Player{:05}", seed % 100_000) +} + +/// The name kept in `dir`, created on first use. A file that can't be written +/// still yields a name for this run. +pub fn load_or_create(dir: &Path) -> String { + let path = dir.join(FILE); + if let Some(name) = fs::read_to_string(&path).ok().and_then(|text| parse(&text)) { + return name; + } + let name = generate(seed()); + if let Err(e) = fs::write(&path, format!("{KEY}{name}\n")) { + log::warn!( + "Horizon: could not keep the player name in {}: {e}", + path.display() + ); + } + name +} + +fn parse(text: &str) -> Option { + text.lines() + .find_map(|line| line.trim_end_matches('\r').strip_prefix(KEY)) + .filter(|name| is_valid(name)) + .map(str::to_owned) +} + +fn seed() -> u64 { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos() as u64); + // Two players starting the game in the same millisecond still differ. + let mut x = nanos ^ u64::from(std::process::id()).rotate_left(32); + x ^= x >> 33; + x = x.wrapping_mul(0xff51_afd7_ed55_8ccd); + x ^ (x >> 33) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!( + "horizon-offline-name-{name}-{}", + std::process::id() + )); + let _ = fs::remove_dir_all(&d); + fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn generated_names_are_valid_and_never_the_hosts_profile() { + for seed in [0, 7, 99_999, 100_000, u64::MAX] { + let name = generate(seed); + assert!(is_valid(&name), "{name}"); + // The LAN host's own profile (game/chat.rs PLAYER_NAME). + assert_ne!(name, "Player"); + assert_eq!(name.len(), 11); + } + assert_eq!(generate(42), "Player00042"); + } + + #[test] + fn the_name_is_kept_and_reused() { + let d = dir("kept"); + let first = load_or_create(&d); + assert_eq!( + fs::read_to_string(d.join(FILE)).unwrap(), + format!("name:{first}\n") + ); + assert_eq!(load_or_create(&d), first); + // An edited name is used as it is. + fs::write(d.join(FILE), "name:Alex_2\r\n").unwrap(); + assert_eq!(load_or_create(&d), "Alex_2"); + let _ = fs::remove_dir_all(&d); + } + + #[test] + fn invalid_names_are_replaced() { + for text in [ + "", + "name:", + "name:has space", + "name:ThisNameIsTooLong17", + "name:été", + ] { + let d = dir("invalid"); + fs::write(d.join(FILE), text).unwrap(); + let name = load_or_create(&d); + assert!( + name.starts_with("Player") && is_valid(&name), + "{text:?} -> {name}" + ); + assert_eq!(load_or_create(&d), name); + let _ = fs::remove_dir_all(&d); + } + } +} diff --git a/tools/test_lan_lifecycle.py b/tools/test_lan_lifecycle.py index 5344e7564..1ad67d0f9 100644 --- a/tools/test_lan_lifecycle.py +++ b/tools/test_lan_lifecycle.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 -"""Check LAN shutdown when leaving a singleplayer world through the pause menu. +"""Check LAN shutdown when leaving a singleplayer world through the pause menu, +and that offline guests joining with their default names are not refused as the +host's profile (#195: everyone was "Player"). Requires a built horizon-client, prepared resources and a display on Unix: xvfb-run -a python3 tools/test_lan_lifecycle.py --client target/fast/horizon-client @@ -101,6 +103,45 @@ def scenario(endpoint, scanner): command(endpoint, 'quit') +def start_client(client, resources, home, endpoint, log, *extra): + return subprocess.Popen([ + str(client), '--resources', str(resources), '--render-distance', '2', + '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', *extra, + ], cwd=home, env=dict(os.environ, HORIZON_HOME=str(home), HORIZON_NO_AUDIO='1', + HORIZON_MENU_STYLE='classic', HORIZON_PLAYER_NAME=''), + stdout=log, stderr=subprocess.STDOUT) + + +def guest_names(endpoint, port, guests): + """Two guests with default names join together; a guest named like the host is refused.""" + names = [] + for home, guest in guests: + wait_for(guest, 'screen', lambda value: value['screen'] == 'title') + command(guest, f'connect 127.0.0.1:{port}') + wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) + kept = (home / 'horizon-player.txt').read_text() + assert kept.startswith('name:Player') and kept.strip() != 'name:Player', kept + names.append(kept.strip().removeprefix('name:')) + assert names[0] != names[1], names + status = wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 2) + assert sorted(g['name'] for g in status['guests']) == sorted(names), status + # The same home keeps its name: leave and join again as the same profile. + home, guest = guests[0] + command(guest, 'disconnect') + wait_for(endpoint, 'lan status', lambda value: len(value['guests']) == 1) + command(guest, f'connect 127.0.0.1:{port}') + wait_for(guest, 'status', lambda value: (value.get('server') or {}).get('joined')) + assert (home / 'horizon-player.txt').read_text().strip() == f'name:{names[0]}' + # A guest that really is the host's offline profile is refused, the others stay. + command(guest, 'disconnect') + command(guest, f'connect 127.0.0.1:{port} Player') + refused = wait_for(guest, 'screen', lambda value: (value.get('menu') or {}).get('disconnected')) + assert 'another location' in refused['menu']['disconnected'], refused + status = command(endpoint, 'lan status') + assert [g['name'] for g in status['guests']] == [names[1]], status + return names + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--client', type=Path, required=True) @@ -116,12 +157,7 @@ def main(): scanner.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(GROUP) + socket.inet_aton('0.0.0.0')) with (work / 'client.log').open('w+') as log: - process = subprocess.Popen([ - str(client), '--resources', str(resources), '--render-distance', '2', - '--test-terrain', '--control-socket', str(endpoint), '--timeout-seconds', '180', - ], cwd=work, env=dict(os.environ, HORIZON_HOME=str(work), HORIZON_NO_AUDIO='1', - HORIZON_MENU_STYLE='classic'), - stdout=log, stderr=subprocess.STDOUT) + process = start_client(client, resources, work, endpoint, log) try: scenario(endpoint, scanner) assert process.wait(timeout=20) == 0, 'client exited unsuccessfully' @@ -130,14 +166,51 @@ def main(): print('\n'.join(log.read().splitlines()[-20:])) raise finally: - if process.poll() is None: - process.terminate() - try: - process.wait(timeout=10) - except subprocess.TimeoutExpired: - process.kill() - process.wait(timeout=10) + stop(process) + names = guests_scenario(client, resources, work) print('LAN lifecycle passed: leaving stops hosting and discovery; reopening stays private') + print(f'LAN guests passed: default names {names[0]} and {names[1]} joined together and kept; ' + '"Player" refused as the host\'s profile') + + +def stop(process): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=10) + + +def guests_scenario(client, resources, work): + host_home = work / 'host' + homes = [work / 'guest-a', work / 'guest-b'] + processes, logs = [], [] + try: + for home in [host_home, *homes]: + home.mkdir() + log = (home / 'client.log').open('w+') + logs.append(log) + processes.append(start_client(client, resources, home, home / 'control.sock', log)) + endpoint = host_home / 'control.sock' + wait_for(endpoint, 'screen', lambda value: value['screen'] == 'title') + command(endpoint, 'open LanGuests 0 creative') + wait_for(endpoint, 'status', lambda value: value['player'] is not None + and value['pending_chunks'] == 0) + port = command(endpoint, 'lan open 0')['port'] + return guest_names(endpoint, port, [(home, home / 'control.sock') for home in homes]) + except Exception: + for log in logs: + log.seek(0) + print(f'--- {log.name}') + print('\n'.join(log.read().splitlines()[-20:])) + raise + finally: + for process in processes: + stop(process) + for log in logs: + log.close() if __name__ == '__main__': From bf7b3d140f8da83540a4f555a80e90b5efce44a9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:22:08 +0200 Subject: [PATCH 3/8] Play the player's hurt sound for every damage, by its damage effects (#144) Vanilla plays the hurt sound on the client from broadcastDamageEvent (LivingEntity.handleDamageEvent -> Player.getHurtSound, the damage type's DamageEffects sound, pitch (r - r) * 0.2 + 1). Horizon only played entity.player.hurt by hand for falls and mob hits, so sweet berry bushes (poking -> hurt_sweet_berry_bush), fire and lava (burning -> hurt_on_fire), drowning, freezing, cactus and the rest were silent. The combat port's broadcast_damage now carries its damage source (HealthEvent::DamageBroadcast, same trace line as before) and the game plays hurt_sound(effects) for it; the two hand-written plays are gone. Fixes #144 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 5 +++ crates/horizon-client/src/game.rs | 7 ++-- crates/horizon-client/src/game/combat.rs | 14 +++++++ crates/horizon-client/src/game/creatures.rs | 3 -- crates/horizon-client/src/health.rs | 41 ++++++++++++++++++++- 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 6705235ae..54bd3bda8 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -617,6 +617,11 @@ impl Audio { let seed = self.random.next_long(); self.play_seeded(event, at, volume, pitch, seed); } + /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the + /// client (the entity's own random there, never the server's world random). + pub fn hurt_pitch(&mut self) -> f32 { + (self.random.next_float() - self.random.next_float()) * 0.2 + 1.0 + } /// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound. pub fn play_button_click(&mut self) { self.play_instance( diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..5da5b7654 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2942,9 +2942,10 @@ impl Game<'_> { b.notify_written(level, ticks, position, level_flags::UPDATE_ALL) }); } - MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => { - self.audio - .play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0); + MotionEvent::Health(horizon_client::health::HealthEvent::DamageBroadcast { + source, + }) => { + self.player_hurt_sound(source, feet); } MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity), MotionEvent::EnterBlock { state } => self.trigger_enter_block(state), diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 73c6b7fc0..14a1133e0 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -54,6 +54,20 @@ impl Game<'_> { .push((damage_type.to_owned(), (mob, name))); } } + /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the + /// source's `DamageEffects` (`Player.getHurtSound`). + pub(super) fn player_hurt_sound( + &mut self, + source: horizon_world::damage_source::DamageTypeId, + at: [f64; 3], + ) { + let Some(d) = self.motion.health.damage.definition(source) else { + return; + }; + let sound = horizon_client::health::hurt_sound(&d.effects); + let pitch = self.audio.hurt_pitch(); + self.audio.play(sound, Some(at), 1.0, pitch); + } /// `CombatTracker.recordDamage` for the motion events of this tick. pub(super) fn record_combat(&mut self, events: &[MotionEvent]) { self.recheck_combat(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8c749b704..ee7f2c111 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1352,9 +1352,6 @@ impl Game<'_> { (player.velocity.y / 2.0 + 0.4).min(0.4), player.velocity.z / 2.0 + dz / l * 0.4, ); - let at = [player.position.x, player.position.y, player.position.z]; - self.audio - .play("minecraft:entity.player.hurt", Some(at), 1.0, 1.0); self.hurt_armor(amount); self.thorns(from); } diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 46b4f4542..29cba4610 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -76,6 +76,18 @@ impl HealthResources { .expect("validated landing source") } } +/// `DamageEffects.sound()` by its serialized id: what `Player.getHurtSound` +/// plays for a damage type's `effects` (unknown ids fall back to `hurt`, the codec default). +pub fn hurt_sound(effects: &str) -> &'static str { + match effects { + "drowning" => "minecraft:entity.player.hurt_drown", + "burning" => "minecraft:entity.player.hurt_on_fire", + "poking" => "minecraft:entity.player.hurt_sweet_berry_bush", + "freezing" => "minecraft:entity.player.hurt_freeze", + // HURT and THORNS (both SoundEvents.PLAYER_HURT). + _ => "minecraft:entity.player.hurt", + } +} #[derive(Clone, Copy, Debug)] pub enum HealthEvent { StarvationDamage(f32), @@ -97,6 +109,11 @@ pub enum HealthEvent { amount: f32, }, Phase(&'static str), + /// `ServerLevel.broadcastDamageEvent`: the client's + /// `LivingEntity.handleDamageEvent` plays the source's hurt sound. + DamageBroadcast { + source: DamageTypeId, + }, Criterion { original: f32, amount: f32, @@ -119,6 +136,7 @@ impl HealthEvent { format!("record-damage {:08x}", amount.to_bits()) } Self::Phase(name) => name.into(), + Self::DamageBroadcast { .. } => "broadcast-damage".into(), Self::Criterion { .. } => "hurt-criterion".into(), } } @@ -559,7 +577,10 @@ impl HurtWorld for Environment<'_> { Ok(()) } fn broadcast_damage(&mut self, _: &mut State) -> io::Result<()> { - self.phase("broadcast-damage") + self.event(HealthEvent::DamageBroadcast { + source: self.source.type_id(), + }); + Ok(()) } fn mark_hurt(&mut self, _: &mut State) -> io::Result<()> { *self.sync_velocity = true; @@ -655,3 +676,21 @@ impl ServerPlayerHurtWorld for Environment<'_> { Ok(true) } } + +#[cfg(test)] +mod tests { + #[test] + fn hurt_sounds_follow_damage_effects() { + // DamageEffects: HURT, THORNS, DROWNING, BURNING, POKING, FREEZING. + for (effects, sound) in [ + ("hurt", "minecraft:entity.player.hurt"), + ("thorns", "minecraft:entity.player.hurt"), + ("drowning", "minecraft:entity.player.hurt_drown"), + ("burning", "minecraft:entity.player.hurt_on_fire"), + ("poking", "minecraft:entity.player.hurt_sweet_berry_bush"), + ("freezing", "minecraft:entity.player.hurt_freeze"), + ] { + assert_eq!(super::hurt_sound(effects), sound, "{effects}"); + } + } +} From aec497c94b088c31f48fbd5657d6b4077a74db76 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:31:19 +0200 Subject: [PATCH 4/8] Items, orbs and arrows fly to whoever picks them up (#142) Vanilla's ClientPacketListener.handleTakeItemEntity adds an ItemPickupParticle for every take: the taken entity's render state (extracted at partial tick 1) moves to the collector's x, (y + eyeY) / 2, z along ((life + partial) / 3)^2 over three ticks, the target lerped between ticks (ItemPickupParticleGroup). Horizon removed taken entities at once. game/pickups.rs keeps those particles (joining the group at the end of the particle tick, as ParticleEngine.tick does) and the item, orb and arrow renderers draw them frozen at the moving position. Takes by the player (items, orbs, arrows), by mobs (allays, villagers, piglins, sulfur cubes, raid banners), by LAN guests on the host, and ClientboundTakeItemEntity on a LAN guest or server all add one. Fixes #142 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 39 +++- crates/horizon-client/src/game/allays.rs | 5 + crates/horizon-client/src/game/creatures.rs | 23 ++- crates/horizon-client/src/game/item_draw.rs | 20 +- crates/horizon-client/src/game/lan_actions.rs | 21 +- crates/horizon-client/src/game/pickups.rs | 185 ++++++++++++++++++ crates/horizon-client/src/game/piglins.rs | 5 + crates/horizon-client/src/game/raids.rs | 9 + crates/horizon-client/src/game/remote.rs | 16 ++ crates/horizon-client/src/game/render_tick.rs | 1 + .../horizon-client/src/game/sulfur_cubes.rs | 5 + crates/horizon-client/src/game/villagers.rs | 8 + 12 files changed, 324 insertions(+), 13 deletions(-) create mode 100644 crates/horizon-client/src/game/pickups.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0d9c394e4..6b021757e 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -81,6 +81,7 @@ mod paintings; mod passengers; mod persist; mod perspective; +mod pickups; mod piglins; mod postprocess; mod potions; @@ -720,6 +721,8 @@ struct Game<'a> { dropped: Vec, next_entity: u32, particles: horizon_client::particles::ParticleEngine, + /// `ItemPickupParticle`s: taken items, orbs and arrows flying to their collector. + pickups: pickups::Pickups, /// Sign text being edited (`SignEditScreen`). sign_edit: Option, /// An open book, book and quill or lectern screen. @@ -1401,6 +1404,10 @@ impl Game<'_> { match self.give(item.stack.clone()) { None => { self.stats.add("picked_up", &kind, before as i32); + self.add_pickup( + pickups::Taken::Item(Box::new(item)), + pickups::Collector::Player, + ); let pitch = ((self.world.random.next_float() - self.world.random.next_float()) * 0.7 @@ -1414,6 +1421,10 @@ impl Game<'_> { if rest.count < before { self.stats .add("picked_up", &kind, (before - rest.count) as i32); + self.add_pickup( + pickups::Taken::Item(Box::new(item.clone())), + pickups::Collector::Player, + ); self.audio .play("minecraft:entity.item.pickup", Some(feet), 0.2, 1.0); } @@ -4924,16 +4935,25 @@ impl Game<'_> { ); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - for o in &self.orbs { - let p = glam::DVec3::new( + let live = self.orbs.iter().map(|o| { + let at = [ o.previous.x + (o.position.x - o.previous.x) * alpha, - o.previous.y + (o.position.y - o.previous.y) * alpha + 0.1, + o.previous.y + (o.position.y - o.previous.y) * alpha, o.previous.z + (o.position.z - o.previous.z) * alpha, - ) - camera; + ]; + (o, at, alpha as f32) + }); + // ItemPickupParticle: the render state extracted at partial tick 1. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + pickups::Taken::Orb(o) => Some((&**o, pickups::position(p, alpha), 1.0)), + _ => None, + }); + for (o, at, partial) in live.chain(taken) { + let p = glam::DVec3::new(at[0], at[1] + 0.1, at[2]) - camera; let icon = o.icon(); let (du, dv) = ((r.u1 - r.u0) / 4.0, (r.v1 - r.v0) / 4.0); let (u0, v0) = (r.u0 + (icon % 4) as f32 * du, r.v0 + (icon / 4) as f32 * dv); - let t = (o.age as f32 + alpha as f32) / 2.0; + let t = (o.age as f32 + partial) / 2.0; let red = ((t.sin() + 1.0) * 0.5 * 255.0) as u32; let blue = (((t + 4.188_79).sin() + 1.0) * 0.1 * 255.0) as u32; let color = 0x8000_0000 | blue << 16 | 255 << 8 | red; @@ -5693,6 +5713,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.experience = Experience { level: self.level.xp_level, @@ -5844,6 +5865,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.mining = None; self.travelling = Some((player, destination)); @@ -5994,6 +6016,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.screen = Screen::Playing; if let Some(r) = self.renderer.as_mut() { r.clear_sections(); @@ -6689,6 +6712,7 @@ impl Game<'_> { let mut orbs = std::mem::take(&mut self.orbs); orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); let mut gained = 0; + let mut taken = Vec::new(); if let Some((min, max)) = bounds { orbs.retain(|o| { let touching = o.position.x + 0.25 > min[0] @@ -6701,12 +6725,16 @@ impl Game<'_> { // ExperienceOrb.playerTouch: one orb every 2 ticks. self.xp_delay = 2; gained += o.value; + taken.push(o.clone()); return false; } true }); } self.orbs = orbs; + for o in taken { + self.add_pickup(pickups::Taken::Orb(Box::new(o)), pickups::Collector::Player); + } if gained > 0 { gained = self.mending(gained); } @@ -9097,6 +9125,7 @@ pub fn run() -> Result<()> { dropped: Vec::new(), next_entity: 0, particles, + pickups: Default::default(), sign_edit: None, book: None, lectern_pulses: Vec::new(), diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index c948663b1..a2a5842b5 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -54,6 +54,11 @@ impl Game<'_> { .inflate(horizon_core::geometry::Vec3::new(1.0, 1.0, 1.0)); if b.contains(e.position) { let take = (max - carried).min(e.stack.count as i32); + let (item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(item)), + super::pickups::Collector::Mob(id), + ); self.mobs[i].extra.ints[1] += take; let e = &mut self.dropped[j]; e.stack.count -= take as u32; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8c749b704..7e2d20ecb 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1434,6 +1434,7 @@ impl Game<'_> { // Player.hasInfiniteMaterials. let creative = self.creative; let mut projectiles = std::mem::take(&mut self.creatures.projectiles); + let mut picked = Vec::new(); projectiles.retain(|shot| { let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else { return true; @@ -1461,10 +1462,17 @@ impl Game<'_> { 0.2, pitch, ); + picked.push(shot.clone()); } !taken }); self.creatures.projectiles = projectiles; + for shot in picked { + self.add_pickup( + super::pickups::Taken::Arrow(Box::new(shot)), + super::pickups::Collector::Player, + ); + } } fn tick_projectiles(&mut self) -> Result<()> { @@ -2672,12 +2680,21 @@ impl Game<'_> { ); let right = forward.cross(glam::Vec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - for a in &self.creatures.projectiles { - let p = glam::DVec3::new( + let live = self.creatures.projectiles.iter().map(|a| { + let at = [ a.previous.x + (a.position.x - a.previous.x) * alpha, a.previous.y + (a.position.y - a.previous.y) * alpha, a.previous.z + (a.position.z - a.previous.z) * alpha, - ) - camera; + ]; + (a, at) + }); + // ItemPickupParticle: a picked-up arrow flying to its collector. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + super::pickups::Taken::Arrow(a) => Some((&**a, super::pickups::position(p, alpha))), + _ => None, + }); + for (a, at) in live.chain(taken) { + let p = glam::DVec3::from_array(at) - camera; let c = p.as_vec3(); let light = self.world.light( a.position.x.floor() as i32, diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index a30a02127..72dd7ea59 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -310,13 +310,25 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - for item in &self.dropped { + let live = self.dropped.iter().map(|item| { let (p, q) = (item.previous, item.position); - let pos = glam::DVec3::new( + let at = [ p.x + (q.x - p.x) * alpha, p.y + (q.y - p.y) * alpha, p.z + (q.z - p.z) * alpha, - ) - camera; + ]; + (item, at, alpha as f32) + }); + // ItemPickupParticle: the render state extracted at partial tick 1. + let taken = self.pickups.live.iter().filter_map(|p| match &p.taken { + super::pickups::Taken::Item(item) => { + Some((&**item, super::pickups::position(p, alpha), 1.0)) + } + _ => None, + }); + for (item, at, partial) in live.chain(taken) { + let q = item.position; + let pos = glam::DVec3::from_array(at) - camera; if pos.length_squared() > 64.0 * 64.0 { continue; } @@ -331,7 +343,7 @@ impl Game<'_> { if state.is_empty() { continue; } - let age = item.age as f32 + alpha as f32; + let age = item.age as f32 + partial; let (lo, _) = state.bounding_box(); let min_offset_y = -lo.y + 0.0625; let bob = (age / 10.0 + item.bob_offset).sin() * 0.1 + 0.1; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 577bc5777..293afdcdd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -748,10 +748,12 @@ impl Game<'_> { let rest = self.as_guest(host, conn, |g| g.give(stack)).flatten(); match rest { None => { - self.dropped.remove(i); + let item = self.dropped.remove(i); + self.guest_pickup(host, id, item); taken.push((item_id, before)); } Some(rest) if rest.count < before => { + self.guest_pickup(host, id, self.dropped[i].clone()); self.dropped[i].stack = rest; taken.push((item_id, before - self.dropped[i].stack.count)); } @@ -765,6 +767,23 @@ impl Game<'_> { } } + /// The host's own `ItemPickupParticle` toward the guest's model. + fn guest_pickup( + &mut self, + host: &LanHost, + id: i32, + item: horizon_client::entities::ItemEntity, + ) { + use super::pickups::{Collector, Taken, guest_target}; + if let Some(target) = guest_target(host, id as u32) { + self.add_pickup_toward( + Taken::Item(Box::new(item)), + Collector::Guest(id as u32), + target, + ); + } + } + /// Positional sounds and level events of the tick, for the guests. pub(super) fn lan_broadcast_effects(&mut self, host: &mut LanHost) { let sounds = self.audio.capture.take().unwrap_or_default(); diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs new file mode 100644 index 000000000..2729dc98f --- /dev/null +++ b/crates/horizon-client/src/game/pickups.rs @@ -0,0 +1,185 @@ +//! `ItemPickupParticle`: a taken item entity, experience orb or arrow flies +//! into whoever took it over three ticks (`ClientPacketListener.handleTakeItemEntity` +//! adds one for every `ClientboundTakeItemEntityPacket`), drawn with the render +//! state it had when it was taken (`extractEntity(from, 1.0F)`). +use super::Game; +use horizon_client::{ + entities::{ExperienceOrb, ItemEntity}, + projectiles::Projectile, +}; + +/// `ItemPickupParticle.LIFE_TIME`. +const LIFE_TIME: u32 = 3; + +/// The taken entity, as it was when taken. +pub(super) enum Taken { + Item(Box), + Orb(Box), + Arrow(Box), +} +impl Taken { + /// The render state's position: the entity's at partial tick 1. + fn position(&self) -> [f64; 3] { + let p = match self { + Taken::Item(i) => i.position, + Taken::Orb(o) => o.position, + Taken::Arrow(a) => a.position, + }; + [p.x, p.y, p.z] + } +} + +/// Whoever took it: the particle's `target`. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(super) enum Collector { + Player, + /// A mob, or another player on a server (both kept as mobs here). + Mob(u32), + /// A LAN guest, by entity id (the host draws it as a model). + Guest(u32), +} + +pub(super) struct Pickup { + pub taken: Taken, + collector: Collector, + life: u32, + target: [f64; 3], + target_old: [f64; 3], +} + +/// `ParticleEngine`'s ITEM_PICKUP group and the particles waiting to join it. +#[derive(Default)] +pub(super) struct Pickups { + pub live: Vec, + added: Vec, +} +impl Pickups { + pub fn clear(&mut self) { + self.live.clear(); + self.added.clear(); + } +} + +/// `ItemPickupParticleGroup.ParticleInstance.fromParticle`: the position at +/// `partial`, from the taken entity's to the collector's (lerped between ticks) +/// along the square of the particle's age. +pub(super) fn position(p: &Pickup, partial: f64) -> [f64; 3] { + let time = (p.life as f32 + partial as f32) / LIFE_TIME as f32; + let time = f64::from(time * time); + let from = p.taken.position(); + std::array::from_fn(|i| { + let target = p.target_old[i] + partial * (p.target[i] - p.target_old[i]); + from[i] + time * (target - from[i]) + }) +} + +/// A LAN guest's target, from the model the host draws for it. +pub(super) fn guest_target(host: &super::lan::LanHost, id: u32) -> Option<[f64; 3]> { + let m = host.models.values().find(|m| m.id == id)?; + let (p, eye) = (m.position, m.eye_height()); + Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z]) +} + +impl Game<'_> { + /// `ItemPickupParticle.updatePosition`: the collector's x and z, halfway up to its eyes. + fn collector_target(&self, collector: Collector) -> Option<[f64; 3]> { + let (p, eye) = match collector { + Collector::Player => { + let p = self.player.as_ref()?; + (p.position, f64::from(p.dimensions.eye_height)) + } + Collector::Mob(id) => { + let m = self.mobs.iter().find(|m| m.id == id)?; + (m.position, m.eye_height()) + } + Collector::Guest(id) => { + return guest_target(self.lan.as_ref()?, id); + } + }; + Some([p.x, (p.y + (p.y + eye)) / 2.0, p.z]) + } + /// `handleTakeItemEntity`: `particleEngine.add(new ItemPickupParticle(...))` when the + /// collector is known; it joins the group at the end of the next particle tick. + pub(super) fn add_pickup(&mut self, taken: Taken, collector: Collector) { + if let Some(target) = self.collector_target(collector) { + self.add_pickup_toward(taken, collector, target); + } + } + /// [`Self::add_pickup`] with the collector's first target given (a LAN + /// guest's model while the host is taken out for its tick). + pub(super) fn add_pickup_toward( + &mut self, + taken: Taken, + collector: Collector, + target: [f64; 3], + ) { + self.pickups.added.push(Pickup { + taken, + collector, + life: 0, + target, + target_old: target, + }); + } + /// `ParticleEngine.tick` for the ITEM_PICKUP group: age (removed at + /// `LIFE_TIME`), follow the collector, then let the new particles in. + pub(super) fn tick_pickups(&mut self) { + let mut live = std::mem::take(&mut self.pickups.live); + live.retain_mut(|p| { + p.life += 1; + if p.life == LIFE_TIME { + return false; + } + p.target_old = p.target; + if let Some(t) = self.collector_target(p.collector) { + p.target = t; + } + true + }); + live.append(&mut self.pickups.added); + self.pickups.live = live; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn orb_at(x: f64, y: f64, z: f64) -> Taken { + let at = horizon_core::geometry::Vec3::new(x, y, z); + Taken::Orb(Box::new(ExperienceOrb { + position: at, + previous: at, + velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0), + value: 1, + age: 0, + on_ground: false, + })) + } + + #[test] + fn flies_along_the_square_of_its_age_to_the_moving_target() { + let mut p = Pickup { + taken: orb_at(0.0, 64.0, 0.0), + collector: Collector::Player, + life: 0, + target: [3.0, 65.0, 0.0], + target_old: [3.0, 65.0, 0.0], + }; + // Added this tick: still at the orb. + assert_eq!(position(&p, 0.0), [0.0, 64.0, 0.0]); + // Halfway through the first tick: (0.5 / 3)^2 of the way. + let t = (0.5f32 / 3.0) * (0.5 / 3.0); + let mid = position(&p, 0.5); + assert!((mid[0] - 3.0 * f64::from(t)).abs() < 1e-9, "{mid:?}"); + // Last tick before removal, the target moved: lerped between its ticks. + p.life = 2; + p.target_old = [3.0, 65.0, 0.0]; + p.target = [4.0, 65.0, 0.0]; + let end = position(&p, 1.0); + assert!( + (end[0] - 4.0).abs() < 1e-9 && (end[1] - 65.0).abs() < 1e-9, + "{end:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index c51941d02..3515b380b 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -64,6 +64,11 @@ impl Game<'_> { } // Nuggets come whole, anything else one at a time. let item = e.stack.item.clone(); + let (taken_item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(taken_item)), + super::pickups::Collector::Mob(id), + ); let taken = if &*item == "minecraft:gold_nugget" { self.dropped.remove(j).stack.count } else { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index ecb173822..1f1fa3507 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -770,6 +770,7 @@ impl Game<'_> { .map(|(i, e)| (i, e.position)) .collect(); let mut taken: Vec = Vec::new(); + let mut collectors: Vec<(usize, u32)> = Vec::new(); let mut recruit: Vec<(i32, Vec3)> = Vec::new(); let mut joins: Vec<(u32, i32, f32)> = Vec::new(); let mut new_leaders: Vec<(i32, i32, u32)> = Vec::new(); @@ -868,6 +869,7 @@ impl Game<'_> { if p.distance_squared(position) < 1.414 * 1.414 { // pickUpItem: the banner becomes the wave's leader. taken.push(*i); + collectors.push((*i, m.id)); leaders.insert((id, s.wave)); new_leaders.push((id, s.wave, m.id)); s.banner_at = None; @@ -878,6 +880,13 @@ impl Game<'_> { } } } + for (i, mob) in collectors { + let item = self.dropped[i].clone(); + self.add_pickup( + super::pickups::Taken::Item(Box::new(item)), + super::pickups::Collector::Mob(mob), + ); + } taken.sort_unstable(); for i in taken.into_iter().rev() { self.dropped.remove(i); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index bafb71f9e..7156f37c6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -186,6 +186,7 @@ impl Game<'_> { self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.orbs.clear(); self.falling.clear(); self.travelling = None; @@ -278,6 +279,7 @@ impl Game<'_> { self.mobs.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); self.score.board = Default::default(); self.tab_list = Default::default(); self.border = Default::default(); @@ -469,6 +471,7 @@ impl Game<'_> { self.mobs.clear(); self.dropped.clear(); self.particles.clear(); + self.pickups.clear(); if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); @@ -982,6 +985,19 @@ impl Game<'_> { self.audio .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } + // ItemPickupParticle toward the collector (this player, another one or a mob). + if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() { + let collector = if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) + { + super::pickups::Collector::Player + } else { + super::pickups::Collector::Mob(p.player as u32) + }; + self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector); + } self.remove_entity(p.item); } C::HurtAnimation(p) => { diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4c916e773..46255667a 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -331,6 +331,7 @@ impl Game<'_> { .map(|p| ([p.position.x, p.position.y, p.position.z], p.velocity.y)), }; self.particles.tick(&level); + self.tick_pickups(); for (name, at, volume, pitch) in std::mem::take(&mut self.particles.sounds) { self.audio.play(name, Some(at), volume, pitch); } diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 5a8ae361f..4606f6859 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -126,6 +126,11 @@ impl Game<'_> { continue; } let item = e.stack.item.clone(); + let (taken_item, id) = (e.clone(), self.mobs[i].id); + self.add_pickup( + super::pickups::Taken::Item(Box::new(taken_item)), + super::pickups::Collector::Mob(id), + ); let e = &mut self.dropped[j]; e.stack.count -= 1; if e.stack.count == 0 { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 0d547c0b0..72fa2839a 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -293,7 +293,15 @@ impl Game<'_> { j += 1; continue; } + let before = self.dropped[j].clone(); let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max); + if rest.as_ref().is_none_or(|r| r.count < before.stack.count) { + let id = self.mobs[i].id; + self.add_pickup( + super::pickups::Taken::Item(Box::new(before)), + super::pickups::Collector::Mob(id), + ); + } match rest { None => { self.dropped.remove(j); From a3fcacb212f4cc7247c74f177eef183af9baa0b6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 00:32:42 +0200 Subject: [PATCH 5/8] Website: the new favicon reaches browsers at once, and /favicon.ico exists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The icon files kept their names while the server lets browsers cache /favicon* for a week, so visitors still saw the old mark. The pages now link each icon with its content hash (?v=…), and the build writes /favicon.ico (the 32-pixel PNG in an ICO container) for browsers that ask for it on their own. Co-Authored-By: Claude Opus 5.5 --- website/build.mjs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/website/build.mjs b/website/build.mjs index 19451900e..6163d6307 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -122,6 +122,28 @@ await mkdir(join(dist, "assets"), { recursive: true }); await cp(join(site, "public"), dist, { recursive: true }); await cp(join(site, "LEGAL.md"), join(dist, "LEGAL.md")); +// The icons keep their names (browsers and other sites ask for /favicon.svg and the +// rest), so the pages link them with their content's hash: a new mark reaches everyone +// at once instead of after the week the server lets browsers keep the old one. +const iconVersions = {}; +for (const icon of ["favicon.svg", "favicon-32.png", "apple-touch-icon.png"]) { + iconVersions[icon] = fingerprint(await readFile(join(site, "public", icon))); +} +// /favicon.ico, which browsers request on their own: the 32-pixel PNG in an ICO +// container (one image entry; ICO has held PNG data since Windows Vista). +const png32 = await readFile(join(site, "public", "favicon-32.png")); +const ico = Buffer.alloc(22); +ico.writeUInt16LE(0, 0); // reserved +ico.writeUInt16LE(1, 2); // type: icon +ico.writeUInt16LE(1, 4); // one image +ico.writeUInt8(32, 6); // width +ico.writeUInt8(32, 7); // height +ico.writeUInt16LE(1, 10); // colour planes +ico.writeUInt16LE(32, 12); // bits per pixel +ico.writeUInt32LE(png32.length, 14); +ico.writeUInt32LE(22, 18); // the image follows the header and its entry +await writeFile(join(dist, "favicon.ico"), Buffer.concat([ico, png32])); + // The page's modules, fingerprinted; each import of a shared module is rewritten to its name. const names = {}; const rewrite = (code) => code.replace(/"\.\/(\w+\.js)"/g, (all, file) => (names[file] ? `"./${names[file]}"` : all)); @@ -184,6 +206,7 @@ for (const page of ["index.html", "404.html"]) { if (!(key in values)) throw new Error(`${page}: unknown placeholder ${all}`); return values[key]; }); + html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`); await writeFile(join(dist, page), html); } From 86e0e122f4f4c7f864ad2e8206374dafc824371d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:01:26 +0200 Subject: [PATCH 6/8] Release train: ship every settled player-facing change, no 3-hour gap Ludovic wants releases as often as changes land. A kind now releases when player-facing pull requests merged since its last release and the newest of them merged 15 minutes ago (a burst of merges becomes one release), or the oldest an hour ago when merges never pause; release-now still ships at once. There is no minimum time between releases. The scheduled checks run every 10 minutes (game at :02, launcher at :07) so a settled release goes out without another merge. Release titles keep proper nouns (Horizon's mark, Microsoft, LAN, ...) when they lowercase the clauses after the first. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 7 ++++--- .github/workflows/release.yml | 13 +++++++------ docs/release-flow.md | 14 ++++++++------ tests/test_release_train.py | 32 ++++++++++++++++++------------- tools/release_train.py | 35 ++++++++++++++++++++-------------- 5 files changed, 59 insertions(+), 42 deletions(-) diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index d41b38092..60d0ba5c1 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,7 +1,8 @@ name: launcher # Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a # push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme), -# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game. +# every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as +# for the game. # A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull # request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits. # Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases. @@ -17,7 +18,7 @@ on: - 'crates/horizon-theme/**' - '.github/workflows/launcher.yml' schedule: - - cron: '47 * * * *' + - cron: '7-59/10 * * * *' workflow_dispatch: inputs: dry_run: @@ -25,7 +26,7 @@ on: type: boolean default: true force: - description: Release even without launcher changes, within the cooldown or while paused + description: Release even without launcher changes, before merges settle or while paused type: boolean default: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 4b8444176..0ffa29d26 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,8 +1,9 @@ name: release -# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release -# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release -# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at -# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them. +# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a +# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides: +# a release when pull requests merged since the last one changed what players run and the newest merged 15 minutes +# ago (the oldest an hour ago, if merges never pause), or at once for a pull request labelled release-now. +# RELEASES_PAUSED=1 (repository variable) stops them. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then # publishes vYYYY.MM.DD[.N] with notes from the merged pull requests. @@ -14,7 +15,7 @@ on: types: [completed] branches: [main] schedule: - - cron: '17 * * * *' + - cron: '2-59/10 * * * *' workflow_dispatch: inputs: dry_run: @@ -22,7 +23,7 @@ on: type: boolean default: true force: - description: Release even without player-facing changes, within the cooldown or while paused + description: Release even without player-facing changes, before merges settle or while paused type: boolean default: false permissions: diff --git a/docs/release-flow.md b/docs/release-flow.md index a9bfc166d..4a8951296 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -73,7 +73,7 @@ blocks a fork's pull request; the maintainer decides whether to run it. ## Game releases `.github/workflows/release.yml` releases the game by itself. It starts after every green `checks` run of a push -to main, every hour at :17 (so a release the cooldown held goes out without another merge), and by hand. +to main, every 10 minutes (so a release waiting for merges to settle goes out without another merge), and by hand. ```mermaid flowchart LR @@ -83,7 +83,7 @@ flowchart LR main --> mainchecks{"checks on main"} mainchecks -- green --> decide{"decide
tools/release_train.py"} cron(["every hour :17"]) --> decide - decide -- "player-facing PRs, 3 h since the last release,
or release-now" --> build + decide -- "player-facing PRs settled 15 min
(or waiting 1 h), or release-now" --> build decide -- otherwise --> wait(["wait"]) subgraph build["build, in parallel"] linux["Linux x86_64
GitHub ubuntu-22.04"] @@ -104,8 +104,10 @@ commits) since the last **published** game release: `xtask/`, `packaging/`, `Cargo.toml`, `Cargo.lock`, `research-lock.json`, or an exporter `horizon-prepare` compiles (the `mods/horizon/src/test/java/dev/horizonlab/parity/*.java` files its sources name). Markdown never counts. -- It releases when at least one pull request counts and the last game release is at least 3 hours old. -- A pull request labelled `release-now` (a crash or a blocker) releases at once, cooldown or not. +- It releases when at least one pull request counts and the newest of them merged at least 15 minutes ago, so a burst + of merges becomes one release; if merges never pause, it releases once the oldest has waited an hour. There is no + minimum time between releases: every settled player-facing change ships. +- A pull request labelled `release-now` (a crash or a blocker) releases at once. - A pull request labelled `skip-release` (work players don't see) doesn't count and isn't listed in the notes. - One release at a time (concurrency group `game-release`); a run that finds nothing new does nothing. - A scheduled or hand-started run releases main's newest commit whose `checks` passed; after `checks`, the commit @@ -116,7 +118,7 @@ commits) since the last **published** game release: | Label | Effect | | --- | --- | | `feature` | Listed under **New** (Kira pings the releases role); makes the next launcher release a minor one | -| `release-now` | Releases as soon as main's checks pass, without the cooldown | +| `release-now` | Releases as soon as main's checks pass, without waiting for merges to settle | | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | @@ -193,7 +195,7 @@ and by hand; pushes to `launcher` and `launcher-*` branches only build. - `tools/release_train.py decide --kind launcher` counts the pull requests merged since the last published launcher release that changed those paths (not `launcher/links.json`, which the launcher reads from main, nor - tests or Markdown), with the same 3-hour cooldown, `release-now`, `skip-release` and `RELEASES_PAUSED`. + tests or Markdown), with the same settling rule (15 minutes, at most an hour), `release-now`, `skip-release` and `RELEASES_PAUSED`. - The tag is `launcher-vX.Y.Z`: the patch after the last launcher tag, or the next minor (`X.Y+1.0`) when one of those pull requests is labelled `feature`. - No version-bump commits: the build gets the version in `HORIZON_LAUNCHER_VERSION`, which diff --git a/tests/test_release_train.py b/tests/test_release_train.py index 17414abbd..fef887f3c 100644 --- a/tests/test_release_train.py +++ b/tests/test_release_train.py @@ -8,9 +8,10 @@ from tools import release_train as train NOW = dt.datetime(2026, 10, 15, 12, 0, tzinfo=dt.timezone.utc) -def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111"): +def pr(number, title="Fix a thing", labels=(), paths=("crates/horizon-client/src/game.rs",), issues=(), author="ludovic111", + merged=dt.timedelta(hours=9)): return {"number": number, "title": title, "labels": list(labels), "paths": list(paths), "issues": list(issues), - "author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}"} + "author": author, "url": f"https://github.com/ludovic111/horizon/pull/{number}", "merged_at": NOW - merged} class ReleaseTrainTests(unittest.TestCase): @@ -47,17 +48,19 @@ class ReleaseTrainTests(unittest.TestCase): self.assertEqual(train.next_launcher_tag(tags, minor=True), "launcher-v0.2.0") def test_decision(self): - hour = dt.timedelta(hours=1) - decide = lambda prs, age, **kw: train.decision("game", prs, NOW - age, NOW, **kw)[0] - self.assertTrue(decide([pr(1)], 4 * hour)) - self.assertFalse(decide([pr(1)], 2 * hour), "within the cooldown") - self.assertTrue(decide([pr(1, labels=["release-now"])], 0.1 * hour)) - self.assertFalse(decide([pr(1, paths=[])], 9 * hour), "nothing players run") - self.assertFalse(decide([pr(1, labels=["skip-release"])], 9 * hour)) - self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])], 9 * hour)) - self.assertFalse(decide([pr(1)], 9 * hour, paused=True)) - self.assertTrue(decide([], 0.1 * hour, paused=True, force=True)) - self.assertTrue(train.decision("game", [pr(1)], None, NOW)[0], "the first release") + minute = dt.timedelta(minutes=1) + decide = lambda prs, **kw: train.decision("game", prs, NOW, **kw)[0] + self.assertTrue(decide([pr(1, merged=16 * minute)]), "settled for the debounce") + self.assertFalse(decide([pr(1, merged=5 * minute)]), "merged moments ago") + self.assertFalse(decide([pr(1, merged=40 * minute), pr(2, merged=5 * minute)]), "a burst still merging") + self.assertTrue(decide([pr(1, merged=61 * minute), pr(2, merged=2 * minute)]), "merges that never pause still ship") + self.assertTrue(decide([pr(1, labels=["release-now"], merged=minute)])) + self.assertFalse(decide([pr(1, paths=[])]), "nothing players run") + self.assertFalse(decide([pr(1, labels=["skip-release"])])) + self.assertFalse(decide([pr(1, labels=["release-now", "skip-release"])])) + self.assertFalse(decide([pr(1, merged=5 * minute), pr(2, labels=["skip-release"], merged=minute)]), "the settled one waits for nothing") + self.assertFalse(decide([pr(1)], paused=True)) + self.assertTrue(decide([], paused=True, force=True)) def test_notes(self): prs = [pr(5, "Nether portals: vanilla timing and linking (fixes #94)", issues=[94]), @@ -73,6 +76,9 @@ class ReleaseTrainTests(unittest.TestCase): self.assertNotIn("#8", body) self.assertIn("Thanks to @cosmic.", body) self.assertLess(body.index("### New"), body.index("### Fixed")) + title, _ = train.notes("game", "v2026.10.15.2", [pr(9, "Horizon's mark", labels=["feature"]), + pr(10, "Game menus", labels=["feature"])], []) + self.assertEqual(title, "Horizon 2026.10.15.2: Game menus, Horizon's mark", "proper nouns keep their capital") def test_a_long_release_is_named_after_its_first_titles(self): prs = [pr(n, f"Change number {n} with a fairly long title") for n in range(1, 10)] diff --git a/tools/release_train.py b/tools/release_train.py index cf3219fde..b881265f9 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -6,8 +6,9 @@ python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes A kind releases when a pull request merged into main since its last published release changed one of its -player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and that release is at least COOLDOWN old, or when one of those -pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count +player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst +of merges becomes one release), or the oldest at least MAX_WAIT ago (merges that never pause still ship), or when one +of those pull requests is labelled release-now. Pull requests labelled skip-release (work players don't see) don't count towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repository variable) stops automatic releases. Game releases are tagged vYYYY.MM.DD, then .1, .2 the same UTC day; launcher releases launcher-vX.Y.Z, the @@ -29,7 +30,11 @@ import sys ROOT = Path(__file__).resolve().parents[1] REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") -COOLDOWN = dt.timedelta(hours=3) +DEBOUNCE = dt.timedelta(minutes=15) +MAX_WAIT = dt.timedelta(hours=1) +# Kept as typed in release titles, where the clauses after the first are lowercased. +PROPER = {"Horizon", "Horizon's", "Minecraft", "Mojang", "Microsoft", "Java", "Xbox", "PlayStation", "Steam", "Windows", + "Linux", "LAN", "Kira", "Discord", "Wayland", "Hyprland", "F3", "GUI", "UI"} EXPORTERS = "mods/horizon/src/test/java/dev/horizonlab/parity/" # What players run. Documentation (*.md), tests, benchmarks and harness probes (examples/) never count. @@ -119,7 +124,7 @@ def changed_paths(commit): def pull_request(number): data = gh_json("pr", "view", str(number), "--repo", REPO, "--json", - "number,title,url,labels,closingIssuesReferences,author") + "number,title,url,labels,closingIssuesReferences,author,mergedAt") return { "number": data["number"], "title": data["title"].strip(), @@ -127,6 +132,7 @@ def pull_request(number): "labels": sorted(label["name"] for label in data["labels"]), "issues": sorted(issue["number"] for issue in data.get("closingIssuesReferences") or []), "author": (data.get("author") or {}).get("login", ""), + "merged_at": dt.datetime.fromisoformat(data["mergedAt"].replace("Z", "+00:00")) if data.get("mergedAt") else None, } @@ -143,12 +149,12 @@ def last_release(releases, kind): return max(ours, key=lambda release: tag_key(release["tag_name"]), default=None) -def decision(kind, prs, last_published, now, paused=False, force=False): +def decision(kind, prs, now, paused=False, force=False): """Whether to release now, and why. prs: the merged pull requests since the last release, each with the - files it changed under "paths" (player-facing ones only).""" + files it changed under "paths" (player-facing ones only) and when it merged ("merged_at").""" counted = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] urgent = [pr for pr in counted if "release-now" in pr["labels"]] - age = now - last_published if last_published else None + merged = [pr["merged_at"] for pr in counted if pr.get("merged_at")] if force: return True, "started by hand with force" if paused: @@ -157,9 +163,9 @@ def decision(kind, prs, last_published, now, paused=False, force=False): return False, "no merged pull request changed what players run" if urgent: return True, "release-now: " + ", ".join(f"#{pr['number']}" for pr in urgent) - if age is not None and age < COOLDOWN: - wait = COOLDOWN - age - return False, f"{len(counted)} pull requests wait for the cooldown ({wait.seconds // 60} more minutes)" + if merged and now - max(merged) < DEBOUNCE and now - min(merged) < MAX_WAIT: + wait = DEBOUNCE - (now - max(merged)) + return False, f"{len(counted)} pull requests: waiting {wait.seconds // 60 + 1} more minutes for merges to settle" return True, f"{len(counted)} pull requests changed what players run" @@ -178,7 +184,9 @@ def summary(new, fixed, limit=72): titles.append(title) shown, text = [], "" for title in titles: - title = title if not shown or not title[1:2].islower() else title[0].lower() + title[1:] + first = title.split(" ", 1)[0] + if shown and title[1:2].islower() and first not in PROPER: + title = title[0].lower() + title[1:] candidate = ", ".join(shown + [title]) if shown and len(candidate) > limit - 20: break @@ -265,7 +273,7 @@ def main(): parser.add_argument("--kind", choices=["game", "launcher"], required=True) parser.add_argument("--head", help="the commit to release (default: the newest commit on main whose checks passed)") parser.add_argument("--tag", help="notes: the release's tag") - parser.add_argument("--force", action="store_true", help="release even without player-facing changes or within the cooldown") + parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused") parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") args = parser.parse_args() @@ -289,8 +297,7 @@ def main(): print(title + "\n\n" + body) return 0 - published = dt.datetime.fromisoformat(last["published_at"].replace("Z", "+00:00")) if last else None - release, reason = decision(args.kind, prs, published, now, os.environ.get("RELEASES_PAUSED") == "1", args.force) + release, reason = decision(args.kind, prs, now, os.environ.get("RELEASES_PAUSED") == "1", args.force) tags = run("git", "tag", "--list").split() minor = any("feature" in pr["labels"] for pr in prs if pr["paths"]) tag = next_game_tag(tags, now.date()) if args.kind == "game" else next_launcher_tag(tags, minor) From 7a07251acfa3ecf27aab252d3c1c2e98e9eb1d7a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:05:59 +0200 Subject: [PATCH 7/8] CI disk: short artifact retention, runner cleanup, sccache on the Mac runners Releases now ship as often as changes land, so nothing they leave behind may grow without bound. Workflow uploads keep 3 days (nightly parity logs 7); the releases carry their own assets. tools/ci/runner-gc.sh, run every 6 hours by launchd on the Mac mini from a copy of main, skips a runner in a job, removes a checkout's cargo build folders past 12 GB and harness work folders under .local/ untouched for 3 days, and keeps the 2 newest shared preparations while no runner works. The runners build through the machine's sccache, so what it removes comes back from the cache. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 ++ .github/workflows/launcher.yml | 3 +- .github/workflows/nightly.yml | 2 +- .github/workflows/release.yml | 3 +- docs/release-flow.md | 13 +++++++++ tools/ci/runner-env.sh | 5 ++++ tools/ci/runner-gc.sh | 53 ++++++++++++++++++++++++++++++++++ 7 files changed, 78 insertions(+), 3 deletions(-) create mode 100755 tools/ci/runner-gc.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index dd9cde557..57b7842b1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,6 +80,7 @@ jobs: name: parity-logs path: .local/parity-runner/logs/ if-no-files-found: ignore + retention-days: 3 # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in @@ -541,3 +542,4 @@ jobs: dist/client-graphics-smoke.json dist/client-graphics-macos-title.json dist/client-graphics-macos-world.json + retention-days: 3 diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 60d0ba5c1..f0ac59a2b 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -209,7 +209,7 @@ jobs: with: name: ${{ matrix.asset }} path: launcher/out/* - retention-days: 7 + retention-days: 3 release: needs: [decide, build] @@ -250,3 +250,4 @@ jobs: with: name: launcher-release-notes path: notes/ + retention-days: 3 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index 59560e262..689cdae59 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -76,4 +76,4 @@ jobs: name: nightly-parity-logs path: .local/parity-runner/logs/ if-no-files-found: ignore - retention-days: 14 + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0ffa29d26..3162b6f1b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -181,7 +181,7 @@ jobs: name: ${{ matrix.asset }} path: dist/${{ matrix.asset }} if-no-files-found: error - retention-days: 7 + retention-days: 3 publish: needs: [decide, build] @@ -222,3 +222,4 @@ jobs: with: name: release-notes path: notes/ + retention-days: 3 diff --git a/docs/release-flow.md b/docs/release-flow.md index 4a8951296..f494bf538 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -229,3 +229,16 @@ time, on the Mac mini's runner, after preparing the resources again if the prepa The bugs session picks the issues up. The audit's logs are the run's `nightly-parity-logs` artifact; harnesses listed `linux_only` are skipped there (see above). By hand: `gh workflow run "nightly audit"` (add `-f dry_run=true` to leave issues alone). + +## Disk + +Releases ship often, so nothing they leave behind may grow without bound. + +- **Artifacts:** every upload keeps 3 days (nightly parity logs 7); a release's assets live on the release itself. +- **Mac runners:** `tools/ci/runner-gc.sh` runs every 6 hours from launchd on the Mac mini, as a copy taken from main + (`~/.actions-runners/runner-gc.sh`, plist `dev.horizon.runner-gc`), never from a pull request's checkout. It skips a + runner in a job, removes a checkout's cargo build folders past 12 GB (`MAX_TARGET_GB`) and harness work folders + under `.local/` untouched for 3 days (`STALE_DAYS`), and keeps the 2 newest shared preparations (`KEEP_PREPARED`) + while no runner works. Runner builds go through the machine's sccache (`tools/ci/runner-env.sh`), so what it removes + comes back from the cache. Update the copy after changing the script: + `ssh macmini 'curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/tools/ci/runner-gc.sh -o ~/.actions-runners/runner-gc.sh'`. diff --git a/tools/ci/runner-env.sh b/tools/ci/runner-env.sh index b4c5094bd..49158ac91 100755 --- a/tools/ci/runner-env.sh +++ b/tools/ci/runner-env.sh @@ -12,5 +12,10 @@ if [ "$(uname)" = Darwin ]; then java_home=$(/usr/libexec/java_home -v "$java_major") { echo "$bin"; echo "$java_home/bin"; echo /opt/homebrew/bin; } >> "$GITHUB_PATH" echo "JAVA_HOME=$java_home" >> "$GITHUB_ENV" + # Builds go through the machine's sccache (shared with ~/fleet/rbuild), so the build folders runner-gc.sh + # removes come back from the cache instead of compiling cold. + if [ -x /opt/homebrew/bin/sccache ]; then + { echo "RUSTC_WRAPPER=/opt/homebrew/bin/sccache"; echo "CARGO_INCREMENTAL=0"; } >> "$GITHUB_ENV" + fi fi echo "HORIZON_NO_AUDIO=1" >> "$GITHUB_ENV" diff --git a/tools/ci/runner-gc.sh b/tools/ci/runner-gc.sh new file mode 100755 index 000000000..0f4f1e4c2 --- /dev/null +++ b/tools/ci/runner-gc.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Keeps the Mac mini's Horizon runners from filling its disk. launchd runs a copy taken from main +# (~/.actions-runners/runner-gc.sh, never a pull request's checkout) every 6 hours; see docs/release-flow.md. +# - A runner in the middle of a job is left alone. +# - A checkout whose cargo build folders (target/ and the harness probes' targets under .local/, the +# directories holding a CACHEDIR.TAG) pass MAX_TARGET_GB loses them: sccache (tools/ci/runner-env.sh) +# makes the next build cheap. Symlinks into the shared vanilla data are never followed. +# - Harness work folders under .local/ (vanilla exports, probe outputs: real directories, not the links into +# the shared vanilla data) that nothing touched for STALE_DAYS go; a harness that runs again rebuilds its own. +# .local/parity-runner (run state, oracle cache) stays. +# - The shared prepared resources keep their KEEP_PREPARED newest preparations, only while no runner works. +set -euo pipefail +root=${RUNNERS:-$HOME/.actions-runners} +max_kb=$(( ${MAX_TARGET_GB:-12} * 1024 * 1024 )) +keep=${KEEP_PREPARED:-2} +stale_min=$(( ${STALE_DAYS:-3} * 24 * 60 )) +busy() { pgrep -f "$1/bin/Runner.Worker" > /dev/null; } + +any_busy=0 +for runner in "$root"/horizon "$root"/horizon-[0-9]*; do + [ -d "$runner/_work" ] || continue + if busy "$runner"; then echo "$(basename "$runner"): in a job, skipped"; any_busy=1; continue; fi + rm -rf "${runner:?}/_work/_temp/"* 2>/dev/null || true + checkout="$runner/_work/horizon/horizon" + [ -d "$checkout" ] || continue + stale=0 + for dir in "$checkout"/.local/*/; do + dir=${dir%/} + [ -L "$dir" ] || [ "$(basename "$dir")" = parity-runner ] && continue + if [ -z "$(find "$dir" -mmin -"$stale_min" -print -quit 2>/dev/null)" ]; then rm -rf "$dir"; stale=$((stale + 1)); fi + done + [ "$stale" = 0 ] || echo "$(basename "$runner"): removed $stale harness folders untouched for ${STALE_DAYS:-3} days" + targets=() + [ -f "$checkout/target/CACHEDIR.TAG" ] && targets+=("$checkout/target") + while IFS= read -r tag; do targets+=("$(dirname "$tag")"); done < <( + find "$checkout/.local" -mindepth 2 -maxdepth 2 -name CACHEDIR.TAG -type f 2>/dev/null) + [ ${#targets[@]} -gt 0 ] || continue + size=$(du -sk "${targets[@]}" | awk '{s += $1} END {print s}') + if [ "$size" -gt "$max_kb" ]; then + rm -rf "${targets[@]}" + echo "$(basename "$runner"): removed ${#targets[@]} build folders ($(( size / 1024 / 1024 )) GB)" + fi +done + +prepared="$root/horizon/_work/horizon/shared-local/prepared" +if [ "$any_busy" = 0 ] && [ -d "$prepared" ] && mkdir "$prepared/.lock" 2>/dev/null; then + trap 'rmdir "$prepared/.lock" 2>/dev/null || true' EXIT + ls -1t "$prepared" | tail -n +"$(( keep + 1 ))" | while read -r old; do + rm -rf "${prepared:?}/$old" + echo "prepared resources $old removed" + done +fi +df -h "$root" | tail -1 From 2ce2ddcd4dd9b0cd0b429e5133c98fa6eb056901 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 01:07:48 +0200 Subject: [PATCH 8/8] Explorer, treasure and abandoned camp maps work (#147) Vanilla 26.3 has a MapItem per explorer map (buried_treasure_map, abandoned_camp_map, woodland_mansion_map...) and treats any stack with a map_id as a map. Its ExplorationMapFunction finds the nearest structure of the tag, makes an unlimited tracking map centred on it, draws the biome preview (MapItem.renderBiomePreviewMap) and adds the target decoration (MAP_DECORATIONS, drawn by tickCarriedBy). Horizon only recognised filled_map, turned trade maps into filled_map, cleared every decoration but the player's each tick, and chest loot only flagged the map as found: the treasure maps of shipwrecks and underwater ruins and the maps of 26.3's abandoned camps had no map id, no target and no picture. - map_id: any stack with the component. - tick_maps: the item's map_decorations (red X, mansion, camp...) are drawn as addDecoration places them (off the map only when unlimited). - render_biome_preview: vanilla's water outline picture from the noise biomes at sea level (new generator query noise_biomes, fuzzed through BiomeManager's zoom) and #water_on_map_outlines. - Chest loot (rolled with the chunk here) keeps the function's search in minecraft:custom_data; opening the chest runs it from the chest (vanilla runs it when the chest is unpacked on first open), else reaching the inventory runs it from the player. Nothing found drops the item, as the tables' filtered map_id check does. - Trades keep their map item. Fixes #147 Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_death_loot_fixture.rs | 1 + crates/horizon-client/src/game.rs | 6 + crates/horizon-client/src/game/creatures.rs | 1 + crates/horizon-client/src/game/maps.rs | 357 +++++++++++++++++- crates/horizon-client/src/game/trading.rs | 2 +- crates/horizon-client/src/merchant.rs | 23 +- crates/horizon-client/src/mobs/drops.rs | 1 + crates/horizon-client/src/structure_blocks.rs | 152 +++++++- crates/horizon-client/src/vanillagen.rs | 7 + crates/horizon-world/src/loot.rs | 46 ++- .../horizon-world/src/worldgen/generator.rs | 20 + 11 files changed, 572 insertions(+), 44 deletions(-) diff --git a/crates/horizon-client/examples/entity_death_loot_fixture.rs b/crates/horizon-client/examples/entity_death_loot_fixture.rs index 1c9d06440..a8eceb8ca 100644 --- a/crates/horizon-client/examples/entity_death_loot_fixture.rs +++ b/crates/horizon-client/examples/entity_death_loot_fixture.rs @@ -21,6 +21,7 @@ fn stack(spec: &str) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, }; for e in parts { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 146e5c8f0..8ce46d5b7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1895,6 +1895,12 @@ impl Game<'_> { // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { self.world.block_entities.entry(key).or_insert(entity); + let centre = [ + f64::from(key.0) + 0.5, + f64::from(key.1) + 0.5, + f64::from(key.2) + 0.5, + ]; + self.resolve_container_maps(key, centre); self.container = Some(key); self.container_opener_event(key, true); self.post_block_game_event( diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 9d7bc79d6..7291931bc 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2861,6 +2861,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack { .collect(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index f11b96408..3da532a31 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -138,12 +138,116 @@ fn packed_rgba(packed: u8) -> [u8; 4] { let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8; [ch(16), ch(8), ch(0), 255] } +/// `has(DataComponents.MAP_ID)`: filled maps and the explorer map items +/// (`buried_treasure_map`, `woodland_mansion_map`, ..., all `MapItem`s). pub(super) fn map_id(stack: &ItemStack) -> Option { - if &*stack.item != "minecraft:filled_map" { - return None; - } stack.data().and_then(|d| d.map_id) } +/// `MapDecorationTypes`: the sprite of a decoration type that a +/// `minecraft:map_decorations` entry can name. +fn decoration_sprite(id: &str) -> Option<&'static str> { + Some(match id.strip_prefix("minecraft:").unwrap_or(id) { + "player" => "map/decorations/player", + "frame" => "map/decorations/frame", + "red_marker" => "map/decorations/red_marker", + "blue_marker" => "map/decorations/blue_marker", + "target_x" => "map/decorations/target_x", + "target_point" => "map/decorations/target_point", + "player_off_map" => "map/decorations/player_off_map", + "player_off_limits" => "map/decorations/player_off_limits", + "mansion" => "map/decorations/woodland_mansion", + "monument" => "map/decorations/ocean_monument", + "red_x" => "map/decorations/red_x", + "village_desert" => "map/decorations/desert_village", + "village_plains" => "map/decorations/plains_village", + "village_savanna" => "map/decorations/savanna_village", + "village_snowy" => "map/decorations/snowy_village", + "village_taiga" => "map/decorations/taiga_village", + "jungle_temple" => "map/decorations/jungle_temple", + "swamp_hut" => "map/decorations/swamp_hut", + "trial_chambers" => "map/decorations/trial_chambers", + "abandoned_camp" => "map/decorations/abandoned_camp", + "ancient_city" => "map/decorations/ancient_city", + "desert_pyramid" => "map/decorations/desert_pyramid", + "mineshaft" => "map/decorations/mineshaft", + "ocean_ruin_warm" => "map/decorations/warm_ocean_ruins", + _ => return None, + }) +} +/// `minecraft:map_decorations` of a map item: (sprite, x, z, rotation), in +/// the component's order. +fn static_decorations(stack: &ItemStack) -> Vec<(&'static str, f64, f64, f32)> { + let Some(Tag::Compound(entries)) = stack.data().and_then(|d| { + d.other + .iter() + .find(|(k, _)| k == "minecraft:map_decorations") + .map(|(_, t)| t) + }) else { + return Vec::new(); + }; + let number = |t: Option<&Tag>| match t { + Some(Tag::Double(b)) => Some(f64::from_bits(*b)), + Some(Tag::Float(b)) => Some(f64::from(f32::from_bits(*b))), + Some(Tag::Int(v)) => Some(f64::from(*v)), + _ => None, + }; + entries + .values() + .filter_map(|e| { + let sprite = match e.get("type") { + Some(Tag::String(s)) => decoration_sprite(&s.to_string_lossy())?, + _ => return None, + }; + Some(( + sprite, + number(e.get("x"))?, + number(e.get("z"))?, + number(e.get("rotation")).unwrap_or(0.0) as f32, + )) + }) + .collect() +} +/// `MapItemSavedData.addTargetDecoration`: the `"+"` entry of +/// `minecraft:map_decorations`, rotation 180. +fn target_decoration(decoration: &str, at: [i32; 3]) -> Tag { + Tag::compound([( + "+", + Tag::compound([ + ("type", Tag::String(decoration.into())), + ("x", Tag::Double(f64::from(at[0]).to_bits())), + ("z", Tag::Double(f64::from(at[2]).to_bits())), + ("rotation", Tag::Float(180.0f32.to_bits())), + ]), + )]) +} +/// `MapItemSavedData.clampMapCoordinate`. +fn clamp_map_coordinate(d: f32) -> i8 { + if d <= -63.0 { + -128 + } else if d >= 63.0 { + 127 + } else { + (d * 2.0 + 0.5) as i8 + } +} +/// `MapItemSavedData.calculateRotation`: spinning in the Nether. +fn decoration_rotation(nether: bool, game_time: i64, y_rot: f64) -> u8 { + if nether { + let s = (game_time / 10) as i32; + (s.wrapping_mul(s) + .wrapping_mul(34_187_121) + .wrapping_add(s.wrapping_mul(121)) + >> 15 + & 15) as u8 + } else { + let adjusted = if y_rot < 0.0 { + y_rot - 8.0 + } else { + y_rot + 8.0 + }; + ((adjusted * 16.0 / 360.0) as i32 & 15) as u8 + } +} impl Game<'_> { fn dimension_id(&self) -> &'static str { match self.dim { @@ -199,6 +303,161 @@ impl Game<'_> { self.maps.data.insert(id, data); let last = self.maps.last_id.unwrap_or(-1).max(id); self.maps.last_id = Some(last); + self.render_biome_preview(id); + } + } + /// `ExplorationMapFunction.run` for an item a generated chest still holds + /// unsearched (`structure_blocks::take_pending_map`): the nearest + /// structure of the tag around `origin`, a new map centred on it with its + /// biome preview and target decoration. False when nothing is found: the + /// loot table's `filtered` map_id check would have discarded the item. + pub(super) fn resolve_pending_map(&mut self, item: &mut ItemStack, origin: [f64; 3]) -> bool { + let Some(map) = horizon_client::structure_blocks::take_pending_map(item) else { + return true; + }; + let names = self.structure_tag(&map.destination); + let from = origin.map(|v| v.floor() as i32); + let found = self + .end + .locator() + .filter(|_| !names.is_empty()) + .and_then(|t| t.locate(&names, from, map.search_radius)); + let Some((_, at)) = found else { + return false; + }; + let mut data = MapData::fresh( + f64::from(at[0]), + f64::from(at[2]), + map.zoom, + self.dimension_id(), + ); + data.unlimited = true; + let id = self.new_map_id(data); + self.render_biome_preview(id); + let d = item.data_mut(); + d.map_id = Some(id); + d.other.retain(|(k, _)| k != "minecraft:map_decorations"); + d.other.push(( + "minecraft:map_decorations".into(), + target_decoration(&map.decoration, at), + )); + true + } + /// The unsearched exploration maps of a container being opened + /// (`RandomizableContainer.unpackLootTable` runs the function then). + pub(super) fn resolve_container_maps(&mut self, key: (i32, i32, i32), origin: [f64; 3]) { + use horizon_client::containers::BlockEntity; + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get(&key) else { + return; + }; + let pending: Vec = slots + .iter() + .enumerate() + .filter(|(_, s)| { + s.as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + }) + .map(|(i, _)| i) + .collect(); + for i in pending { + let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let Some(mut item) = slots[i].take() else { + continue; + }; + let keep = self.resolve_pending_map(&mut item, origin); + if let Some(BlockEntity::Chest(slots)) = self.world.block_entities.get_mut(&key) { + slots[i] = keep.then_some(item); + } + } + } + /// `MapItem.renderBiomePreviewMap`: the map's biomes at sea level, water + /// outlines (`#water_on_map_outlines`) drawn in orange and brown. + pub(super) fn render_biome_preview(&mut self, id: i32) { + let Some(terrain) = self.end.locator() else { + return; + }; + let dim = self.dimension_id(); + let zoom = self.streaming.biome_zoom; + let watery_biomes: std::collections::HashSet = self + .tag_entries("worldgen/biome", "minecraft:water_on_map_outlines") + .into_iter() + .collect(); + let Some(m) = self.maps.data.get(&id) else { + return; + }; + if m.dimension != dim { + return; + } + let scale = 1i32 << m.scale; + let start_x = m.center[0] / scale - 64; + let start_z = m.center[1] / scale - 64; + let sea_level = 63; + let quarts: Vec<[i32; 3]> = (0..128) + .flat_map(|row| { + (0..128).map(move |column| { + zoom.quart_at_block(horizon_core::position::BlockPos::new( + (start_x + column) * scale, + sea_level, + (start_z + row) * scale, + )) + }) + }) + .collect(); + let watery: Vec = terrain + .noise_biomes(&quarts) + .into_iter() + .map(|b| b.is_some_and(|b| watery_biomes.contains(&b))) + .collect(); + let is_watery = |x: i32, z: i32| watery[(z * 128 + x) as usize]; + // MapColor ids and MapColor.Brightness ids. + const ORANGE: u8 = 15; + const BROWN: u8 = 26; + const LOW: u8 = 0; + const NORMAL: u8 = 1; + const HIGH: u8 = 2; + const LOWEST: u8 = 3; + let Some(m) = self.maps.data.get_mut(&id) else { + return; + }; + for mx in 1..127 { + for mz in 1..127 { + let mut water_count = 0; + for dx in -1..2 { + for dz in -1..2 { + if (dx != 0 || dz != 0) && is_watery(mx + dx, mz + dz) { + water_count += 1; + } + } + } + let mut brightness = LOWEST; + let mut color = 0; + if is_watery(mx, mz) { + color = ORANGE; + if water_count > 7 && mz % 2 == 0 { + let sin = horizon_core::geometry::trig::sin(f64::from(mz as f32 + 0.0)); + match (mx + (sin * 7.0) as i32) / 8 % 5 { + 0 | 4 => brightness = LOW, + 1 | 3 => brightness = NORMAL, + 2 => brightness = HIGH, + _ => {} + } + } else if water_count > 7 { + color = 0; + } else if water_count > 5 { + brightness = NORMAL; + } else if water_count > 1 { + brightness = LOW; + } + } else if water_count > 0 { + color = BROWN; + brightness = if water_count > 3 { NORMAL } else { LOWEST }; + } + if color != 0 { + m.update_color(mx, mz, color << 2 | brightness); + } + } } } /// Registers `data` under a free map id. @@ -250,20 +509,33 @@ impl Game<'_> { let Some(p) = self.player.as_ref().map(|p| p.position) else { return; }; + // A generated exploration map that reached the inventory unsearched + // (moved out of its chest by a hopper): searched from here. + for i in 0..self.inventory.len() { + if self.inventory[i] + .as_ref() + .is_some_and(horizon_client::structure_blocks::has_pending_map) + && let Some(mut item) = self.inventory[i].take() + { + let keep = self.resolve_pending_map(&mut item, [p.x, p.y, p.z]); + self.inventory[i] = keep.then_some(item); + } + } let held: Vec = [Some(self.selected), Some(super::shield::OFFHAND_SLOT)] .into_iter() .flatten() .filter_map(|i| self.stack_in(i).and_then(map_id)) .collect(); - let carried: Vec = self + let carried: Vec<(i32, Vec<(&'static str, f64, f64, f32)>)> = self .inventory .iter() .chain(std::iter::once(&self.offhand)) .flatten() - .filter_map(map_id) + .filter_map(|s| Some((map_id(s)?, static_decorations(s)))) .collect(); let (yaw, dim) = (self.yaw, self.dimension_id()); - for id in carried { + let (nether, game_time) = (self.dim == super::Dim::Nether, self.world.game_time); + for (id, targets) in carried { let Some(m) = self.map(id) else { continue }; // tickCarriedBy: the player marker while tracking in this dimension. m.decorations.clear(); @@ -302,6 +574,26 @@ impl Game<'_> { }); } } + // The item's MAP_DECORATIONS (an explorer map's target), added + // after the players as addDecoration would. + let s = (1 << m.scale) as f32; + for (sprite, x, z, rotation) in targets { + let dx = (x - f64::from(m.center[0])) as f32 / s; + let dz = (z - f64::from(m.center[1])) as f32 / s; + let inside = (-63.0..=63.0).contains(&dx) && (-63.0..=63.0).contains(&dz); + if !inside && !m.unlimited { + continue; + } + let d = Decoration { + sprite, + x: clamp_map_coordinate(dx), + y: clamp_map_coordinate(dz), + rot: decoration_rotation(nether, game_time, f64::from(rotation)), + }; + if !m.decorations.contains(&d) { + m.decorations.push(d); + } + } } for id in held { self.update_map(id); @@ -663,3 +955,56 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_target_decoration_type_has_its_sprite() { + // MapDecorationTypes: (name, asset). + for (name, asset) in [ + ("mansion", "woodland_mansion"), + ("monument", "ocean_monument"), + ("red_x", "red_x"), + ("village_desert", "desert_village"), + ("village_plains", "plains_village"), + ("village_savanna", "savanna_village"), + ("village_snowy", "snowy_village"), + ("village_taiga", "taiga_village"), + ("jungle_temple", "jungle_temple"), + ("swamp_hut", "swamp_hut"), + ("trial_chambers", "trial_chambers"), + ("abandoned_camp", "abandoned_camp"), + ("ancient_city", "ancient_city"), + ("desert_pyramid", "desert_pyramid"), + ("mineshaft", "mineshaft"), + ("ocean_ruin_warm", "warm_ocean_ruins"), + ] { + assert_eq!( + decoration_sprite(&format!("minecraft:{name}")), + Some(format!("map/decorations/{asset}").as_str()), + "{name}" + ); + } + assert_eq!(decoration_sprite("minecraft:nothing"), None); + } + + #[test] + fn target_decorations_read_back_with_vanilla_rotation() { + let mut stack = ItemStack::new("minecraft:buried_treasure_map", 1); + stack.data_mut().map_id = Some(3); + stack.data_mut().other.push(( + "minecraft:map_decorations".into(), + target_decoration("minecraft:red_x", [120, 40, -300]), + )); + assert_eq!(map_id(&stack), Some(3)); + let found = static_decorations(&stack); + assert_eq!(found, vec![("map/decorations/red_x", 120.0, -300.0, 180.0)]); + // calculateRotation(180): (byte) (188 * 16 / 360) = 8. + assert_eq!(decoration_rotation(false, 0, 180.0), 8); + assert_eq!(decoration_rotation(false, 0, -90.0), 12); + assert_eq!(clamp_map_coordinate(-70.0), -128); + assert_eq!(clamp_map_coordinate(10.25), 21); + } +} diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 70ba4ab6a..738e3965b 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -89,8 +89,8 @@ impl merchant::MapMaker for GameMaps<'_> { self.made .borrow_mut() .push((id, at, map.zoom, map.decoration.clone())); + // The trade's own map item (woodland_mansion_map, ...) keeps its id. let mut out = stack; - out.item = std::sync::Arc::from("minecraft:filled_map"); let d = out.data_mut(); d.map_id = Some(id); d.other.push(( diff --git a/crates/horizon-client/src/merchant.rs b/crates/horizon-client/src/merchant.rs index 32f7512dc..81e2dab01 100644 --- a/crates/horizon-client/src/merchant.rs +++ b/crates/horizon-client/src/merchant.rs @@ -643,13 +643,7 @@ pub trait MapMaker { ) -> ItemStack; } /// An `exploration_map` function's settings. -pub struct ExplorationMap { - pub destination: String, - pub decoration: String, - pub zoom: u8, - pub search_radius: i32, - pub skip_existing_chunks: bool, -} +pub use horizon_world::loot::ExplorationMap; fn int_provider(v: &Value, random: &mut R) -> i32 { match v { Value::Number(n) => n.as_i64().unwrap_or(0) as i32, @@ -953,20 +947,7 @@ impl Trades { let Some(maps) = ctx.maps else { return Some((stack, 0)); }; - let map = ExplorationMap { - destination: m["destination"] - .as_str() - .unwrap_or("#minecraft:on_treasure_maps") - .trim_start_matches('#') - .to_owned(), - decoration: m["decoration"] - .as_str() - .unwrap_or("minecraft:mansion") - .to_owned(), - zoom: m["zoom"].as_u64().unwrap_or(2) as u8, - search_radius: m["search_radius"].as_i64().unwrap_or(50) as i32, - skip_existing_chunks: m["skip_existing_chunks"].as_bool().unwrap_or(true), - }; + let map = ExplorationMap::from_json(m); Some((maps.exploration_map(stack, &map, ctx.origin), 0)) } _ => Some((stack, 0)), diff --git a/crates/horizon-client/src/mobs/drops.rs b/crates/horizon-client/src/mobs/drops.rs index 102a5a5b6..3ebcc71f5 100644 --- a/crates/horizon-client/src/mobs/drops.rs +++ b/crates/horizon-client/src/mobs/drops.rs @@ -301,6 +301,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 86d83f4ed..ea399937e 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -12,6 +12,81 @@ use std::{ sync::{Arc, OnceLock}, }; +/// The `custom_data` key holding an exploration map's search until the game +/// runs it (vanilla runs `ExplorationMapFunction` when the chest is unpacked, +/// on first open; here loot is rolled with the chunk). +const PENDING_MAP: &str = "horizon:exploration_map"; +const CUSTOM_DATA: &str = "minecraft:custom_data"; + +/// A generated chest's item, with its exploration map search kept in +/// `minecraft:custom_data` (which vanilla loads as is). +fn loot_item(s: &horizon_world::loot::LootStack) -> ItemStack { + let mut item = ItemStack { + item: Arc::from(s.item.as_str()), + count: s.count.max(0) as u32, + damage: s.damage.max(0) as u32, + extra: None, + }; + if let Some(map) = &s.exploration { + let search = Tag::compound([ + ("destination", Tag::String(map.destination.as_str().into())), + ("decoration", Tag::String(map.decoration.as_str().into())), + ("zoom", Tag::Byte(map.zoom as i8)), + ("search_radius", Tag::Int(map.search_radius)), + ( + "skip_existing_chunks", + Tag::Byte(i8::from(map.skip_existing_chunks)), + ), + ]); + item.data_mut() + .other + .push((CUSTOM_DATA.into(), Tag::compound([(PENDING_MAP, search)]))); + } + item +} + +/// The exploration map search an item still waits for, removed from it. +pub fn take_pending_map(item: &mut ItemStack) -> Option { + let data = item.extra.as_deref_mut()?; + let i = data + .other + .iter() + .position(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some())?; + let (_, mut custom) = data.other.remove(i); + let search = match &mut custom { + Tag::Compound(c) => c.remove(&JavaString::from(PENDING_MAP))?, + _ => return None, + }; + if matches!(&custom, Tag::Compound(c) if !c.is_empty()) { + data.other.insert(i, (CUSTOM_DATA.into(), custom)); + } + let text = |k: &str| match search.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let int = |k: &str| match search.get(k) { + Some(Tag::Int(v)) => Some(*v), + Some(Tag::Byte(v)) => Some(i32::from(*v)), + _ => None, + }; + Some(horizon_world::loot::ExplorationMap { + destination: text("destination")?, + decoration: text("decoration")?, + zoom: int("zoom").unwrap_or(2).clamp(0, 4) as u8, + search_radius: int("search_radius").unwrap_or(50), + skip_existing_chunks: int("skip_existing_chunks").unwrap_or(1) != 0, + }) +} + +/// Whether an item still waits for its exploration map search. +pub fn has_pending_map(item: &ItemStack) -> bool { + item.data().is_some_and(|d| { + d.other + .iter() + .any(|(k, t)| k == CUSTOM_DATA && t.get(PENDING_MAP).is_some()) + }) +} + /// Loot data of the resource root, loaded once per process. pub fn loot_data(root: &Path) -> Option> { static LOOT: OnceLock>> = OnceLock::new(); @@ -64,12 +139,7 @@ pub fn block_entities( .zip(loot.fill(&table, seed, 27, Some(biome))) { *slot = stack.map(|s| { - let mut item = ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }; + let mut item = loot_item(&s); // An ominous bottle's level (the default, 0, is no component). if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) { item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8); @@ -114,17 +184,71 @@ pub fn unpack_entity_loot( let slots: Vec> = loot .fill(&table, seed, 27, Some(biome)) .into_iter() - .map(|s| { - s.map(|s| ItemStack { - item: Arc::from(s.item.as_str()), - count: s.count.max(0) as u32, - damage: s.damage.max(0) as u32, - extra: None, - }) - }) + .map(|s| s.map(|s| loot_item(&s))) .collect(); nbt.remove(&JavaString::from("LootTable")); nbt.remove(&JavaString::from("LootTableSeed")); nbt.insert("Items".into(), crate::save::encode_items(&slots)); nbt } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_world::loot::{ExplorationMap, LootStack}; + + #[test] + fn exploration_maps_wait_in_custom_data_until_searched() { + let mut stack = LootStack { + item: "minecraft:buried_treasure_map".into(), + count: 1, + damage: 0, + enchantments: Vec::new(), + potion: None, + map: true, + exploration: Some(Box::new(ExplorationMap::from_json(&serde_json::json!({ + "decoration": "minecraft:red_x", + "destination": "#minecraft:on_treasure_maps", + "skip_existing_chunks": false, + "zoom": 1 + })))), + ominous_amplifier: None, + }; + let mut item = loot_item(&stack); + assert!(has_pending_map(&item)); + // The rest of custom_data stays. + if let Some(Tag::Compound(c)) = item + .data_mut() + .other + .iter_mut() + .find(|(k, _)| k == CUSTOM_DATA) + .map(|(_, t)| t) + { + c.insert("note".into(), Tag::Int(7)); + } + let map = take_pending_map(&mut item).unwrap(); + assert_eq!( + map, + ExplorationMap { + destination: "minecraft:on_treasure_maps".into(), + decoration: "minecraft:red_x".into(), + zoom: 1, + search_radius: 50, + skip_existing_chunks: false, + } + ); + assert!(!has_pending_map(&item)); + assert!(take_pending_map(&mut item).is_none()); + let custom = &item.data().unwrap().other; + assert_eq!(custom.len(), 1); + assert_eq!(custom[0].1.get("note"), Some(&Tag::Int(7))); + // Only the search: the component goes away with it. + stack.item = "minecraft:abandoned_camp_map".into(); + let mut item = loot_item(&stack); + take_pending_map(&mut item).unwrap(); + assert!(item.data().unwrap().other.is_empty()); + // A plain item has nothing pending. + stack.exploration = None; + assert!(!has_pending_map(&loot_item(&stack))); + } +} diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 04716b99d..9b58cdd38 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -117,6 +117,13 @@ impl VanillaTerrain { let worker = worker.get_or_insert_with(|| self.generator.worker()); worker.find_closest_biome(search) } + /// `BiomeSource.getNoiseBiome` at quart positions, for places that may not + /// be generated yet (`MapItem.renderBiomePreviewMap`). + pub fn noise_biomes(&self, quarts: &[[i32; 3]]) -> Vec> { + let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner()); + let worker = worker.get_or_insert_with(|| self.generator.worker()); + worker.noise_biomes(quarts) + } /// `/place jigsaw`: `JigsawPlacement.addPieces`. pub fn jigsaw_pieces( &self, diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index fccfa4c77..b0a885ba2 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -26,9 +26,43 @@ pub struct LootStack { pub potion: Option, /// Set by exploration_map (the map_id component of a found map). pub map: bool, + /// The search an exploration_map function asked for, left to the game + /// (it needs the level's structures and maps). + pub exploration: Option>, /// Set by set_ominous_bottle_amplifier. pub ominous_amplifier: Option, } +/// `ExplorationMapFunction`'s settings. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExplorationMap { + /// A structure tag, without `#`. + pub destination: String, + pub decoration: String, + pub zoom: u8, + pub search_radius: i32, + pub skip_existing_chunks: bool, +} +impl ExplorationMap { + /// The function's fields with their codec defaults (`DEFAULT_DESTINATION` + /// on_treasure_maps, `DEFAULT_DECORATION` mansion, zoom 2, radius 50, + /// skipping known structures). + pub fn from_json(f: &Value) -> Self { + Self { + destination: f["destination"] + .as_str() + .unwrap_or("#minecraft:on_treasure_maps") + .trim_start_matches('#') + .to_owned(), + decoration: f["decoration"] + .as_str() + .unwrap_or("minecraft:mansion") + .to_owned(), + zoom: f["zoom"].as_u64().unwrap_or(2) as u8, + search_radius: f["search_radius"].as_i64().unwrap_or(50) as i32, + skip_existing_chunks: f["skip_existing_chunks"].as_bool().unwrap_or(true), + } + } +} impl LootStack { fn new(item: &str) -> Self { Self { @@ -38,6 +72,7 @@ impl LootStack { enchantments: Vec::new(), potion: None, map: false, + exploration: None, ominous_amplifier: None, } } @@ -1045,8 +1080,15 @@ impl Context<'_, R> { } } // ExplorationMapFunction needs an origin; with one, the map is - // taken as found (the structure search itself is not run). - "minecraft:exploration_map" => stack.map = self.biome.is_some(), + // taken as found here and the game runs the structure search + // (it drops the map when nothing is found, as the filtered + // map_id check after it would). + "minecraft:exploration_map" => { + stack.map = self.biome.is_some(); + if stack.map { + stack.exploration = Some(Box::new(ExplorationMap::from_json(f))); + } + } "minecraft:filtered" => { let pass = self.item_matches(&f["item_filter"], &stack); let branch = if pass { &f["on_pass"] } else { &f["on_fail"] }; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7adcb33b5..7e06f2013 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1403,6 +1403,8 @@ trait SeededPipeline: Send + Sync { worker: &mut WorkerState, search: &BiomeSearch<'_>, ) -> Option<(String, [i32; 3])>; + /// `BiomeSource.getNoiseBiome` at each quart position (unloaded chunks). + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec>; fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1562,6 +1564,21 @@ where } None } + fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec> { + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + quarts + .iter() + .map(|&quart| { + resolver + .sample(&mut worker.carver_context, quart) + .ok() + .map(str::to_owned) + }) + .collect() + } fn jigsaw_pieces( &self, worker: &mut WorkerState, @@ -1841,6 +1858,9 @@ impl GeneratorWorker { } /// `BiomeSource.findClosestBiome3d`: the first sampled position whose /// noise biome passes `allowed`, spiralling out from the origin. + pub fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec> { + self.pipeline.noise_biomes(&mut self.state, quarts) + } pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> { self.pipeline.find_closest_biome(&mut self.state, search) }