From 621b791a33224155253f0470774715022e9f683f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:08:32 +0200 Subject: [PATCH 001/115] End crystals spin and bob in every dimension EndCrystal.tick advances the crystal's time wherever it is; only the fire at its block needs a dragon fight. Horizon advanced it only during the End fight, so a crystal placed elsewhere kept a fixed time and jumped back every tick (it flickered instead of turning). Fixes #1051 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 10 ++++++---- crates/horizon-client/src/game/end.rs | 1 + 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index cbfad527b..d7dd37640 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -535,7 +535,6 @@ impl Game<'_> { if self.fight.crystal_scan >= 100 { self.count_crystals(); } - self.tick_crystals(); self.tick_dragon(); } /// EndSpikeFeature's crystals (with fire under them on the bedrock). @@ -583,9 +582,12 @@ impl Game<'_> { }) .count() as i32; } - /// `EndCrystal.tick`: the time and the fire below it in the End. - fn tick_crystals(&mut self) { - let fire = self.pack.assets.registry.default_state("minecraft:fire"); + /// `EndCrystal.tick` in every dimension: the time (the spin and bob), + /// and fire at its block where there is a dragon fight (the End). + pub(super) fn tick_crystals(&mut self) { + let fire = (self.dim == Dim::End) + .then(|| self.pack.assets.registry.default_state("minecraft:fire")) + .flatten(); for i in 0..self.crystals.len() { self.crystals[i].time += 1; let p = self.crystals[i].position; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a6d91d563..a7813c767 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -350,6 +350,7 @@ impl Game<'_> { self.tick_fight(); self.tick_dragon_fireballs(); } + self.tick_crystals(); self.tick_eyes(); if self.dim == Dim::End { self.end.flash.tick(self.world.game_time); From 08fdafc4fcb327803a4c6363d02a0f26c24f4418 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:13:48 +0200 Subject: [PATCH 002/115] Thrown potions: drawn as their item, facing the camera (ThrownItemRenderer) A thrown splash or lingering potion or experience bottle was a stand-in terrain particle spawned at its tick position: darkened by the terrain particle colour, without the potion's colour, two overlapping copies and no interpolation between ticks. Draw it as vanilla's ThrownItemRenderer does: the item model (GROUND, with the potion tint) facing the camera, interpolated, lit at its light probe, hidden for its first two ticks near the camera (ThrowableProjectile.shouldRenderAtSqrDistance). Witch potions draw as the splash potion of their effect instead of a bare bottle. Fixes #818 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/game/creatures.rs | 9 +++ crates/horizon-client/src/game/potions.rs | 76 ++++++++++++++------- crates/horizon-client/src/projectiles.rs | 13 ++++ 4 files changed, 76 insertions(+), 23 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4013bb04b..e8237700d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6476,6 +6476,7 @@ impl Game<'_> { self.leash_geometry(camera, alpha, &mut out); self.trident_geometry(camera, alpha, &mut out); self.rocket_geometry(camera, alpha, &mut out); + self.thrown_potion_geometry(camera, alpha, &mut out); // Particles (ParticleEngine.extract): camera-facing quads. let world = &self.world; self.particles.render( diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index db793d993..0d3c9705a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3,6 +3,7 @@ //! breeding, conversions, drops), projectiles, player interactions //! (feeding, shearing, milking, spawn eggs, throwing) and rendering. use super::{Dim, Game, view_vector}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ Result, arrows::EntityHit, @@ -3011,6 +3012,14 @@ impl Game<'_> { } continue; } + if let Some(stack) = a.potion_item() { + let owner = super::item_draw::owner_at(at, 0.0, "minecraft:splash_potion"); + let state = self.resolve_item(&stack, DisplayContext::Ground, Some(&owner), 0); + let pose = glam::Mat4::from_translation(c) + * glam::Mat4::from_quat(self.camera_orientation()); + self.submit_item_world(&state, pose, packed, out); + continue; + } let Some(name) = a.item_sprite() else { continue; }; diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 52ab5060a..72c8fe885 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,13 +2,16 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen}; +use super::{Game, Screen, item_draw::owner_at}; +use horizon_assets::item_model::DisplayContext; use horizon_client::{ + block_entity_render::vertex_light, brewing, effects::{EffectAction, EffectInstance, PlayerEffects}, hud::HudBatch, hud_layout, hud_overlays, inventory_effects, items::ItemStack, + mesher::Vertex, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -16,6 +19,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; #[derive(Clone, Debug)] pub(super) struct ThrownPotion { stack: ItemStack, + /// The position before the last tick, for drawing between ticks. + previous: Vec3, position: Vec3, velocity: Vec3, age: u32, @@ -43,6 +48,7 @@ impl Game<'_> { pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { stack, + previous: position, position, velocity, age: 0, @@ -411,6 +417,7 @@ impl Game<'_> { let mut landed = Vec::new(); thrown.retain_mut(|t| { t.age += 1; + t.previous = t.position; let next = Vec3::new( t.position.x + t.velocity.x, t.position.y + t.velocity.y, @@ -461,33 +468,56 @@ impl Game<'_> { ); t.age < 1200 && t.position.y > -128.0 }); - // ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position. - for t in &thrown { - let sprite = match &*t.stack.item { - "minecraft:lingering_potion" => "item/lingering_potion", - "minecraft:experience_bottle" => "item/experience_bottle", - _ => "item/splash_potion", - }; - let mut fixed = horizon_core::random::LegacyRandom::new(0); - let mut p = horizon_client::particles::Particle::terrain( - &mut fixed, - [t.position.x, t.position.y, t.position.z], - [0.0; 3], - sprite.into(), - 0xFFFFFF, - ); - p.velocity = [0.0; 3]; - p.gravity = 0.0; - p.lifetime = 2; - p.size = 0.25; - p.uv = [0.0, 0.0, 1.0, 1.0]; - self.particles.push(p); - } self.potions.thrown = thrown; for (stack, at) in landed { self.splash(&stack, at); } } + /// `ThrownItemRenderer` for thrown splash and lingering potions and + /// experience bottles: the item (GROUND) facing the camera at scale 1, + /// lit at the light probe (the eye, 0.85 of the 0.25 height). + pub(super) fn thrown_potion_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let orientation = glam::Mat4::from_quat(self.camera_orientation()); + for t in &self.potions.thrown { + let previous = glam::DVec3::new(t.previous.x, t.previous.y, t.previous.z); + let position = glam::DVec3::new(t.position.x, t.position.y, t.position.z); + // ThrowableProjectile.shouldRenderAtSqrDistance: hidden for its + // first two ticks within 3.5 blocks (not in the thrower's face). + if t.age < 2 && position.distance_squared(camera) < 12.25 { + continue; + } + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + 0.25, + 0.25, + 64.0, + 0.0, + ) { + continue; + } + let p = previous.lerp(position, alpha); + let owner = owner_at(p.to_array(), 0.0, &t.stack.item); + let state = self.resolve_item(&t.stack, DisplayContext::Ground, Some(&owner), 0); + if state.is_empty() { + continue; + } + let pose = glam::Mat4::from_translation((p - camera).as_vec3()) * orientation; + let light = self.world.light( + p.x.floor() as i32, + (p.y + 0.2125).floor() as i32, + p.z.floor() as i32, + ); + self.submit_item_world(&state, pose, vertex_light(light), out); + } + } /// A splash potion's effects on the player in place, by their distance. fn splash_on_player( &mut self, diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index cc44e7511..093482a08 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -689,6 +689,19 @@ impl Projectile { } damage as f32 } + /// The item a thrown potion is drawn as (`ThrownItemRenderer`): the + /// splash potion `Witch.performRangedAttack` makes for the effect. + pub fn potion_item(&self) -> Option { + let ProjectileKind::Potion { effect, .. } = self.kind else { + return None; + }; + let potion = match effect { + "minecraft:instant_health" => "minecraft:healing", + "minecraft:instant_damage" => "minecraft:harming", + other => other, + }; + Some(crate::items::ItemStack::new("minecraft:splash_potion", 1).with_potion(potion)) + } /// The item sprite drawn for thrown projectiles (ThrownItemRenderer). pub fn item_sprite(&self) -> Option<&'static str> { Some(match self.kind { From e3cea08736907a624a37c3207bc7993b7a55516c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 18:26:23 +0200 Subject: [PATCH 003/115] Boats: the water patch hides water inside the hull; the riding camera turns smoothly BoatRenderer draws its water_patch part with RenderTypes.waterMask (depth only) unless the boat is under water, so translucent water behind it fails the depth test inside the hull. Horizon loaded the part but never drew it: the water surface showed through the boat. The patch now draws with a depth-only Water mask pipeline after the entities and before translucent terrain (rafts have none, as RaftRenderer). Turning in a boat stepped the camera at the tick rate: positionRider adds the boat's deltaRotation to the passenger's yRot after its yRotO was kept, and LocalPlayer.getViewYRot interpolates a passenger's yaw between them. The camera now spreads the turn over the tick's frames. Fixes #1016 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity.wgsl | 5 ++ crates/horizon-client/src/game/boats.rs | 20 +++++ crates/horizon-client/src/game/perspective.rs | 10 ++- crates/horizon-client/src/gfx.rs | 80 ++++++++++++++++--- crates/horizon-client/src/gfx/entity_batch.rs | 23 ++++-- 5 files changed, 118 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index c6305c697..aa384f711 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -188,3 +188,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; return color; } + +// RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). +@fragment fn fs_water_mask() -> @location(0) vec4 { + return vec4(0.0); +} diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index f9740598e..433c588d0 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -141,6 +141,8 @@ pub(super) fn boat_wood(item: &str) -> Option<&str> { pub(super) struct BoatModels { pub models: HashMap, pub chest_models: HashMap, + /// `ModelLayers.BOAT_WATER_PATCH`, shared by every boat (not rafts). + pub water_patch: Option, } impl BoatModels { /// Whether a boat of this wood (with or without a chest) can be drawn. @@ -175,6 +177,7 @@ impl BoatModels { Self { models, chest_models, + water_patch: document.and_then(|d| d.model("minecraft:boat#water_patch")), } } } @@ -785,6 +788,23 @@ impl Game<'_> { 0, out, ); + // BoatRenderer.submitTypeAdditions: the water patch hides the water + // inside the hull unless the boat is under water (RaftRenderer has none). + if let Some(patch) = self.boat_models.water_patch.as_ref() + && &*b.wood != "bamboo" + && !matches!(b.status, Status::UnderWater | Status::UnderFlowingWater) + { + horizon_client::mobs::render::draw( + patch, + base, + &Poses::new(patch), + uv, + 0xFFFF_FFFF, + packed, + horizon_client::gfx::WATER_MASK_OVERLAY, + out, + ); + } self.cull_entity_vertices(out, entity_start); } } diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index cdc7fa2d8..ec46120dd 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -223,6 +223,14 @@ impl Game<'_> { .riding .and_then(|id| self.mobs.iter().find(|m| m.id == id)) .map(|_| (1.0, 4.0)); + // AbstractBoat.positionRider turns a passenger by the boat's + // deltaRotation after its yRotO was saved, and LocalPlayer.getViewYRot + // interpolates a passenger's yaw: the boat's turn is spread over the + // frames of a tick. + let ride_turn = self + .riding + .and_then(|id| self.boats.iter().find(|b| b.id == id)) + .map_or(0.0, |b| b.delta_rotation); let entity = CameraEntity { position: [p.position.x, p.position.y, p.position.z], previous: [ @@ -235,7 +243,7 @@ impl Game<'_> { x_rot: self.pitch, y_rot: self.yaw, x_rot_o: self.pitch, - y_rot_o: self.yaw, + y_rot_o: self.yaw - ride_turn, eye_height: p.dimensions.eye_height, living: Some(LivingCamera { scale, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5141b6089..304352918 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -34,6 +34,7 @@ fn entity_shader() -> String { mod entity_batch; use entity_batch::EntityBatch; +pub use entity_batch::WATER_MASK_OVERLAY; /// Window.getAppropriateLineWidth, in framebuffer pixels. pub fn outline_width(width: u32) -> f32 { @@ -317,6 +318,8 @@ pub struct Renderer { crosshair_globals: wgpu::Buffer, entity_pipeline: wgpu::RenderPipeline, crumbling_pipeline: wgpu::RenderPipeline, + /// `RenderPipelines.WATER_MASK`: depth writes only, no colour. + water_mask_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, cloud_mesh: crate::clouds::Mesh, cloud_buffer: wgpu::Buffer, @@ -1539,7 +1542,16 @@ impl Renderer { step_mode: wgpu::VertexStepMode::Vertex, attributes: &entity_attributes, })]; - let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| { + #[allow(clippy::too_many_arguments)] + let entity_pipeline_with = |label, + cull_mode, + depth_write, + compare, + bias, + blend, + clouds, + fragment: &str, + write_mask| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), layout: Some(if clouds { @@ -1567,18 +1579,43 @@ impl Renderer { multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &entity_shader, - entry_point: Some("fs_entity"), + entry_point: Some(fragment), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), blend: Some(blend), - write_mask: wgpu::ColorWrites::ALL, + write_mask, })], }), multiview_mask: None, cache: None, }) }; + let entity_pipeline = |label, cull_mode, depth_write, compare, bias, blend, clouds| { + entity_pipeline_with( + label, + cull_mode, + depth_write, + compare, + bias, + blend, + clouds, + "fs_entity", + wgpu::ColorWrites::ALL, + ) + }; + // RenderPipelines.WATER_MASK: the boat's water patch writes depth only. + let water_mask_pipeline = entity_pipeline_with( + "Water mask", + None, + true, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + alpha_blend, + false, + "fs_water_mask", + wgpu::ColorWrites::empty(), + ); let crumbling_pipeline = entity_pipeline( "Breaking cracks", Some(wgpu::Face::Back), @@ -2058,6 +2095,7 @@ impl Renderer { crosshair_globals, entity_pipeline, crumbling_pipeline, + water_mask_pipeline, cloud_pipeline, cloud_mesh: Default::default(), cloud_buffer, @@ -3183,14 +3221,19 @@ impl Renderer { self.uploads .buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines)); } - let [entity_quads, crumbling_quads, translucent_crumbling_quads] = - self.entity_batch.update( - frame.entities, - frame.additive, - frame.hand, - frame.see_through, - ); - let world_quads = entity_quads + crumbling_quads + translucent_crumbling_quads; + let [ + entity_quads, + crumbling_quads, + translucent_crumbling_quads, + water_mask_quads, + ] = self.entity_batch.update( + frame.entities, + frame.additive, + frame.hand, + frame.see_through, + ); + let world_quads = + entity_quads + crumbling_quads + translucent_crumbling_quads + water_mask_quads; let cloud_quads = if let Some(input) = &frame.clouds { let (rebuilt, uniform) = crate::spans::time("clouds", || self.cloud_mesh.prepare(input)); @@ -3552,6 +3595,19 @@ impl Renderer { pass.draw_indexed(0..crumbling_quads * 6, (entity_quads * 4) as i32, 0..1); pass.set_bind_group(0, &self.group, &[]); } + // BoatRenderer's water patch (RenderTypes.waterMask): depth only, + // before translucent terrain, so no water shows inside the boat. + if water_mask_quads > 0 { + pass.set_pipeline(&self.water_mask_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..water_mask_quads * 6, + ((entity_quads + crumbling_quads + translucent_crumbling_quads) * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -4116,7 +4172,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1]); + assert_eq!(counts, [4, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index e7bfccb96..999113761 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -1,12 +1,19 @@ //! Stable entity material grouping with renderer-owned, reusable CPU scratch. use super::Vertex; +/// Entity materials by a quad's overlay (`Vertex::layer`), in draw order: +/// ordinary entities, breaking cracks (11), translucent breaking cracks (12) +/// and the boat water mask (13, `RenderPipelines.WATER_MASK`). +const MATERIALS: usize = 4; +/// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). +pub const WATER_MASK_OVERLAY: u32 = 13; + #[derive(Default)] pub(super) struct EntityBatch { // Quad indices avoid copying vertices twice while grouping materials. // Keep initialized high-water storage; local counts delimit active entries. // Each bucket can hold all quads, removing per-quad Vec growth checks. - buckets: [Vec; 3], + buckets: [Vec; MATERIALS], pub(super) combined: Vec, } @@ -17,18 +24,19 @@ impl EntityBatch { additive: &[Vertex], hand: &[Vertex], see_through: &[Vertex], - ) -> [u32; 3] { + ) -> [u32; MATERIALS] { let quads = entities.as_chunks::<4>().0; for bucket in &mut self.buckets { if bucket.len() < quads.len() { bucket.resize(quads.len(), 0); } } - let mut counts = [0usize; 3]; + let mut counts = [0usize; MATERIALS]; for (index, quad) in quads.iter().enumerate() { let material = match quad[0].layer { 11 => 1, 12 => 2, + WATER_MASK_OVERLAY => 3, _ => 0, }; self.buckets[material][counts[material]] = index; @@ -77,14 +85,15 @@ mod tests { entities: &[Vertex], additive: &[Vertex], hand: &[Vertex], - ) -> (Vec, [u32; 3]) { + ) -> (Vec, [u32; MATERIALS]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); - let mut counts = [0; 3]; - for (i, layer) in [0, 11, 12].into_iter().enumerate() { + let mut counts = [0; MATERIALS]; + for (i, layer) in [0, 11, 12, 13].into_iter().enumerate() { for quad in entities.as_chunks::<4>().0 { let material = match quad[0].layer { 11 => 11, 12 => 12, + 13 => 13, _ => 0, }; if material == layer { @@ -104,7 +113,7 @@ mod tests { pos: [index as f32, 2.0, 3.0], uv: [index as f32, 5.0], layer: if mixed { - [7, 11, 12, 4, 0][index / 4 % 5] + [7, 11, 12, 4, 13, 0][index / 4 % 6] } else { 0 }, From 1cca55b66724484fa27fdb8f0d5b357be963db91 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:34:13 +0200 Subject: [PATCH 004/115] Draw and collide blocks while a piston moves them Moving blocks are minecraft:moving_piston blocks with a block entity. The client drew nothing for them and gave them no collision, so pistons on a clock flickered and players walked through them (#935). The world now keeps a copy of the level's moving-piston block entities. SceneCollisions::moving_piston_shape returns their shape (PistonMovingBlockEntity.getCollisionShape, already in piston_shape), and game/moving_pistons.rs ports PistonHeadRenderer: the moved block at its interpolated offset, the moving head's short state, and a retracting piston's head and extended base. Entity pushing (moveCollidedEntities) is not ported yet. Fixes #935 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/collisions.rs | 29 ++++- crates/horizon-client/src/game.rs | 15 +++ crates/horizon-client/src/game/dispenser.rs | 6 +- .../horizon-client/src/game/moving_pistons.rs | 108 ++++++++++++++++++ crates/horizon-client/src/motion.rs | 62 ++++++++++ crates/horizon-client/src/world.rs | 4 + crates/horizon-world/src/block_collision.rs | 10 ++ crates/horizon-world/src/level/pistons.rs | 11 ++ 8 files changed, 241 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-client/src/game/moving_pistons.rs diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index a52f25ce7..67f5d6027 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,8 +15,9 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, + piston_shape::PistonCollisionWorld, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::{BlockRegistry, BlockTableFile}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, @@ -259,8 +260,30 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result> { Ok(None) } - fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result> { - Ok(None) + /// `MovingPistonBlock.getCollisionShape`: the block entity's moving shape + /// (`PistonMovingBlockEntity.getCollisionShape`), outside any push. + fn moving_piston_shape(&mut self, p: [i32; 3]) -> io::Result> { + let Some(&(_, piston)) = self.world.moving_pistons.iter().find(|(q, _)| *q == p) else { + return Ok(None); + }; + let binding = self.binding; + let Some(pistons) = binding.pistons() else { + return Ok(None); + }; + pistons + .collision_shape(self, p, piston, None) + .map(Some) + .map_err(io::Error::other) + } +} +impl PistonCollisionWorld for SceneCollisions<'_, '_> { + type Error = io::Error; + /// `BlockState.getCollisionShape(level, pos)` of the moved state. + fn collision_shape(&mut self, state: BlockStateId, p: [i32; 3]) -> io::Result { + let binding = self.binding; + binding + .collision_shape(self, state, p) + .map_err(io::Error::other) } } impl DynamicCollisionWorld for SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 4013bb04b..a6aacd219 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -89,6 +89,7 @@ mod mob_gear; mod mods; mod mount_menu; mod mounts; +mod moving_pistons; mod music; mod names; mod natural_spawning; @@ -2314,8 +2315,21 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + self.sync_moving_pistons(); self.process_level_events() } + /// Copies the moving-piston block entities into the world, where the + /// collision queries and the renderer read them. + fn sync_moving_pistons(&mut self) { + let pistons = &mut self.world.moving_pistons; + pistons.clear(); + pistons.extend( + self.block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), + ); + } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game /// events) happen before the next tick runs, as they do inline in vanilla. @@ -6465,6 +6479,7 @@ impl Game<'_> { vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); } } + self.moving_piston_geometry(camera, alpha, &mut out); self.tnt_geometry(camera, alpha, &mut out); self.painting_geometry(camera, &mut out); self.frame_geometry(camera, &mut out); diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index db3f523bc..b4e358d50 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -317,7 +317,11 @@ impl Game<'_> { .cloned() } /// The same block with other properties (`withProperty`). - fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { + pub(super) fn with_props( + &self, + state: BlockStateId, + props: &[(&str, &str)], + ) -> Option { let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs new file mode 100644 index 000000000..8b47483df --- /dev/null +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -0,0 +1,108 @@ +//! `PistonHeadRenderer`: while a piston moves them, blocks are +//! `minecraft:moving_piston` block entities (drawn as nothing by the chunk +//! mesher); this draws each moved block at its interpolated offset. +use super::Game; +use horizon_client::mesher::Vertex; +use horizon_world::{piston_shape::MovingPistonState, registry::BlockStateId}; + +impl Game<'_> { + /// `PistonHeadRenderer.extractRenderState` and `submit`. + pub(super) fn moving_piston_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let partial = alpha as f32; + for &(p, piston) in &self.world.moving_pistons { + let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { + continue; + }; + let step = piston.movement_direction().normal(); + let from = horizon_core::position::BlockPos::new( + p[0] - step[0], + p[1] - step[1], + p[2] - step[2], + ); + let offset = piston.interpolated_offset(partial); + let light = self.world.light(p[0], p[1], p[2]); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let corner = glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])); + let moved = corner + glam::Vec3::from_array(offset).as_dvec3(); + self.moving_block_vertices(block, from, moved - camera, packed, out); + if let Some(base) = base { + let at = horizon_core::position::BlockPos::new(p[0], p[1], p[2]); + self.moving_block_vertices(base, at, corner - camera, packed, out); + } + } + } + /// The moved block and, for a retracting piston, its extended base. + fn moving_piston_blocks( + &self, + piston: MovingPistonState, + partial: f32, + ) -> Option<(BlockStateId, Option)> { + let facts = self.res.facts(); + if facts.is_air(piston.moved_state) { + return None; + } + let progress = piston.interpolated_progress(partial); + let name = &*facts.get(piston.moved_state).name; + // Vanilla tests `progress <= 4.0`: a moving head is always drawn so. + if name == "minecraft:piston_head" { + let short = if progress <= 0.5 { "true" } else { "false" }; + return Some(( + self.with_props(piston.moved_state, &[("short", short)])?, + None, + )); + } + if piston.source && !piston.extending { + let registry = &self.pack.assets.registry; + let facing = registry + .state(piston.moved_state)? + .properties + .get("facing")? + .clone(); + let kind = if name == "minecraft:sticky_piston" { + "sticky" + } else { + "normal" + }; + let short = if progress >= 0.5 { "true" } else { "false" }; + let head = self.with_props( + registry.default_state("minecraft:piston_head")?, + &[("type", kind), ("facing", &facing), ("short", short)], + )?; + let base = self.with_props(piston.moved_state, &[("extended", "true")])?; + return Some((head, Some(base))); + } + Some((piston.moved_state, None)) + } + /// One `MovingBlockRenderState`: the baked model at `at` (camera-relative), + /// seeded by its block position and tinted like a falling block. + fn moving_block_vertices( + &self, + state: BlockStateId, + seed: horizon_core::position::BlockPos, + at: glam::DVec3, + light: u32, + out: &mut Vec, + ) { + let tint = self.particle_sprite(state).map(|(_, tint)| tint); + let start = out.len(); + self.block_model_vertices( + state, + horizon_core::random::position_seed(seed), + glam::Mat4::from_translation(at.as_vec3()), + light, + false, + out, + ); + if let Some(tint) = tint { + let tint = horizon_client::mobs::render::abgr(tint); + for vertex in &mut out[start..] { + vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint); + } + } + } +} diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 40f4d0657..03a92b20c 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -2128,6 +2128,68 @@ mod tests { assert!(player.position.y < 84.0); } + /// `MovingPistonBlock.getCollisionShape`: a block halfway through a push + /// up is solid at its moving position, so a player lands on it. + #[test] + fn a_player_lands_on_a_block_a_piston_is_moving() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); + let registry = assets.registry; + let moving = registry.default_state("minecraft:moving_piston").unwrap(); + let stone = registry.default_state("minecraft:stone").unwrap(); + scene.set(20, 4, 20, moving).unwrap(); + scene.moving_pistons.push(( + [20, 4, 20], + horizon_world::piston_shape::MovingPistonState { + moved_state: stone, + direction: horizon_core::geometry::Direction::Up, + extending: true, + source: false, + progress: 0.5, + previous_progress: 0.0, + }, + )); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 6.0, 20.5)).unwrap(); + for _ in 0..30 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert!(player.ground.on_ground); + assert_eq!(player.position.y, 4.5); + // Once the block entity is gone, the moving_piston block has no shape. + scene.moving_pistons.clear(); + for _ in 0..10 { + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(Default::default()) + .unwrap(); + } + assert_eq!(player.position.y, 4.0); + } + #[test] fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 4a80a7fcd..3b2920ade 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -93,6 +93,9 @@ pub struct World { pub light_log: Option>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections, + /// The moving-piston block entities of the level, by position, copied + /// from the block ticks after each tick: collision and rendering read them. + pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, } /// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] @@ -178,6 +181,7 @@ impl World { weather: Weather::default(), block_log: None, light_log: None, + moving_pistons: Vec::new(), pois: Default::default(), } } diff --git a/crates/horizon-world/src/block_collision.rs b/crates/horizon-world/src/block_collision.rs index b84db5def..3770a1a0f 100644 --- a/crates/horizon-world/src/block_collision.rs +++ b/crates/horizon-world/src/block_collision.rs @@ -6,6 +6,7 @@ use crate::{ collision_context::CollisionContext, dynamic_support::{DynamicSupport, DynamicSupportError, DynamicSupportWorld}, liquid_collision::{LiquidCollision, LiquidCollisionWorld}, + piston_shape::PistonBlockBindings, powder_snow_collision::{PowderSnowWorld, powder_snow_collision_shape}, registry::{BlockRegistry, BlockStateId}, }; @@ -79,6 +80,9 @@ pub struct BlockCollisionRegistry<'r> { dynamic: HashMap, contextual: HashMap, scan_flags: Vec, + /// Piston and piston-head states for moving-piston collision; None in + /// registries without pistons. + pistons: Option>, } enum ContextualRule { Scaffolding(ScaffoldingCollision), @@ -122,16 +126,22 @@ impl<'r> BlockCollisionRegistry<'r> { } } } + let pistons = PistonBlockBindings::new(cached.registry()).ok(); Ok(Self { cached, dynamic, contextual, scan_flags, + pistons, }) } pub fn registry(&self) -> &'r BlockRegistry { self.cached.registry() } + /// The piston states behind `PistonMovingBlockEntity.getCollisionShape`. + pub fn pistons(&self) -> Option<&PistonBlockBindings<'r>> { + self.pistons.as_ref() + } pub fn cached_shapes(&self) -> &CachedCollisionRegistry<'r> { &self.cached } diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index fa5b7989c..648d6d543 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -31,6 +31,17 @@ pub struct MovingPiston { pub id: u64, } impl MovingPiston { + /// What collision and rendering need from this block entity. + pub fn shape_state(&self) -> crate::piston_shape::MovingPistonState { + crate::piston_shape::MovingPistonState { + moved_state: self.moved_state, + direction: self.direction, + extending: self.extending, + source: self.source, + progress: self.progress, + previous_progress: self.progress_o, + } + } pub fn movement_direction(&self) -> Direction { if self.extending { self.direction From 082cc278afb22d1196bfc8b698a4ce1ae9510984 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:52:08 +0200 Subject: [PATCH 005/115] Audio: pan like OpenAL Soft's stereo output, not at full gain on both sides A centred mono source played at full gain on each channel; OpenAL Soft (vanilla's LWJGL build, HRTF off) renders stereo pairwise: 0.596 per side ahead, 0.404 behind, 0.5 above or below. Explosions were 4.5 dB louder than vanilla. Pan with the camera's forward and up vectors, play a mono output unpanned, and release the limiter over 0.2 s like OpenAL Soft's. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 151 +++++++++++++++++++++++++---- crates/horizon-client/src/game.rs | 2 +- 2 files changed, 131 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 62bdc041f..14de6efc7 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -2,7 +2,7 @@ //! small mixer standing in for OpenAL: one channel per source with its gain, //! pitch, linear distance attenuation (`AL_LINEAR_DISTANCE`, reference 0, //! rolloff 1), looping, relative flag and source state, Ogg/Vorbis decoding -//! (streams on a worker thread) and stereo panning. +//! (streams on a worker thread) and OpenAL Soft's stereo panning. use crate::Result; use crate::sound_engine::{ Attenuation, Backend, Bound, ChannelId, InstanceId, PlayResult, SoundEngine, SoundInstance, @@ -45,6 +45,7 @@ struct Mixer { channels: HashMap, listener: [f64; 3], listener_yaw: f32, + listener_pitch: f32, limiter_peak: f32, } /// A sound the player could have heard (`SoundEventListener.onPlaySound`): @@ -331,6 +332,32 @@ impl Backend for MixerBackend { .unwrap_or(true) } } +/// OpenAL Soft's stereo gains `[left, right]` for a mono source in a +/// direction given in listener space (right, up, forward; any length). +/// Vanilla's context (`Library.createAttributes`: HRTF off) on a stereo +/// output renders pairwise: front azimuths are stretched by 1.5 +/// (`ScaleAzimuthFront`, so 60 degrees off-centre pans fully) and the +/// direction is decoded by the first-order stereo decoder, 0.5 W, 0.5 Y and +/// 0.0957 X in this scaling. A centred source gets 0.596 on each side, one +/// behind 0.404, one above or below 0.5, one at the source's own position +/// is panned to the front. Matches OpenAL Soft 1.25.2 (LWJGL 3.4.3, the +/// pinned client's) rendered through `ALC_SOFT_loopback` within 1e-5. +fn stereo_gains(right: f32, up: f32, forward: f32) -> [f32; 2] { + let length = (right * right + up * up + forward * forward).sqrt(); + if length <= f32::EPSILON { + return stereo_gains(0.0, 0.0, 1.0); + } + let elevation = (up / length).clamp(-1.0, 1.0).asin(); + let mut azimuth = right.atan2(forward); + if azimuth.abs() < std::f32::consts::FRAC_PI_2 { + azimuth = (azimuth.abs() * 1.5) + .min(std::f32::consts::FRAC_PI_2) + .copysign(azimuth); + } + let side = azimuth.sin() * elevation.cos(); + let front = azimuth.cos() * elevation.cos() * 0.095_660_8; + [0.5 - 0.5 * side + front, 0.5 + 0.5 * side + front] +} /// The gain OpenAL applies for distance (`AL_LINEAR_DISTANCE` with reference /// distance 0 and rolloff 1: the distance clamps to the max distance). fn distance_gain(linear: Option, distance: f32) -> f32 { @@ -345,9 +372,30 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; - let yaw = mixer.listener_yaw.to_radians(); + // The camera's forward and up vectors (`Camera.forwardVector`/`upVector`) + // and OpenAL's right = forward x up. + let (yaw, pitch) = ( + f64::from(mixer.listener_yaw.to_radians()), + f64::from(mixer.listener_pitch.to_radians()), + ); + let forward = [ + -yaw.sin() * pitch.cos(), + -pitch.sin(), + yaw.cos() * pitch.cos(), + ]; + let up = [ + -yaw.sin() * pitch.sin(), + pitch.cos(), + yaw.cos() * pitch.sin(), + ]; + let right = [ + forward[1] * up[2] - forward[2] * up[1], + forward[2] * up[0] - forward[0] * up[2], + forward[0] * up[1] - forward[1] * up[0], + ]; + let dot = |a: [f64; 3], b: [f64; 3]| (a[0] * b[0] + a[1] * b[1] + a[2] * b[2]) as f32; // Gains and pans per source for this buffer. - let mut voices: Vec<(ChannelId, f32, f32, f64)> = Vec::new(); + let mut voices: Vec<(ChannelId, [f32; 3], f64)> = Vec::new(); for (id, c) in &mixer.channels { let Some((_, source_rate)) = &c.samples else { continue; @@ -366,19 +414,17 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { }; let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt() as f32; let gain = c.gain.clamp(0.0, 1.0) * distance_gain(c.linear, distance); - // The listener's right vector for a Minecraft yaw. - let side = if c.relative { - (d[0] as f32) / distance.max(0.001) + // Relative sources are already in OpenAL's listener space (-Z ahead). + let [left, right] = if c.relative { + stereo_gains(d[0] as f32, d[1] as f32, -d[2] as f32) } else { - (-(yaw.cos()) as f64 * d[0] - (yaw.sin()) as f64 * d[2]) as f32 / distance.max(0.001) - }; - let pan = side.clamp(-1.0, 1.0); - let left = gain * (1.0 - pan.max(0.0) * 0.6); - let right = gain * (1.0 + pan.min(0.0) * 0.6); + stereo_gains(dot(d, right), dot(d, up), dot(d, forward)) + } + .map(|pan| gain * pan); let step = f64::from(*source_rate) / f64::from(rate) * f64::from(c.pitch.max(0.0)); - voices.push((*id, left, right, step)); + voices.push((*id, [left, right, gain], step)); } - for (id, left, right, step) in voices { + for (id, [left, right, gain], step) in voices { let Some(c) = mixer.channels.get_mut(&id) else { continue; }; @@ -402,16 +448,19 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { frame[0] += s * left; frame[1] += s * right; } else { - frame[0] += s * (left + right) / 2.0; + // A mono output has no panning: the source's own gain. + frame[0] += s * gain; } c.position += step; } } // Limit the whole buffer together, preserving waveform and stereo balance - // instead of flattening each overloaded sample; release over 50 ms. + // instead of flattening each overloaded sample; release over 200 ms + // (OpenAL Soft's output limiter, `ALC_OUTPUT_LIMITER_SOFT`, releases + // over 0.2 s). let peak = data.iter().fold(1.0f32, |peak, s| peak.max(s.abs())); mixer.limiter_peak = mixer.limiter_peak.max(peak); - let release = (-1.0 / (0.05 * rate as f32)).exp(); + let release = (-1.0 / (0.2 * rate as f32)).exp(); for frame in data.chunks_mut(channels) { let gain = mixer.limiter_peak.recip(); for s in frame { @@ -591,13 +640,15 @@ impl Audio { backend: &mut self.backend, } } - /// `SoundManager.updateSource`: the camera position and yaw. - pub fn set_listener(&mut self, position: [f64; 3], yaw: f32) { + /// `SoundManager.updateSource`: the camera position and rotation + /// (`Listener.setTransform` takes its forward and up vectors). + pub fn set_listener(&mut self, position: [f64; 3], yaw: f32, pitch: f32) { self.listener = position; self.listener_yaw = yaw; if let Ok(mut m) = self.backend.mixer.lock() { m.listener = position; m.listener_yaw = yaw; + m.listener_pitch = pitch; } } /// Sync the volume options, refreshing the categories that changed @@ -908,8 +959,9 @@ mod tests { } let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); + // West of a listener facing south: fully on the right. for (frame, sample) in data.as_chunks::<2>().0.iter().zip(wave) { - assert!((frame[0] - sample * 0.4).abs() < 1e-6, "{frame:?}"); + assert!(frame[0].abs() < 1e-6, "{frame:?}"); assert!((frame[1] - sample).abs() < 1e-6, "{frame:?}"); } assert!(data.iter().all(|s| s.abs() <= 1.0)); @@ -920,9 +972,10 @@ mod tests { let mut m = Mixer::default(); m.channels .insert(1, channel(vec![0.25; 2], None, [0.0; 3], true)); + let quiet = 0.25 * stereo_gains(0.0, 0.0, 1.0)[0]; let mut data = [0.0; 16]; mix(&mut m, &mut data, 2, 48_000); - assert_eq!(data, [0.25; 16]); + assert_eq!(data, [quiet; 16]); for id in 2..=5 { m.channels @@ -935,7 +988,7 @@ mod tests { mix(&mut m, &mut recovery, 2, 48_000); assert!(recovery[0] > 0.0 && recovery[0] < 0.1); assert!(recovery.windows(2).all(|w| w[1] >= w[0])); - assert_eq!(*recovery.last().unwrap(), 0.25); + assert_eq!(*recovery.last().unwrap(), quiet); } #[test] @@ -953,4 +1006,60 @@ mod tests { let first = data[0] + data[1]; assert!(first > 1.4 && first < 3.1, "{first}"); } + + #[test] + fn stereo_panning_matches_openal_soft() { + // OpenAL Soft 1.25.2 (LWJGL 3.4.3's macOS build), stereo loopback + // device with vanilla's attributes, 1 kHz sine 4 blocks away. + let cases = [ + ((0.0, 0.0, 1.0), [0.5957, 0.5957]), + ((-1.0, 0.0, 0.0), [1.0, 0.0]), + ((1.0, 0.0, 0.0), [0.0, 1.0]), + ((0.0, 0.0, -1.0), [0.4043, 0.4043]), + ((0.0, 1.0, 0.0), [0.5, 0.5]), + ((0.0, -1.0, 0.0), [0.5, 0.5]), + ((-1.0, 0.0, 1.0), [0.9985, 0.0747]), + ((-1.0, 0.0, -1.0), [0.7859, 0.0788]), + ((0.0, 0.0, 0.0), [0.5957, 0.5957]), + ]; + for ((right, up, forward), expected) in cases { + let gains = stereo_gains(right, up, forward); + for (g, e) in gains.into_iter().zip(expected) { + assert!((g - e).abs() < 1e-4, "{right} {up} {forward}: {gains:?}"); + } + } + } + + #[test] + fn panning_follows_the_camera_rotation() { + let gains = |yaw: f32, pitch: f32, at: [f32; 3]| { + let mut m = Mixer { + listener_yaw: yaw, + listener_pitch: pitch, + ..Mixer::default() + }; + m.channels.insert(1, channel(vec![1.0; 4], None, at, true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 2, 48_000); + data + }; + let close = + |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-4 && (a[1] - b[1]).abs() < 1e-4; + // Facing south (yaw 0), east is on the left; facing north, on the right. + assert!(close(gains(0.0, 0.0, [1.0, 0.0, 0.0]), [1.0, 0.0])); + assert!(close(gains(180.0, 0.0, [1.0, 0.0, 0.0]), [0.0, 1.0])); + // Looking straight down, a source below is ahead and one south is above. + assert!(close(gains(0.0, 90.0, [0.0, -1.0, 0.0]), [0.5957, 0.5957])); + assert!(close(gains(0.0, 90.0, [0.0, 0.0, 1.0]), [0.5, 0.5])); + } + + #[test] + fn a_mono_output_plays_sources_unpanned() { + let mut m = Mixer::default(); + m.channels + .insert(1, channel(vec![0.5; 4], None, [0.0, 0.0, -3.0], true)); + let mut data = [0.0; 2]; + mix(&mut m, &mut data, 1, 48_000); + assert_eq!(data, [0.5; 2]); + } } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 82be49ed7..9e7eba481 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9255,7 +9255,7 @@ impl Game<'_> { ), }; self.audio - .set_listener([camera.x, camera.y, camera.z], view_yaw); + .set_listener([camera.x, camera.y, camera.z], view_yaw, view_pitch); let block = [ camera.x.floor() as i32, camera.y.floor() as i32, From 30cdd6298a6b13b51a34d59b30b80825f11ae7ef Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:20:13 +0200 Subject: [PATCH 006/115] Version sources: a release build says its version (0.2.3), not 0.1.0 or a folder name release.yml builds every game release with HORIZON_VERSION, the tag without its v (docs/versioning.md), as launcher.yml already does for the launcher: no version-bump commits. - horizon_core::release::{RELEASE, VERSION}: the built-in version, or Cargo.toml's for a build from source. (horizon_core::version stays Minecraft's, generated by gen_version_consts.py.) - horizon-server and horizon-prepare --version, the server's /api/v1/status, horizon-ctl's MCP serverInfo and the "Horizon/" user agents use it; they all said 0.1.0. - The client's crash reports and telemetry say v0.2.3 from the built-in version wherever the game is installed; releases from before 0.2 (no version built in) still read the launcher's folder name. - The launcher's benchmark telemetry used Cargo.toml's version instead of the release's. - release.yml checks that horizon-prepare and horizon-server --version say the release's version. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/release.yml | 17 ++++++++-- crates/horizon-client/src/auth.rs | 2 +- .../horizon-client/src/bin/horizon-ctl/mcp.rs | 2 +- crates/horizon-client/src/crash.rs | 29 +++++++++++++---- crates/horizon-client/src/telemetry.rs | 2 +- crates/horizon-core/src/lib.rs | 1 + crates/horizon-core/src/release.rs | 32 +++++++++++++++++++ crates/horizon-prepare/src/main.rs | 9 +++++- crates/horizon-server-files/src/profiles.rs | 4 +-- crates/horizon-server/src/api.rs | 2 +- crates/horizon-server/src/main.rs | 9 +++++- launcher/src/perf.rs | 4 +-- 12 files changed, 94 insertions(+), 19 deletions(-) create mode 100644 crates/horizon-core/src/release.rs diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2c4e13cf2..d3631a851 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -44,6 +44,7 @@ jobs: outputs: release: ${{ steps.decide.outputs.release }} tag: ${{ steps.decide.outputs.tag }} + version: ${{ steps.decide.outputs.version }} head: ${{ steps.decide.outputs.head }} dry_run: ${{ steps.mode.outputs.dry_run }} steps: @@ -64,6 +65,9 @@ jobs: run: | python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY" + # The version the programs are built with (docs/versioning.md): the tag without its v. + tag=$(jq -r '.tag' decision.json) + echo "version=${tag#v}" >> "$GITHUB_OUTPUT" # A dry run builds whatever the decision, to test the builds. if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi @@ -98,6 +102,9 @@ jobs: timeout-minutes: ${{ matrix.mac && 60 || 40 }} env: RUSTFLAGS: ${{ matrix.rustflags }} + # The release's version, built in (horizon_core::release): --version, user agents, crash reports and + # telemetry say it. No version-bump commits. + HORIZON_VERSION: ${{ needs.decide.outputs.version }} defaults: run: shell: bash @@ -161,9 +168,13 @@ jobs: bin=target/release "$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources' "$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null - "$bin/horizon-prepare${{ matrix.exe }}" --version "$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir' - "$bin/horizon-server${{ matrix.exe }}" --version + # The version is the release's. + for binary in horizon-prepare horizon-server; do + out=$("$bin/$binary${{ matrix.exe }}" --version | tr -d '\r') + echo "$out" + [[ "$out" == "$binary $HORIZON_VERSION" ]] || { echo "::error::expected $binary $HORIZON_VERSION"; exit 1; } + done - name: Tools from the runner if: runner.environment == 'self-hosted' run: bash tools/ci/runner-env.sh @@ -244,7 +255,7 @@ jobs: folder="dist/${{ matrix.server_dir }}" python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" "$folder/horizon-engine" --help | grep -q -- '--resources' - "$folder/horizon-server" --version + [[ "$("$folder/horizon-server" --version)" == "horizon-server $HORIZON_VERSION" ]] cd dist rm -f "${{ matrix.server_asset }}" tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index a6dfab1ee..b899ea5d5 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -174,7 +174,7 @@ pub fn discovery_url() -> String { fn agent() -> ureq::Agent { ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build() } diff --git a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs index fa60b38f9..8d67953a5 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/mcp.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/mcp.rs @@ -130,7 +130,7 @@ impl Session { "initialize" => Ok(json!({ "protocolVersion": params.get("protocolVersion").and_then(Value::as_str).unwrap_or(PROTOCOL), "capabilities": { "tools": {} }, - "serverInfo": { "name": "horizon-ctl", "version": env!("CARGO_PKG_VERSION") }, + "serverInfo": { "name": "horizon-ctl", "version": horizon_core::release::VERSION }, "instructions": "Play Horizon, a Rust reimplementation of Minecraft Java Edition. Start with launch (it finds the game installed by the Horizon launcher and opens or creates a world), then read the world with state, inventory, screen, entities and find_block, and act with goto, look_at_block, break, place, interact, click_slot and click_button. Actions block until they finish and report what happened. Coordinates are block coordinates; yaw 0 faces south (+Z).", })), "ping" => Ok(json!({})), diff --git a/crates/horizon-client/src/crash.rs b/crates/horizon-client/src/crash.rs index 8ee5803b5..e147bfb4c 100644 --- a/crates/horizon-client/src/crash.rs +++ b/crates/horizon-client/src/crash.rs @@ -105,18 +105,23 @@ impl Report { } } -/// The release tag (the launcher installs each build in a folder named after it) and the client's -/// own version, or just the latter. +/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's +/// crate version; for a build from source, that version alone. pub fn version() -> String { let version = env!("CARGO_PKG_VERSION"); - match release_tag() { - Some(tag) => format!("{tag} (client {version})"), - None => version.to_owned(), + match (horizon_core::release::RELEASE, release_tag()) { + (Some(_), Some(tag)) => tag, + (None, Some(tag)) => format!("{tag} (client {version})"), + (_, None) => version.to_owned(), } } -/// The release this binary came with: launcher installs live in a folder named after the tag. +/// The release this binary came with: the version release.yml built in (docs/versioning.md), else +/// the folder the launcher installed it in, named after the tag (releases from before 0.2). pub fn release_tag() -> Option { + if let Some(version) = horizon_core::release::RELEASE { + return Some(format!("v{version}")); + } let exe = std::env::current_exe().ok()?; let folder = exe.parent()?.file_name()?.to_str()?; (folder.starts_with('v') && folder[1..].starts_with(|c: char| c.is_ascii_digit())) @@ -517,6 +522,18 @@ pub fn debug_crash_after() -> Option { mod tests { use super::*; + #[test] + fn a_release_reports_its_built_in_version() { + // release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed. + match horizon_core::release::RELEASE { + Some(version) => { + assert_eq!(release_tag(), Some(format!("v{version}"))); + assert_eq!(super::version(), format!("v{version}")); + } + None => assert!(release_tag().is_none() || super::version().contains("(client ")), + } + } + fn report() -> Report { Report { time: chrono::TimeZone::with_ymd_and_hms(&Local, 2026, 10, 14, 9, 5, 7).unwrap(), diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs index d0140f941..2010df04a 100644 --- a/crates/horizon-client/src/telemetry.rs +++ b/crates/horizon-client/src/telemetry.rs @@ -75,7 +75,7 @@ pub fn system() -> System { system } -/// The release (`v2026.10.15`), or the client's crate version for a build from source. +/// The release (`v0.2.3`), or the client's crate version for a build from source. pub fn version() -> String { crate::crash::release_tag().unwrap_or_else(|| format!("dev {}", env!("CARGO_PKG_VERSION"))) } diff --git a/crates/horizon-core/src/lib.rs b/crates/horizon-core/src/lib.rs index c8077b327..9034ef2eb 100644 --- a/crates/horizon-core/src/lib.rs +++ b/crates/horizon-core/src/lib.rs @@ -17,6 +17,7 @@ pub mod storage; pub mod text; pub mod ticks; +pub mod release; pub mod version; pub use version::VANILLA_VERSION; diff --git a/crates/horizon-core/src/release.rs b/crates/horizon-core/src/release.rs new file mode 100644 index 000000000..54a3cb94e --- /dev/null +++ b/crates/horizon-core/src/release.rs @@ -0,0 +1,32 @@ +//! Which Horizon release this build is (docs/versioning.md). Not Minecraft's version: that is +//! [`crate::version`], generated from the game's own files. + +/// The release's version (`0.2.3`, no `v`): release.yml builds every release with `HORIZON_VERSION` +/// set from its tag, so there are no version-bump commits. None for a build from source. +pub const RELEASE: Option<&str> = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => Some(version), + _ => None, +}; + +/// [`RELEASE`], or this crate's Cargo.toml version for a build from source: what `--version`, user +/// agents and reports say. +pub const VERSION: &str = match RELEASE { + Some(version) => version, + None => env!("CARGO_PKG_VERSION"), +}; + +#[cfg(test)] +mod tests { + #[test] + fn the_version_is_the_release_or_the_crate() { + assert_eq!( + super::RELEASE, + option_env!("HORIZON_VERSION").filter(|v| !v.is_empty()) + ); + assert_eq!( + super::VERSION, + super::RELEASE.unwrap_or(env!("CARGO_PKG_VERSION")) + ); + assert!(!super::VERSION.starts_with('v')); + } +} diff --git a/crates/horizon-prepare/src/main.rs b/crates/horizon-prepare/src/main.rs index 0e8adc927..71b7a40cc 100644 --- a/crates/horizon-prepare/src/main.rs +++ b/crates/horizon-prepare/src/main.rs @@ -5,6 +5,13 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; +/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag +/// (docs/versioning.md); a build from source says Cargo.toml's. +const VERSION: &str = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => version, + _ => env!("CARGO_PKG_VERSION"), +}; + const HELP: &str = "\ horizon-prepare: prepare Horizon's resources from your own Minecraft Java Edition @@ -92,7 +99,7 @@ fn main() -> ExitCode { return ExitCode::SUCCESS; } "-V" | "--version" => { - println!("horizon-prepare {}", env!("CARGO_PKG_VERSION")); + println!("horizon-prepare {VERSION}"); return ExitCode::SUCCESS; } _ => Err(format!("unrecognized argument: {text}")), diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs index 3e16e2a41..3f7e2e509 100644 --- a/crates/horizon-server-files/src/profiles.rs +++ b/crates/horizon-server-files/src/profiles.rs @@ -45,7 +45,7 @@ pub fn resolve(name: &str, online: bool) -> Option { pub fn find_by_name(discovery: &str, name: &str) -> Option { let agent = ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build(); let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?; let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase()); @@ -61,7 +61,7 @@ pub fn fetch_profile_key_keys(discovery: &str) -> Result, &'st const FAILED: &str = "Failed to request Minecraft Services public key"; let agent = ureq::AgentBuilder::new() .timeout(Duration::from_secs(15)) - .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .user_agent(&format!("Horizon/{}", horizon_core::release::VERSION)) .build(); let get = |url: &str| agent.get(url).call().ok()?.into_string().ok(); let doc = get(discovery) diff --git a/crates/horizon-server/src/api.rs b/crates/horizon-server/src/api.rs index 03f7ae079..c9e553fab 100644 --- a/crates/horizon-server/src/api.rs +++ b/crates/horizon-server/src/api.rs @@ -286,7 +286,7 @@ fn status(shared: &Shared) -> Value { let state = shared.state.lock().unwrap(); json!({ "phase": state.phase.name(), - "version": env!("CARGO_PKG_VERSION"), + "version": crate::VERSION, "pid": std::process::id(), "uptime_seconds": shared.started.elapsed().as_secs(), "engine_pid": state.engine_pid, diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index 627961d81..b4512530c 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -18,6 +18,13 @@ mod update; use std::{path::PathBuf, process::ExitCode}; +/// This release's version: release.yml builds it with `HORIZON_VERSION` from the tag +/// (docs/versioning.md); a build from source says Cargo.toml's. +const VERSION: &str = match option_env!("HORIZON_VERSION") { + Some(version) if !version.is_empty() => version, + _ => env!("CARGO_PKG_VERSION"), +}; + const HELP: &str = "\ horizon-server: host a Horizon (Minecraft Java Edition 26.3) server @@ -86,7 +93,7 @@ fn main() -> ExitCode { Ok(()) } Some("version" | "-V" | "--version") => { - println!("horizon-server {}", env!("CARGO_PKG_VERSION")); + println!("horizon-server {VERSION}"); Ok(()) } Some("init") => init_answers(&args[1..]).and_then(|a| init::run(&dir, a)), diff --git a/launcher/src/perf.rs b/launcher/src/perf.rs index 864f6cfa0..7d652283f 100644 --- a/launcher/src/perf.rs +++ b/launcher/src/perf.rs @@ -307,7 +307,7 @@ pub fn benchmark(repeats: usize) -> Result { if let Ok(data) = serde_json::to_value(report.for_upload()) { let item = horizon_telemetry::Item::new( horizon_telemetry::Source::Launcher, - env!("CARGO_PKG_VERSION"), + crate::backend::VERSION, horizon_telemetry::Payload::Benchmark(data), ); let _ = horizon_telemetry::outbox::push(&crate::backend::game_home(), &item); @@ -320,7 +320,7 @@ pub fn benchmark(repeats: usize) -> Result { fn app() -> App { App { name: "horizon-launcher".into(), - version: env!("CARGO_PKG_VERSION").into(), + version: crate::backend::VERSION.into(), ..App::default() } } From f2f3fb6ede37c0431ccead98ee65f54e44e1eb23 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:00:07 +0200 Subject: [PATCH 007/115] fix: the ender dragon fight runs on server levels On a dedicated server (and single player's server thread) the End is ticked with no local player, and `tick_fight` returned before spawning the dragon: players in the End found crystals but never a dragon. - The fight finds its players as `EnderDragonFight.updatePlayers` does, every 20 ticks: every player alive within 192 blocks of (0, 128, 0), the host and the network players in the level alike. Scanning the state, the respawn sequence, `createNewDragon` and the crystal count run while it has one; the dragon and crystals tick whenever the End does. - The dragon is tracked to network players (`minecraft:ender_dragon`, its health and `DATA_PHASE` as vanilla pairs them, no attribute instances) and reserves its eight part ids after its own, as `EnderDragon`'s constructor does, so clients can attack the parts; a network player's attack on a part or an end crystal is aimed at it. tools/test_server_dragon_parity.py sends a lone vanilla-codec client to the End of vanilla's dedicated server and of Horizon's: the fight starts and the dragon is tracked with the same spawn data, synched data entries and attributes. VanillaProtocolClient's entity mode answers a scene's teleport with the acceptance alone, as the 26.3 client does. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 618db927d93bbcf7f3669ad0d630377c4646729d) --- crates/horizon-client/src/game/dragon.rs | 134 +++++++++++++--- crates/horizon-client/src/game/lan_actions.rs | 23 ++- .../horizon-client/src/game/lan_entities.rs | 8 + .../parity/VanillaProtocolClient.java | 4 +- tools/test_server_dragon_parity.py | 151 ++++++++++++++++++ 5 files changed, 287 insertions(+), 33 deletions(-) create mode 100644 tools/test_server_dragon_parity.py diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index d2413e45b..db7495ea4 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -37,6 +37,10 @@ pub(super) struct Fight { exit_portal: Option<[i32; 3]>, alive_crystals: i32, crystal_scan: i32, + /// `ticksSinceLastPlayerScan`, and whether the last scan found a player + /// for the fight (`dragonEvent.getPlayers()` is not empty). + player_scan: i32, + players: bool, /// The spikes' crystals have been placed (worldgen does not place entities here). crystals_placed: bool, /// The respawn sequence (`DragonRespawnStage`) and its tick count. @@ -239,6 +243,9 @@ impl Phase { } } pub(super) struct Dragon { + /// `Entity.id` once tracked to guests (0 before); its parts take the + /// eight ids after it (`EnderDragon`'s constructor reserves them). + pub id: u32, pub position: Vec3, pub previous: Vec3, velocity: Vec3, @@ -284,6 +291,7 @@ const ADJACENCY: [u32; 24] = [ impl Dragon { fn new(position: Vec3, yaw: f32, seed: i64) -> Self { Self { + id: 0, position, previous: position, velocity: Vec3::ZERO, @@ -422,6 +430,8 @@ impl Game<'_> { Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), _ => None, }, + // The first tick scans for players. + player_scan: 21, ..Default::default() }; if fight.gateways.is_empty() { @@ -495,45 +505,67 @@ impl Game<'_> { fn arena_loaded(&self) -> bool { (-2..=1).all(|cz| (-2..=1).all(|cx| self.streaming.is_lit(cx, cz))) } - /// `EnderDragonFight.tick` while the player is in the End. + /// `EnderDragonFight.validPlayer`: the players alive within 192 blocks of + /// (0, 128, 0), the host and the guests in the level alike. + fn fight_has_players(&self) -> bool { + let near = + |p: [f64; 3]| p[0].powi(2) + (p[1] - 128.0).powi(2) + p[2].powi(2) <= 192.0 * 192.0; + let host = self.player.as_ref().is_some_and(|p| { + !p.health.dead_or_dying() && near([p.position.x, p.position.y, p.position.z]) + }); + host || self.lan.as_ref().is_some_and(|h| { + h.hub + .guests + .iter() + .any(|g| h.hub.here(g) && g.loaded && !g.dead && near(g.position)) + }) + } + /// `EnderDragonFight.tick` and the fight's entities, while the End is + /// ticked (in place for its player, or on a server with players in it). pub(super) fn tick_fight(&mut self) { if self.dim != Dim::End || self.travelling.is_some() { return; } self.load_fight(); + // updatePlayers, every 20 ticks. + self.fight.player_scan += 1; + if self.fight.player_scan >= 20 { + self.fight.player_scan = 0; + self.fight.players = self.fight_has_players(); + } if !self.arena_loaded() { return; } - if self.fight.needs_scan { - // scanState: a missing exit portal means a fight in progress. - self.fight.previously_killed = self.end_portal_active(); - if !self.fight.previously_killed { - self.fight.killed = false; - } - self.fight.needs_scan = false; - self.fight.dirty = true; - } if !self.fight.crystals_placed { self.place_spike_crystals(); self.fight.crystals_placed = true; self.fight.dirty = true; } - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let near = p.x.powi(2) + (p.y - 128.0).powi(2) + p.z.powi(2) <= 192.0 * 192.0; - if !self.fight.killed && near && self.dragon.is_none() { - // createNewDragon: over the podium, holding pattern, a random yaw. - let yaw = self.world.random.next_float() * 360.0; - let seed = self.world.random.next_long(); - self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); - } - if self.fight.respawn.is_some() { - self.tick_respawn(); - } - self.fight.crystal_scan += 1; - if self.fight.crystal_scan >= 100 { - self.count_crystals(); + if self.fight.players { + if self.fight.needs_scan { + // scanState: a missing exit portal means a fight in progress. + self.fight.previously_killed = self.end_portal_active(); + if !self.fight.previously_killed { + self.fight.killed = false; + } + self.fight.needs_scan = false; + self.fight.dirty = true; + } + if self.fight.respawn.is_some() { + self.tick_respawn(); + } + if !self.fight.killed { + if self.dragon.is_none() { + // createNewDragon: over the podium, holding pattern, a random yaw. + let yaw = self.world.random.next_float() * 360.0; + let seed = self.world.random.next_long(); + self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); + } + self.fight.crystal_scan += 1; + if self.fight.crystal_scan >= 100 { + self.count_crystals(); + } + } } self.tick_crystals(); self.tick_dragon(); @@ -665,6 +697,21 @@ impl Game<'_> { } out } + /// The box of the dragon part or end crystal guests know as entity `id` + /// (`EnderDragonPart`s follow the dragon's id). + pub(super) fn tracked_special_box(&self, id: i32) -> Option { + let id = u32::try_from(id).ok().filter(|&id| id != 0)?; + if let Some(d) = self.dragon.as_ref().filter(|d| d.alive() && d.id != 0) + && (d.id + 1..=d.id + 8).contains(&id) + { + return Some(d.part_box((id - d.id - 1) as usize)); + } + let i = self.crystals.iter().position(|c| c.id == id)?; + self.special_targets() + .into_iter() + .find(|(s, _)| *s == CRYSTAL_IDS + i as u32) + .map(|(_, b)| b) + } /// Damage to a special id (from projectiles and melee). pub(super) fn hit_special(&mut self, id: u32, amount: f32, by_player: bool) { if id >= CRYSTAL_IDS { @@ -2355,6 +2402,41 @@ impl Game<'_> { } } } +impl Game<'_> { + /// The dragon as guests track it (`EnderDragon.getAddEntityPacket` and + /// the synched data that differs from the defaults: its health, defined + /// as 1, and `DATA_PHASE`, defined as hovering). Vanilla pairs it with no + /// attribute instances. + pub(super) fn lan_dragon_state(&self) -> Option { + use horizon_protocol::entity_data::{Value, serializer}; + let d = self.dragon.as_ref().filter(|d| d.id != 0)?; + let mut meta = Vec::new(); + let health = d.health.max(0.0); + if health != 1.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); + } + let phase = d.phase.id(); + if phase != 10 { + meta.push((16, serializer::INT, Value::Int(phase))); + } + Some(horizon_client::lan::entity::EntityState { + id: d.id as i32, + uuid: super::lan::entity_uuid(d.id), + kind: "minecraft:ender_dragon".to_owned(), + position: [d.position.x, d.position.y, d.position.z], + yaw: d.yaw, + pitch: 0.0, + head_yaw: d.yaw, + on_ground: false, + velocity: [d.velocity.x, d.velocity.y, d.velocity.z], + data: 0, + meta, + equipment: Vec::new(), + attributes: Vec::new(), + precise: false, + }) + } +} impl Game<'_> { /// The dragon and fight for `horizon-ctl status`. pub(super) fn dragon_status(&self) -> serde_json::Value { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..ff250dddb 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1082,12 +1082,23 @@ impl Game<'_> { gi: usize, id: i32, ) -> Option<([f64; 3], [f64; 3])> { - let m = self.mobs.iter().find(|m| m.id as i32 == id)?; - let centre = [ - m.position.x, - m.position.y + m.kind.height * 0.5, - m.position.z, - ]; + let centre = match self.mobs.iter().find(|m| m.id as i32 == id) { + Some(m) => [ + m.position.x, + m.position.y + m.kind.height * 0.5, + m.position.z, + ], + // A dragon part or an end crystal (game/dragon.rs). + None => { + let b = self.tracked_special_box(id)?; + let (lo, hi) = (b.min_position(), b.max_position()); + [ + (lo.x + hi.x) / 2.0, + (lo.y + hi.y) / 2.0, + (lo.z + hi.z) / 2.0, + ] + } + }; let g = &mut host.hub.guests[gi]; let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; let d = [centre[0] - eye[0], centre[1] - eye[1], centre[2] - eye[2]]; diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 020ec6adc..76d1588b3 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -264,6 +264,13 @@ impl Game<'_> { self.tridents.iter_mut().for_each(|t| give(&mut t.id)); self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); + // EnderDragon: the dragon, then its eight parts. + if let Some(d) = self.dragon.as_mut() + && d.id == 0 + { + d.id = *next + 1; + *next += 9; + } } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -406,6 +413,7 @@ impl Game<'_> { } out.push(e); } + out.extend(self.lan_dragon_state()); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index e1e7a24c4..9a72ea224 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -523,7 +523,9 @@ public final class VanillaProtocolClient { position.yRot(), position.xRot())); // The 26.3 client answers with the acceptance alone; a second position in the // same tick is an invalid move to vanilla's server once the player is loaded. - if (!respawning) { + // The entity mode's scene may teleport the player (to another level): the + // acceptance alone, as the 26.3 client sends. + if (!respawning && step < ENTITIES) { send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false)); } if (!loaded) { diff --git a/tools/test_server_dragon_parity.py b/tools/test_server_dragon_parity.py new file mode 100644 index 000000000..dc58e851d --- /dev/null +++ b/tools/test_server_dragon_parity.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""The dragon fight on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat +world vanilla generated first, with the same server.properties. A vanilla-codec client (VanillaProtocolClient in +its entity mode) joins, and once its chunks are in, the console sends it to the End, over the exit portal. Nobody +else is in the End: the fight must start from that player alone (`EnderDragonFight.tick` finds it among the +level's players, `createNewDragon` spawns the dragon over the podium) and the dragon must be tracked to the client +(`ServerEntity`'s pairing: ClientboundAddEntityPacket, the synched data, the attribute instances). + +The dragon's flight is random (its yaw, its holding-pattern turns), so its position, rotations and motion are +left out; its type, spawn data, which synched data entries it was paired with and sent (and their serializers) +and its attribute instances must match vanilla's exactly. +""" +import os +from pathlib import Path +import platform +import re +import shutil +import subprocess +import sys + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-dragon-parity' +PLAYER = 'Tester' +# Over the exit portal, well within 192 blocks of (0, 128, 0) and the dragon's holding pattern. +TO_THE_END = f'execute in minecraft:the_end run tp {PLAYER} 0.5 80 0.5' + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}-client.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), PLAYER, str(out), 'entities'], + cwd=lab.ROOT, stdout=log, stderr=subprocess.STDOUT, text=True) + try: + server.wait_for(rf'<{PLAYER}> summon the entities', timeout=180) + server.console(TO_THE_END) + client.wait(timeout=120) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + (build / f'{label}.txt').write_text('\n'.join(lines) + '\n', encoding='utf-8') + return lines + + +def entities(lines, kind): + return [l for l in lines if l.startswith(f'play-entities entity {kind} ')] + + +def dragon_summary(line): + """What of a tracked dragon does not depend on its random flight: its spawn data, the synched data entries + (id and serializer) it was paired with and sent, and its attribute instances.""" + fields = dict(f.split(' ', 1) for f in line.split(' | ')[1:] if ' ' in f) + data = re.search(r' data (-?\d+) ', fields.get('add', '')) + pairing = sorted(int(e.split('=', 1)[0]) for e in fields.get('pairing', '').split() if '=' in e) + sent = sorted((int(k), v.split(' ', 1)[0]) for k, v in re.findall(r'(\d+)=(\d+ [^,}]*)', fields.get('data', ''))) + return { + 'spawn data': data.group(1) if data else None, + 'paired entries': pairing, + 'entries (id, serializer)': sent, + 'attributes': fields.get('attributes'), + 'equipment': fields.get('equipment'), + 'passengers': fields.get('passengers'), + } + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + # SERVER_DRAGON_SIDES=vanilla (or horizon) runs one side and reads the other's last transcript. + sides = [s for s in os.environ.get('SERVER_DRAGON_SIDES', 'vanilla,horizon').split(',') if s] + if 'horizon' in sides: + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-Duser.timezone=UTC', '-cp', str(classes) + os.pathsep + dependencies, + 'dev.horizonlab.parity.VanillaProtocolClient'] + + world = build / 'generate' / 'world' + if not world.exists() or set(sides) == {'vanilla', 'horizon'}: + world = generate_world(vanilla_server, build) + results = {} + for label, command in [('vanilla', vanilla_server), ('horizon', horizon_server)]: + if label in sides: + results[label] = run_side(label, command, client, build, world) + else: + results[label] = (build / f'{label}.txt').read_text(encoding='utf-8').splitlines() + problems = [] + summaries = {} + for label, lines in results.items(): + errors = [l for l in lines if l.startswith('error')] + problems += [f'{label}: {e}' for e in errors[:5]] + dragons = entities(lines, 'minecraft:ender_dragon') + if not dragons: + problems.append(f'{label}: no dragon was tracked to the player in the End') + continue + summaries[label] = dragon_summary(dragons[0]) + if not problems and summaries['vanilla'] != summaries['horizon']: + problems.append(f'the dragons differ:\n vanilla {summaries["vanilla"]}\n horizon {summaries["horizon"]}') + if problems: + raise AssertionError(f'see {build}/vanilla.txt and horizon.txt:\n' + '\n'.join(problems)) + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + dragon=summaries['horizon'], output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='A lone player sent to the End of a dedicated server: the fight starts from it, the dragon spawns ' + 'and is tracked to its vanilla-codec client (spawn data, synched data entries, attributes).')) + print(f'server dragon: the fight started, dragon tracked as vanilla does ({summaries["horizon"]})') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') From f5688883ad3da6cdb755a2cacdd7cfd06ac31330 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:02:44 +0200 Subject: [PATCH 008/115] fix: dragon damage follows vanilla (perched arrows, cooldown, explosions) - A perched dragon (scanning, attacking, flaming, hovering) shrugs arrows off as `AbstractDragonSittingPhase.onHurt` does: no damage, and the arrow is set alight for a second and turns back instead of being spent. Arrows that hit a part or a crystal deal the arrow's damage with its Power bonus, and turn back when the hit is refused (a dying dragon, an invulnerable crystal). - The damage cooldown is `LivingEntity.hurtServer`'s: within it a stronger hit lands its excess over the last one instead of being dropped; the hurt sound plays only for a new hit. - Explosions hit as `ServerExplosion.hurtEntities` does: the dragon itself (its body) and then each part, each by its distance and its exposure (`getSeenPercent`, so cover protects it), through the cooldown; and every end crystal in reach blows up, not only the first. `Dragon::hurt` and `Dragon::explosion_hits` are pure, with unit tests for the perched arrows, the cooldown's excess, the parts' quarter plus one, the take-off after a quarter of its health, and exposure. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit c730ed9ed8e4d9151bacca3313f0fbdf5180c42e) --- crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/game/creatures.rs | 22 +- crates/horizon-client/src/game/dragon.rs | 342 +++++++++++++++----- 3 files changed, 289 insertions(+), 77 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 5cdf46110..26de13cac 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -642,7 +642,7 @@ impl Game<'_> { "dragon-hurt" => { // Test hook: damage the dragon's head as the player would. let amount: f32 = arg(1)?.parse()?; - self.hit_special(super::dragon::SPECIAL, amount, true); + self.hit_special(super::dragon::SPECIAL, amount, true, false); ok() } "quit" => { diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 113558e34..958f7229c 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1879,12 +1879,30 @@ impl Game<'_> { } = hit && id >= super::dragon::SPECIAL { + let by_player = p.owner == Some(Who::Player); + if let ProjectileKind::Arrow { .. } = p.kind { + // AbstractArrow.onHitEntity: spent if the part or crystal took + // it, else turned back (a perched dragon sets it alight first). + let mut arrow = p.clone(); + let amount = arrow_damage(&mut arrow, &mut self.world.random) + p.bonus.damage; + let outcome = match self.hit_special(id, amount, by_player, true) { + super::dragon::Hurt::Landed { .. } => EntityHit::Hurt, + super::dragon::Hurt::Refused => EntityHit::Refused, + super::dragon::Hurt::Shrugged => { + if let Some(a) = arrow.arrow.as_mut() { + a.ignite_for_seconds(1.0); + } + EntityHit::Refused + } + }; + self.finish_arrow_hit(arrow, outcome); + return Ok(()); + } let amount = match p.kind { - ProjectileKind::Arrow { .. } => p.arrow_damage(&mut self.world.random), ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 6.0, _ => 0.0, }; - self.hit_special(id, amount, p.owner == Some(Who::Player)); + self.hit_special(id, amount, by_player, false); return Ok(()); } if let ( diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index db7495ea4..4e6a1779d 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -254,7 +254,10 @@ pub(super) struct Dragon { yaw_accel: f32, pub health: f32, pub hurt_time: i32, + /// `LivingEntity.damageCooldownTime` and `lastHurt`: within the window + /// only damage above the last hit lands, and only the excess. invulnerable: i32, + last_hurt: f32, pub death_time: i32, pub flap: f32, pub old_flap: f32, @@ -273,6 +276,18 @@ pub(super) struct Dragon { nearest_crystal: Option, random: LegacyRandom, } +/// What `EnderDragon.hurt` made of a hit. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(super) enum Hurt { + /// It returned true; `full` when it was a new hit, not just the excess + /// over the last one (the hurt sound and animation). + Landed { full: bool }, + /// It returned false (dying, too little damage). + Refused, + /// A perched dragon's `onHurt` took an arrow's damage away (and set the + /// arrow alight for a second). + Shrugged, +} const PART_SIZES: [(f64, f64); 8] = [ (1.0, 1.0), (3.0, 3.0), @@ -301,6 +316,7 @@ impl Dragon { health: MAX_HEALTH, hurt_time: 0, invulnerable: 0, + last_hurt: 0.0, death_time: 0, flap: 0.0, old_flap: 0.0, @@ -349,6 +365,103 @@ impl Dragon { Vec3::new(p.x + w / 2.0, p.y + h, p.z + w / 2.0), ) } + /// `EnderDragon.hurt(part, source, damage)`: whether the hit landed + /// (an arrow is spent, else it turns back). `counts` is + /// `source.getEntity() instanceof Player` or a damage type that always + /// hurts dragons (explosions); `arrow` a direct arrow or wind charge, + /// which a perched dragon shrugs off (`AbstractDragonSittingPhase.onHurt`). + fn hurt(&mut self, part: usize, damage: f32, counts: bool, arrow: bool) -> Hurt { + if matches!(self.phase, Phase::Dying { .. }) || !self.alive() { + return Hurt::Refused; + } + if arrow && self.phase.sitting() { + return Hurt::Shrugged; + } + let mut damage = damage; + if part != 0 && part != 1 { + damage = damage / 4.0 + damage.min(1.0); + } + if damage < 0.01 { + return Hurt::Refused; + } + if !counts { + return Hurt::Landed { full: false }; + } + let before = self.health; + // LivingEntity.hurtServer: within the cooldown only what exceeds the last hit. + let full = if self.invulnerable > 10 { + if damage <= self.last_hurt { + return Hurt::Landed { full: false }; + } + self.health -= damage - self.last_hurt; + self.last_hurt = damage; + false + } else { + self.last_hurt = damage; + self.invulnerable = 20; + self.health -= damage; + self.hurt_time = 10; + true + }; + if self.health <= 0.0 { + if self.phase.sitting() { + self.health = 0.0; + } else { + // handleKillingBlow: dying flight first. + self.health = 1.0; + self.set_phase(Phase::Dying { + target: None, + time: 0, + }); + } + } + if self.phase.sitting() { + self.sitting_damage += before - self.health.max(0.0); + if self.sitting_damage > 0.25 * MAX_HEALTH { + self.sitting_damage = 0.0; + self.set_phase(Phase::Takeoff { + first: true, + path: None, + target: None, + }); + } + } + Hurt::Landed { full } + } + /// `ServerExplosion.hurtEntities` on the dragon: the dragon itself (its + /// body takes it), then each part, in `Level.getEntities` order, each by + /// its distance and how much of its box the blast sees (`exposure`). + fn explosion_hits( + &self, + center: [f64; 3], + radius: f32, + exposure: impl Fn(Aabb) -> f32, + ) -> Vec<(usize, f32)> { + let diameter = f64::from(radius * 2.0); + let dist = |p: Vec3| { + ((p.x - center[0]).powi(2) + (p.y - center[1]).powi(2) + (p.z - center[2]).powi(2)) + .sqrt() + / diameter + }; + let p = self.position; + let whole = Aabb::new( + Vec3::new(p.x - 8.0, p.y, p.z - 8.0), + Vec3::new(p.x + 8.0, p.y + 8.0, p.z + 8.0), + ); + std::iter::once((2, p, whole)) + .chain((0..8).map(|i| (i, self.parts[i].0, self.part_box(i)))) + .filter_map(|(part, at, b)| { + let d = dist(at); + (d <= 1.0).then(|| { + let pow = (1.0 - d) * f64::from(exposure(b)); + ( + part, + ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32, + ) + }) + }) + .collect() + } fn set_phase(&mut self, phase: Phase) { if self.phase.id() == phase.id() && phase.id() != 1 { return; @@ -656,7 +769,7 @@ impl Game<'_> { if let Some(d) = self.dragon.as_mut() { if d.nearest_crystal == Some(index) { d.nearest_crystal = None; - self.hurt_dragon(0, 10.0, true); + self.hurt_dragon(0, 10.0, true, false); } else if let Some(n) = d.nearest_crystal.as_mut() && *n > index { @@ -712,64 +825,42 @@ impl Game<'_> { .find(|(s, _)| *s == CRYSTAL_IDS + i as u32) .map(|(_, b)| b) } - /// Damage to a special id (from projectiles and melee). - pub(super) fn hit_special(&mut self, id: u32, amount: f32, by_player: bool) { + /// Damage to a special id (from projectiles and melee): what the + /// dragon part or crystal made of it. `arrow` for a direct arrow. + pub(super) fn hit_special( + &mut self, + id: u32, + amount: f32, + by_player: bool, + arrow: bool, + ) -> Hurt { if id >= CRYSTAL_IDS { - self.destroy_crystal((id - CRYSTAL_IDS) as usize, by_player); + // EndCrystal.hurtServer: false while invulnerable, else it blows up. + let index = (id - CRYSTAL_IDS) as usize; + if self.crystals.get(index).is_none_or(|c| c.invulnerable) { + return Hurt::Refused; + } + self.destroy_crystal(index, by_player); + Hurt::Landed { full: true } } else if id >= SPECIAL { - self.hurt_dragon((id - SPECIAL) as usize, amount, by_player); + self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, arrow) + } else { + Hurt::Refused } } - /// `EnderDragon.hurt(part, source, damage)`. - fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool) { + /// `EnderDragon.hurt(part, source, damage)` on the dragon in the level. + fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool, arrow: bool) -> Hurt { let Some(d) = self.dragon.as_mut() else { - return; + return Hurt::Refused; }; - if matches!(d.phase, Phase::Dying { .. }) || !d.alive() { - return; + let hurt = d.hurt(part, damage, counts, arrow); + if hurt == (Hurt::Landed { full: true }) { + let at = [d.position.x, d.position.y, d.position.z]; + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.hurt", Some(at), 5.0, pitch); } - let mut damage = damage; - if part != 0 && part != 1 { - damage = damage / 4.0 + damage.min(1.0); - } - if damage < 0.01 || !counts { - return; - } - // LivingEntity.hurt invulnerability: only damage above the last one in the window. - if d.invulnerable > 10 { - return; - } - let before = d.health; - d.health -= damage; - d.invulnerable = 20; - d.hurt_time = 10; - let at = [d.position.x, d.position.y, d.position.z]; - if d.health <= 0.0 { - if d.phase.sitting() { - d.health = 0.0; - } else { - // handleKillingBlow: dying flight first. - d.health = 1.0; - d.set_phase(Phase::Dying { - target: None, - time: 0, - }); - } - } - if d.phase.sitting() { - d.sitting_damage += before - d.health.max(0.0); - if d.sitting_damage > 0.25 * MAX_HEALTH { - d.sitting_damage = 0.0; - d.set_phase(Phase::Takeoff { - first: true, - path: None, - target: None, - }); - } - } - let pitch = 0.8 + self.world.random.next_float() * 0.3; - self.audio - .play("minecraft:entity.ender_dragon.hurt", Some(at), 5.0, pitch); + hurt } /// Player melee on the dragon's parts or a crystal under the crosshair. /// The dragon part under the crosshair within reach: its id and distance. @@ -826,7 +917,7 @@ impl Game<'_> { amount += self.enchant_damage_bonus("minecraft:ender_dragon") * scale; self.attack_ticks = 0; self.swing_arm(); - self.hit_special(id, amount, true); + self.hit_special(id, amount, true, false); true } /// The 24 nodes (`findClosestNode` builds them on first use). @@ -2370,36 +2461,38 @@ impl Crystal { } } impl Game<'_> { - /// `Explosion.explode` for crystals (they blow up in turn) and the - /// dragon's parts (explosions always hurt dragons). + /// `ServerExplosion.hurtEntities` on the end crystals (each in reach + /// blows up in turn) and the dragon (explosions always hurt dragons). pub(super) fn explosion_hits_special(&mut self, center: [f64; 3], radius: f32) { let diameter = f64::from(radius * 2.0); - let dist = |p: Vec3| { + let in_reach = |p: Vec3| { ((p.x - center[0]).powi(2) + (p.y - center[1]).powi(2) + (p.z - center[2]).powi(2)) .sqrt() + / diameter + <= 1.0 }; - if let Some(i) = self + let crystals: Vec = self .crystals .iter() - .position(|c| !c.invulnerable && dist(c.position) / diameter <= 1.0) - { - self.destroy_crystal(i, false); - } - if let Some(d) = self.dragon.as_ref() { - let hits: Vec<(usize, f32)> = (0..8) - .filter_map(|i| { - let p = d.parts[i].0; - let r = dist(p) / diameter; - (r <= 1.0).then(|| { - let pow = 1.0 - r; - (i, ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32) - }) - }) - .collect(); - if let Some(&(part, amount)) = hits.iter().max_by(|a, b| a.1.total_cmp(&b.1)) { - self.hurt_dragon(part, amount, true); + .filter(|c| !c.invulnerable && in_reach(c.position)) + .map(|c| c.position) + .collect(); + for at in crystals { + // One blowing up may already have taken the next. + if let Some(i) = self.crystals.iter().position(|c| c.position == at) { + self.destroy_crystal(i, false); } } + let Some(d) = self.dragon.as_ref() else { + return; + }; + let hits = d.explosion_hits(center, radius, |b| { + let (lo, hi) = (b.min_position(), b.max_position()); + self.seen_percent(center, [lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) + }); + for (part, amount) in hits { + self.hurt_dragon(part, amount, true, false); + } } } impl Game<'_> { @@ -2840,3 +2933,104 @@ impl Game<'_> { self.fight.dirty = true; } } + +#[cfg(test)] +mod tests { + use super::*; + + fn dragon(phase: Phase) -> Dragon { + let mut d = Dragon::new(Vec3::new(0.0, 70.0, 0.0), 0.0, 1); + d.phase = phase; + d + } + fn flying() -> Phase { + Phase::Holding { + path: None, + target: None, + clockwise: false, + } + } + + #[test] + fn a_perched_dragon_shrugs_arrows_off() { + // AbstractDragonSittingPhase.onHurt: an arrow does nothing, melee does. + let mut d = dragon(Phase::Scanning { time: 0 }); + assert_eq!(d.hurt(0, 9.0, true, true), Hurt::Shrugged); + assert_eq!(d.health, MAX_HEALTH); + assert_eq!(d.hurt(0, 9.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 9.0); + // In flight an arrow lands. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 9.0, true, true), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 9.0); + } + + #[test] + fn the_cooldown_lets_only_the_excess_through() { + // LivingEntity.hurtServer: damageCooldownTime > 10 keeps lastHurt. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 6.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.hurt(0, 4.0, true, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH - 6.0); + assert_eq!(d.hurt(0, 10.0, true, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH - 10.0); + // Ten ticks on, the window is over: a full hit again. + d.invulnerable = 10; + assert_eq!(d.hurt(0, 3.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 13.0); + } + + #[test] + fn parts_and_sources() { + // Neither head nor neck: a quarter plus one. + let mut d = dragon(flying()); + assert_eq!(d.hurt(2, 20.0, true, false), Hurt::Landed { full: true }); + assert_eq!(d.health, MAX_HEALTH - 6.0); + // Not a player's and not an explosion: true, but no damage. + let mut d = dragon(flying()); + assert_eq!(d.hurt(0, 20.0, false, false), Hurt::Landed { full: false }); + assert_eq!(d.health, MAX_HEALTH); + // Too little after the part's cut, and nothing while dying. + assert_eq!(d.hurt(3, 0.001, true, false), Hurt::Refused); + d.phase = Phase::Dying { + target: None, + time: 0, + }; + assert_eq!(d.hurt(0, 20.0, true, false), Hurt::Refused); + } + + #[test] + fn a_quarter_of_its_health_while_perched_makes_it_take_off() { + let mut d = dragon(Phase::Flaming { ticks: 0 }); + d.hurt(0, 30.0, true, false); + assert!(d.phase.sitting()); + d.invulnerable = 0; + d.hurt(0, 21.0, true, false); + assert!(matches!(d.phase, Phase::Takeoff { .. })); + assert_eq!(d.sitting_damage, 0.0); + } + + #[test] + fn explosions_hit_each_part_by_its_exposure() { + let mut d = dragon(flying()); + for (i, part) in d.parts.iter_mut().enumerate() { + part.0 = Vec3::new(i as f64 * 4.0, 70.0, 0.0); + } + // A power-6 blast at the dragon's feet: diameter 12. + let center = [0.0, 70.0, 0.0]; + let open = d.explosion_hits(center, 6.0, |_| 1.0); + // The dragon itself (its body), then the parts within 12 blocks. + let parts: Vec = open.iter().map(|h| h.0).collect(); + assert_eq!(parts, vec![2, 0, 1, 2, 3]); + // At the centre: (1 + 1) / 2 * 7 * 12 + 1. + assert_eq!(open[0].1, 85.0); + // Behind cover (no ray reaches the box) only the 1 is left. + let covered = d.explosion_hits(center, 6.0, |_| 0.0); + assert!(covered.iter().all(|h| h.1 == 1.0)); + // Through the cooldown the strongest hit after the part's cut wins. + for (part, amount) in open { + d.hurt(part, amount, true, false); + } + assert_eq!(d.health, MAX_HEALTH - 85.0); + } +} From 2adfd7519310fa69084f0e2988582b7630419b80 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:09:17 +0200 Subject: [PATCH 009/115] Loot tables apply set_potion SetPotionFunction was skipped, so the potions a loot table gives came out with no contents: a piglin's barter never held fire resistance (the drinkable and splash ones, 16 of 469), only uncraftable potions. The merchant and /loot code had it; the shared loot evaluator now does too. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 1b2767122d7ffc9faf8d8359f49e86bab5054979) --- crates/horizon-client/src/items.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index edf094d39..ab9c98804 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1434,6 +1434,13 @@ impl LootContext<'_> { .count() as u32; } } + // SetPotionFunction (the barter's fire resistance potions). + "minecraft:set_potion" => { + if let Some(id) = f["id"].as_str() { + *stack = std::mem::replace(stack, ItemStack::new("minecraft:air", 0)) + .with_potion(id); + } + } "minecraft:limit_count" => { let limit = &f["limit"]; if let Some(min) = limit["min"].as_i64() { @@ -1631,6 +1638,18 @@ mod tests { ); } + #[test] + fn set_potion_gives_the_potion_its_contents() { + let items = Items::for_tests(HashMap::new()); + let props = BTreeMap::new(); + let table = json!({"pools":[{"rolls":1,"entries":[{"type":"minecraft:item","name":"minecraft:splash_potion", + "modifier":{"type":"minecraft:set_potion","id":"minecraft:fire_resistance"}}]}]}); + let drops = ctx(&items, None, &props, "").evaluate(&table, &mut LegacyRandom::new(1)); + assert_eq!(drops.len(), 1); + assert_eq!(&*drops[0].item, "minecraft:splash_potion"); + assert_eq!(drops[0].potion(), Some("minecraft:fire_resistance")); + } + #[test] fn always_edible_and_consume_effects_loaded() { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) From f16c0318b764b950d49d51fcfbf2973c41f5dc5e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:20:40 +0200 Subject: [PATCH 010/115] fix: a new world knows its world spawn before its first save The world spawn was only filled in when the world was first saved, from the player's spawn point at that moment: a bed slept in before then became the world spawn, and anything asking for the world spawn earlier (a guest's respawn) fell back on the host's spawn point instead. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 03e621ed3af671c0ae695ea2e5b2d1a29d45c84c) --- crates/horizon-client/src/game.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 460899bff..f7094351b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3726,6 +3726,9 @@ impl Game<'_> { f64::from(z) + 0.5, )); self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]); + // The world's spawn from the start, not only once saved: a bed set + // before the first save must not become it. + self.level.world_spawn.get_or_insert([x, y, z]); } let s = self .level From 02ba66b72149bdc86334485170d01ba521e85010 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 04:21:48 +0200 Subject: [PATCH 011/115] /summon reports the entities that take their id when first tracked Primed TNT (and falling blocks, projectiles) spawned from /summon get their entity id only when first tracked, so the summon found no new id and answered "Unable to summon entity" though the entity was there and went off. The summon now also counts those lists, and names the type: "Summoned new Primed TNT", as vanilla. Test: a TNT summon in the command execution corpus (world group: 125/126 match vanilla; the one left, /waypoint list, was there before). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit dd733684bc8a2efca2b2fa76fc54d6eb48608103) --- crates/horizon-client/src/game/commands.rs | 34 +++++++++++++++++----- tools/command_exec_corpus.py | 3 ++ 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index b970414a6..f174f98c1 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1612,11 +1612,16 @@ impl Game<'_> { { return Err(err("commands.summon.failed.peaceful", &[])); } - let Some(target) = self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)? - else { - return Err(err("commands.summon.failed", &[])); + let before = self.spawned_mark(); + let name = match self.summon_with_nbt(&format!("minecraft:{short}"), pos, &nbt)? { + Some(target) => self.target_name(target), + // Spawned as a kind no command target stands for (primed + // TNT, falling blocks, projectiles): its type's name. + None if self.spawned_mark() != before => { + Text::translate(&format!("entity.minecraft.{short}"), &[]) + } + None => return Err(err("commands.summon.failed", &[])), }; - let name = self.target_name(target); self.feedback(Text::translate("commands.summon.success", &[name])); return Ok(1); } @@ -1669,16 +1674,31 @@ impl Game<'_> { } // SummonCommand.createEntity: any other type from an empty compound. _ => { - let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else { - return Err(err("commands.summon.failed", &[])); + let before = self.spawned_mark(); + name = match self.summon_with_nbt(&kind, pos, "{}")? { + Some(target) => self.target_name(target), + // Spawned as a kind no command target stands for + // (primed TNT, falling blocks, projectiles). + None if self.spawned_mark() != before => { + Text::translate(&format!("entity.minecraft.{short}"), &[]) + } + None => return Err(err("commands.summon.failed", &[])), }; - name = self.target_name(target); } } } self.feedback(Text::translate("commands.summon.success", &[name])); Ok(1) } + /// What changes when an entity spawns, kinds that take their id only + /// when first tracked (primed TNT, falling blocks, projectiles) + /// included: a summon compares it before and after. + fn spawned_mark(&self) -> (u32, usize) { + ( + self.next_entity, + self.tnts.len() + self.falling.len() + self.creatures.projectiles.len(), + ) + } /// BlockStateArgument -> registry state. pub(super) fn block_state(&self, b: &BlockInput) -> R { let state = horizon_world::chunk::BlockState { diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 02311beda..b6edc009a 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -568,6 +568,9 @@ def world_misc(): cmd('/summon minecraft:armor_stand 4.5 210 4.5 {NoGravity:1b,Tags:["w"],CustomName:{text:"Stand",color:"blue"}}'), cmd('/swing @e[tag=w]'), cmd('/summon minecraft:lightning_bolt 4.5 300 4.5'), + # Primed TNT is no command target in Horizon: still "Summoned new + # Primed TNT" (it explodes high in the air, far from the rest). + cmd('/summon minecraft:tnt 60.5 300 60.5 {fuse:1s}'), cmd('/summon minecraft:pig 4.5 210 4.5 {NoAI:1b,Invulnerable:1b,Tags:["w"],Passengers:[{id:"minecraft:chicken",NoAI:1b,Tags:["w"]}]}'), cmd('/summon minecraft:pig 4.5 400 4.5'), cmd('/summon minecraft:pig 30000000 210 4.5'), From ac06314bd91369df41e03f62ebafe0ccf15af87d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:08:56 +0200 Subject: [PATCH 012/115] fix: the dragon fights every player in the End, not only the window's The dragon read the window's own player for everything: network players (LAN guests, players on a server) were never targeted, strafed, charged, knocked back, bitten, breathed on or hit by its fireballs. - It sees the level's players (the window's and every guest in the level) through `TargetingConditions.forCombat` as each phase asks (`Level.getNearestPlayer`): alive, neither creative nor spectator, none on Peaceful. The holding pattern strafes the enemy nearest the egg, the landing approach comes in opposite it, the perched dragon scans within 20 blocks (10 up or down) and charges within 150. - The strafe keeps its own target (`attackTarget`) and goes back to the holding pattern when it leaves the level. - A destroyed crystal sends a holding dragon after the player who destroyed it, else the nearest player (`EnderDragon.onCrystalDestroyed`), when it can attack them. - Wing knockback and the head and neck bites, the breath and fireball clouds and its fireballs act on every player alike; what hits a guest runs as that guest, its knockback sent to its client. - The dragon takes its id and its parts' when it is created, so a guest can attack them in a world without network players too. A unit test covers the targeting rules (spectators and creative players passed over, ranges, Peaceful, the nearest to the egg). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2eef4e4bf50137d1cb8d9a377e0be38b07294b8e) --- crates/horizon-client/src/game/dragon.rs | 390 ++++++++++++++---- .../horizon-client/src/game/lan_entities.rs | 7 - 2 files changed, 302 insertions(+), 95 deletions(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 4e6a1779d..bd5ca1209 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -116,6 +116,8 @@ enum Phase { path: Option, target: Option, clockwise: bool, + /// `attackTarget`: the player it strafes. + player: Option, }, LandingApproach { path: Option, @@ -182,6 +184,7 @@ impl Phase { path: None, target: None, clockwise: false, + player: None, }, 2 => Self::LandingApproach { path: None, @@ -274,8 +277,66 @@ pub(super) struct Dragon { pub parts: [(Vec3, Vec3); 8], nodes: Option<[[i32; 3]; 24]>, nearest_crystal: Option, + /// A crystal destroyed while it held its pattern (taken on its next tick). + strafe_request: Option, random: LegacyRandom, } +/// A player in the fight: the window's own player, or a guest by +/// connection (a LAN or server player, or a companion). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum FightWho { + Host, + Guest(u32), +} +/// A player in the End as the dragon sees it. +#[derive(Clone, Copy, Debug)] +struct FightPlayer { + who: FightWho, + position: Vec3, + bounds: Aabb, + alive: bool, + creative: bool, + spectator: bool, +} +impl FightPlayer { + /// `Player.canBeSeenAsEnemy`: alive, neither creative nor spectator. + fn enemy(&self) -> bool { + self.alive && !self.creative && !self.spectator + } +} +/// `TargetingConditions.forCombat` (visibility aside) in +/// `Level.getNearestPlayer`: the enemy nearest `at` among `players`, within +/// `range` of the dragon at `from` and passing `selector`; none on Peaceful. +fn nearest_enemy( + players: &[FightPlayer], + peaceful: bool, + at: Vec3, + range: Option<(Vec3, f64)>, + selector: impl Fn(&FightPlayer) -> bool, +) -> Option { + if peaceful { + return None; + } + players + .iter() + .filter(|p| p.enemy() && selector(p)) + .filter(|p| range.is_none_or(|(from, r)| p.position.distance_squared(from) <= r * r)) + .min_by(|a, b| { + a.position + .distance_squared(at) + .total_cmp(&b.position.distance_squared(at)) + }) + .copied() +} +/// Whom a destroyed crystal sends a holding dragon after +/// (`DragonHoldingPatternPhase.onCrystalDestroyed`). +#[derive(Clone, Copy, Debug)] +enum StrafeRequest { + /// The player who destroyed it. + Player(FightWho), + /// Anything else: the player nearest the crystal. + Nearest(Vec3), +} /// What `EnderDragon.hurt` made of a hit. #[derive(Clone, Copy, Debug, PartialEq)] pub(super) enum Hurt { @@ -335,6 +396,7 @@ impl Dragon { parts: [(position, position); 8], nodes: None, nearest_crystal: None, + strafe_request: None, random: LegacyRandom::new(seed), } } @@ -618,6 +680,53 @@ impl Game<'_> { fn arena_loaded(&self) -> bool { (-2..=1).all(|cz| (-2..=1).all(|cx| self.streaming.is_lit(cx, cz))) } + /// The player acting now: the guest whose turn it is, else the host. + fn acting_player(&self) -> FightWho { + self.lan_acting.map_or(FightWho::Host, FightWho::Guest) + } + /// The players in the level the dragon sees (`level.players()`): the + /// window's own, then every guest in the level. + fn fight_players(&self) -> Vec { + let mut out = Vec::new(); + if let Some(p) = self.player.as_ref() { + out.push(FightPlayer { + who: FightWho::Host, + position: p.position, + bounds: p.bounds(), + alive: !p.health.dead_or_dying(), + creative: self.creative, + spectator: self.spectator(), + }); + } + if let Some(h) = self.lan.as_ref() { + for g in h.hub.guests.iter().filter(|g| h.hub.here(g) && g.loaded) { + let [x, y, z] = g.position; + out.push(FightPlayer { + who: FightWho::Guest(g.conn), + position: Vec3::new(x, y, z), + bounds: super::lan_mobs::guest_bounds(g), + alive: !g.dead, + creative: g.creative(), + spectator: g.spectator(), + }); + } + } + out + } + /// Run `f` as the fight's player `who` (a guest's turn, its knockback + /// sent to its client). + fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { + match who { + FightWho::Host => f(self), + FightWho::Guest(conn) => { + let Some(mut host) = self.lan.take() else { + return; + }; + self.guest_hit_by(&mut host, conn, f); + self.lan = Some(host); + } + } + } /// `EnderDragonFight.validPlayer`: the players alive within 192 blocks of /// (0, 128, 0), the host and the guests in the level alike. fn fight_has_players(&self) -> bool { @@ -680,6 +789,14 @@ impl Game<'_> { } } } + // EnderDragon's constructor takes its id and its parts' from the + // entity counter (a dragon loaded from the save gets them here too). + if let Some(d) = self.dragon.as_mut() + && d.id == 0 + { + d.id = self.next_entity + 1; + self.next_entity += 9; + } self.tick_crystals(); self.tick_dragon(); } @@ -744,7 +861,7 @@ impl Game<'_> { } } /// A crystal took damage: `EndCrystal.hurtServer` blows it up (power 6). - fn destroy_crystal(&mut self, index: usize, by_player: bool) { + fn destroy_crystal(&mut self, index: usize, by: Option) { if index >= self.crystals.len() || self.crystals[index].invulnerable { return; } @@ -775,18 +892,15 @@ impl Game<'_> { { *n -= 1; } - if by_player - && let Some(d) = self.dragon.as_mut() + // EnderDragon.onCrystalDestroyed: the player who did it, else the + // nearest; DragonHoldingPatternPhase strafes them. + if let Some(d) = self.dragon.as_mut() && matches!(d.phase, Phase::Holding { .. }) { - // DragonHoldingPatternPhase.onCrystalDestroyed: strafe the player. - d.set_phase(Phase::Strafe { - charge: 0, - path: None, - target: None, - clockwise: false, + d.strafe_request = Some(match by { + Some(who) => StrafeRequest::Player(who), + None => StrafeRequest::Nearest(c.position), }); - self.strafe_begin(); } } } @@ -840,7 +954,8 @@ impl Game<'_> { if self.crystals.get(index).is_none_or(|c| c.invulnerable) { return Hurt::Refused; } - self.destroy_crystal(index, by_player); + let by = by_player.then(|| self.acting_player()); + self.destroy_crystal(index, by); Hurt::Landed { full: true } } else if id >= SPECIAL { self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, arrow) @@ -1081,10 +1196,8 @@ impl Game<'_> { path.advance(); Some(path) } - fn strafe_begin(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; + /// `DragonStrafePlayerPhase.setTarget`: a path to the player at `p`. + fn strafe_begin(&mut self, p: Vec3) { let Some(d) = self.dragon.as_ref() else { return; }; @@ -1114,6 +1227,32 @@ impl Game<'_> { } /// One phase server tick (`doServerTick`). fn tick_phase(&mut self) { + let players = self.fight_players(); + let peaceful = self.ui.difficulty == 0; + // A crystal destroyed since: strafe whoever it names, if the dragon + // can attack them (`canAttack`). + if let Some(d) = self.dragon.as_mut() + && let Some(request) = d.strafe_request.take() + && matches!(d.phase, Phase::Holding { .. }) + { + let target = match request { + StrafeRequest::Player(who) => players + .iter() + .find(|p| p.who == who && p.enemy() && !peaceful) + .copied(), + StrafeRequest::Nearest(at) => nearest_enemy(&players, peaceful, at, None, |_| true), + }; + if let Some(t) = target { + d.set_phase(Phase::Strafe { + charge: 0, + path: None, + target: None, + clockwise: false, + player: Some(t.who), + }); + self.strafe_begin(t.position); + } + } let Some(d) = self.dragon.as_ref() else { return; }; @@ -1125,14 +1264,13 @@ impl Game<'_> { (t.x - pos.x).powi(2) + (t.y - pos.y).powi(2) + (t.z - pos.z).powi(2) }) }; - let player = self - .player - .as_ref() - .filter(|p| !p.health.dead_or_dying()) - .map(|p| p.position); - let survival_player = player.filter(|_| !self.creative); let podium = self.podium_top(); + // The egg's place (`getHeightmapPos` at the podium) and its centre. + let egg = Vec3::new(0.0, podium.y, 0.0); + let egg_centre = Vec3::new(0.5, podium.y + 0.5, 0.5); let mut next: Option = None; + // Where the player a new strafe goes after stands. + let mut strafe_at: Option = None; match &mut phase { Phase::Holding { path, @@ -1152,11 +1290,10 @@ impl Game<'_> { target: None, }); chosen = true; - } else if let Some(pp) = survival_player { - let dist = ((pp.x - podium.x).powi(2) - + (pp.y - podium.y).powi(2) - + (pp.z - podium.z).powi(2)) - / 512.0; + } else if let Some(nearest) = + nearest_enemy(&players, peaceful, egg, None, |_| true) + { + let dist = nearest.position.distance_squared(egg_centre) / 512.0; let r = &mut self.dragon.as_mut().expect("dragon").random; if r.next_int_bound((dist + 2.0) as i32).unwrap_or(1) == 0 || r.next_int_bound(crystals + 2).unwrap_or(1) == 0 @@ -1166,7 +1303,9 @@ impl Game<'_> { path: None, target: None, clockwise: false, + player: Some(nearest.who), }); + strafe_at = Some(nearest.position); chosen = true; } } @@ -1186,8 +1325,12 @@ impl Game<'_> { path, target, clockwise, + player, } => { - let Some(pp) = survival_player else { + // Its target as it is now, whatever became of it; gone from + // the level, or never found: back to the holding pattern. + let tracked = player.and_then(|who| players.iter().find(|p| p.who == who)); + let Some(pp) = tracked.map(|p| p.position) else { next = Some(Phase::Holding { path: None, target: None, @@ -1245,7 +1388,9 @@ impl Game<'_> { if dt < 100.0 || dt > 22500.0 || collided { if path.as_ref().is_none_or(|p| p.0.done()) { let current = self.closest_node(pos.x, pos.y, pos.z); - let target_node = match player { + // NEAR_EGG_TARGETING: the enemy nearest the egg. + let near_egg = nearest_enemy(&players, peaceful, egg, None, |_| true); + let target_node = match near_egg.map(|p| p.position) { Some(pp) => { let aim = glam::DVec2::new(pp.x, pp.z).normalize_or_zero(); self.closest_node(-aim.x * 40.0, 105.0, -aim.y * 40.0) @@ -1317,12 +1462,12 @@ impl Game<'_> { } Phase::Scanning { time } => { *time += 1; - let near = player.filter(|pp| { - (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2) - <= 400.0 - && (pp.y - pos.y).abs() <= 10.0 - }); - if let Some(pp) = near.filter(|_| !self.creative) { + // scanTargeting: within 20 blocks, at most 10 above or below. + let near = nearest_enemy(&players, peaceful, pos, Some((pos, 20.0)), |p| { + (p.position.y - pos.y).abs() <= 10.0 + }) + .map(|p| p.position); + if let Some(pp) = near { if *time > 25 { next = Some(Phase::Attacking { ticks: 0 }); } else { @@ -1338,19 +1483,15 @@ impl Game<'_> { d.yaw += d.yaw_accel; } } else if *time >= 100 { - next = Some(match survival_player { - Some(pp) - if (pp.x - pos.x).powi(2) - + (pp.y - pos.y).powi(2) - + (pp.z - pos.z).powi(2) - <= 150.0 * 150.0 => - { - Phase::Charging { - target: Some(pp), - since: 0, - } - } - _ => Phase::Takeoff { + // CHARGE_TARGETING: within 150 blocks. + let charge = + nearest_enemy(&players, peaceful, pos, Some((pos, 150.0)), |_| true); + next = Some(match charge { + Some(p) => Phase::Charging { + target: Some(p.position), + since: 0, + }, + None => Phase::Takeoff { first: true, path: None, target: None, @@ -1455,10 +1596,9 @@ impl Game<'_> { let d = self.dragon.as_mut().expect("dragon"); d.phase = phase; if let Some(n) = next { - let strafe = matches!(n, Phase::Strafe { .. }); d.set_phase(n); - if strafe { - self.strafe_begin(); + if let Some(at) = strafe_at { + self.strafe_begin(at); } } } @@ -1692,34 +1832,41 @@ impl Game<'_> { ); let wings = [d.part_box(6), d.part_box(7)]; let heads = [d.part_box(0), d.part_box(1)]; - let player_box = self.player.as_ref().map(|p| p.bounds()); - let creative = self.creative; - if !recently_hurt && let Some(pb) = player_box.filter(|_| !creative) { - for w in wings { - let zone = w - .inflate(Vec3::new(4.0, 2.0, 4.0)) - .move_by(Vec3::new(0.0, -2.0, 0.0)); - if zone.intersects(pb) { - let pp = self - .player - .as_ref() - .map(|p| p.position) - .unwrap_or(Vec3::ZERO); - let (xd, zd) = (pp.x - bc, pp.z - bz); - let dd = (xd * xd + zd * zd).max(0.1); - if let Some(p) = self.player.as_mut() { - p.velocity.x += xd / dd * 4.0; - p.velocity.y += 0.2; - p.velocity.z += zd / dd * 4.0; - } - if !sitting { - self.hurt_player_by("minecraft:mob_attack", 5.0); + if !recently_hurt { + // EntitySelector.NO_CREATIVE_OR_SPECTATOR, every player alike. + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive && !p.creative && !p.spectator) + .collect(); + for p in players { + // knockBack, once for each wing whose zone holds them. + for w in wings { + let zone = w + .inflate(Vec3::new(4.0, 2.0, 4.0)) + .move_by(Vec3::new(0.0, -2.0, 0.0)); + if zone.intersects(p.bounds) { + let (xd, zd) = (p.position.x - bc, p.position.z - bz); + let dd = (xd * xd + zd * zd).max(0.1); + self.as_fight_player(p.who, |g| { + if let Some(pl) = g.player.as_mut() { + pl.velocity.x += xd / dd * 4.0; + pl.velocity.y += 0.2; + pl.velocity.z += zd / dd * 4.0; + } + if !sitting { + g.hurt_player_by("minecraft:mob_attack", 5.0); + } + }); } } - } - for h in heads { - if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(pb) { - self.hurt_player_by("minecraft:mob_attack", 10.0); + // hurt: the head and the neck. + for h in heads { + if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(p.bounds) { + self.as_fight_player(p.who, |g| { + g.hurt_player_by("minecraft:mob_attack", 10.0); + }); + } } } } @@ -1884,7 +2031,13 @@ impl Game<'_> { /// power, bursting into dragon's breath on impact. pub(super) fn tick_dragon_fireballs(&mut self) { let mut balls = std::mem::take(&mut self.dragon_fireballs); - let player = self.player.as_ref().map(|p| p.bounds()); + // Projectile.canHitEntity: any player but spectators. + let players: Vec = self + .fight_players() + .iter() + .filter(|p| p.alive && !p.spectator) + .map(|p| p.bounds) + .collect(); balls.retain_mut(|b| { b.previous = b.position; b.age += 1; @@ -1906,7 +2059,7 @@ impl Game<'_> { let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); f.full_collision || f.legacy_solid }; - let hit_player = player.is_some_and(|pb| { + let hit_player = players.iter().any(|pb| { pb.intersects(Aabb::new( Vec3::new(next.x - 0.5, next.y - 0.5, next.z - 0.5), Vec3::new(next.x + 0.5, next.y + 0.5, next.z + 0.5), @@ -1942,7 +2095,13 @@ impl Game<'_> { /// The dragon's breath clouds (`AreaEffectCloud` with instant damage at /// a quarter duration scale): shrinking, puffing particles, harming the player. fn tick_breath(&mut self) { - let player = self.player.as_ref().map(|p| p.position); + // What instant damage reaches: neither creative nor spectator players. + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive && !p.creative && !p.spectator) + .collect(); + let mut harmed: Vec<(FightWho, f32)> = Vec::new(); let mut clouds = std::mem::take(&mut self.breath_clouds); clouds.retain_mut(|c| { c.age += 1; @@ -1969,20 +2128,26 @@ impl Game<'_> { ); } // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. - if c.age >= 20 - && c.age % 20 == 0 - && let Some(pp) = player - && (pp.x - c.at[0]).hypot(pp.z - c.at[2]) <= f64::from(r) - && (pp.y - c.at[1]).abs() < 1.0 - && !self.creative - { + if c.age >= 20 && c.age % 20 == 0 { // Instant damage: I (6) from the breath, II (12) from a fireball. let amount = if c.from_dragon { 6.0 } else { 12.0 }; - self.hurt_player_by("minecraft:indirect_magic", amount); + for p in &players { + let pp = p.position; + if (pp.x - c.at[0]).hypot(pp.z - c.at[2]) <= f64::from(r) + && (pp.y - c.at[1]).abs() < 1.0 + { + harmed.push((p.who, amount)); + } + } } true }); self.breath_clouds.append(&mut clouds); + for (who, amount) in harmed { + self.as_fight_player(who, |g| { + g.hurt_player_by("minecraft:indirect_magic", amount); + }); + } } /// `BossHealthOverlay`: the dragon's pink bar, then the withers', the /// raids' and the custom bars, in that order. @@ -2480,7 +2645,7 @@ impl Game<'_> { for at in crystals { // One blowing up may already have taken the next. if let Some(i) = self.crystals.iter().position(|c| c.position == at) { - self.destroy_crystal(i, false); + self.destroy_crystal(i, None); } } let Some(d) = self.dragon.as_ref() else { @@ -2535,11 +2700,21 @@ impl Game<'_> { pub(super) fn dragon_status(&self) -> serde_json::Value { serde_json::json!({ "dragon": self.dragon.as_ref().map(|d| serde_json::json!({ + "id": d.id, "position": [d.position.x, d.position.y, d.position.z], "health": d.health, "phase": d.phase.id(), "death_time": d.death_time, + // The player it strafes: "host", or the guest's entity id. + "strafing": match &d.phase { + Phase::Strafe { player: Some(FightWho::Host), .. } => serde_json::json!("host"), + Phase::Strafe { player: Some(FightWho::Guest(conn)), .. } => serde_json::json!( + self.lan.as_ref().and_then(|h| h.hub.guest(*conn)).map(|g| g.entity_id) + ), + _ => serde_json::Value::Null, + }, })), + "players": self.fight.players, "crystals": self.crystals.len(), "alive_crystals": self.fight.alive_crystals, "killed": self.fight.killed, @@ -3033,4 +3208,43 @@ mod tests { } assert_eq!(d.health, MAX_HEALTH - 85.0); } + + fn player(who: FightWho, x: f64, creative: bool, spectator: bool) -> FightPlayer { + let position = Vec3::new(x, 64.0, 0.0); + FightPlayer { + who, + position, + bounds: Aabb::new(position, Vec3::new(x + 0.6, 65.8, 0.6)), + alive: true, + creative, + spectator, + } + } + + #[test] + fn the_dragon_targets_any_player_it_can_attack() { + let at = Vec3::new(0.0, 64.0, 0.0); + // A spectating host and a creative guest are never targets: the + // survival guest further away is. + let players = [ + player(FightWho::Host, 1.0, false, true), + player(FightWho::Guest(7), 2.0, true, false), + player(FightWho::Guest(8), 30.0, false, false), + ]; + let t = nearest_enemy(&players, false, at, None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Guest(8))); + // Out of a 20-block range, or filtered out, or on Peaceful: none. + assert!(nearest_enemy(&players, false, at, Some((at, 20.0)), |_| true).is_none()); + assert!(nearest_enemy(&players, false, at, None, |p| p.position.x < 10.0).is_none()); + assert!(nearest_enemy(&players, true, at, None, |_| true).is_none()); + // The nearest of several, measured from where it looks (the egg). + let players = [ + player(FightWho::Host, 5.0, false, false), + player(FightWho::Guest(8), -3.0, false, false), + ]; + let t = nearest_enemy(&players, false, at, None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Guest(8))); + let t = nearest_enemy(&players, false, Vec3::new(9.0, 64.0, 0.0), None, |_| true); + assert_eq!(t.map(|p| p.who), Some(FightWho::Host)); + } } diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 76d1588b3..7230e323d 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -264,13 +264,6 @@ impl Game<'_> { self.tridents.iter_mut().for_each(|t| give(&mut t.id)); self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); - // EnderDragon: the dragon, then its eight parts. - if let Some(d) = self.dragon.as_mut() - && d.id == 0 - { - d.id = *next + 1; - *next += 9; - } } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and From 1845cc73af5738436a19432ea7fd8458cbd2e27d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 21:44:42 +0200 Subject: [PATCH 013/115] fix: end crystals take their entity ids when the fight places them Like the dragon, a spike's crystal gets its id from the entity counter as EndCrystal's constructor does, instead of only once a client tracks it: a player the level serves without a client can then aim at it. The fight's control status lists each crystal's id and position. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e32e5031c141fbd8c882847729beec92a65179a3) --- crates/horizon-client/src/game/dragon.rs | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index bd5ca1209..e0d6b67cc 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -797,6 +797,12 @@ impl Game<'_> { d.id = self.next_entity + 1; self.next_entity += 9; } + // The spikes' crystals too (EndCrystal's constructor): an id whether + // or not a client has tracked them yet, to be aimed at by it. + for c in self.crystals.iter_mut().filter(|c| c.id == 0) { + self.next_entity += 1; + c.id = self.next_entity; + } self.tick_crystals(); self.tick_dragon(); } @@ -2716,6 +2722,11 @@ impl Game<'_> { })), "players": self.fight.players, "crystals": self.crystals.len(), + // The tracked id (0 until tracked) and position of each crystal. + "crystal_list": self.crystals.iter().map(|c| serde_json::json!({ + "id": c.id, + "position": [c.position.x, c.position.y, c.position.z], + })).collect::>(), "alive_crystals": self.fight.alive_crystals, "killed": self.fight.killed, "exit_portal": self.fight.exit_portal, From 4b4b88b061d204c646d72264070fc0f554f7e1fd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:05:47 +0200 Subject: [PATCH 014/115] dragon: FightWho's doc names LAN and server players only Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dragon.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e0d6b67cc..43f56f400 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -282,7 +282,7 @@ pub(super) struct Dragon { random: LegacyRandom, } /// A player in the fight: the window's own player, or a guest by -/// connection (a LAN or server player, or a companion). +/// connection (a LAN or server player). #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum FightWho { Host, From 4f461b27edc197298ca89457bef889fe32994084 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:43:01 +0200 Subject: [PATCH 015/115] Other players are drawn lying in their beds A sleeping guest stood on top of its bed for everyone else: the server sent its pose but never its bed (LivingEntity.SLEEPING_POS goes only to the sleeper itself), Horizon's clients had no sleeping pose for other players, and the host's own models of its guests ignored the bed. A player paired with the sleeper later (the host walking up from afar) saw the same. The tracked state of a sleeping player (the host or a guest) now holds its bed, so pairing and updates send it, and its removal sends the empty position back; the clients and the host's guest models lie the player in the bed as LivingEntityRenderer.setupRotations does for Pose.SLEEPING (the villagers' sleeping pose, by the bed's facing). lan_e2e `sleep`: the host draws the sleeping guest lying, the guest the sleeping host, and neither once they are up. Fixes #1045 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/examples/lan_flat.rs | 1 + crates/horizon-client/src/game/lan.rs | 19 +++++++++++++++++++ crates/horizon-client/src/game/remote.rs | 19 +++++++++++++++++++ crates/horizon-client/src/lan/entity.rs | 4 +++- crates/horizon-client/src/lan/hub.rs | 12 +++++++++++- crates/horizon-client/src/mobs/render.rs | 3 ++- crates/horizon-client/src/mobs/villager.rs | 16 ++++++++++------ crates/horizon-client/tests/lan_bot.rs | 1 + tools/lan_e2e.py | 15 +++++++++++++-- 9 files changed, 79 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 53a4d62f7..f3dfea6b1 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -102,6 +102,7 @@ fn main() -> Result<(), Box> { equipment: Default::default(), health: 20.0, attributes: Vec::new(), + bed: None, living_flags: 0, }; loop { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 18325828d..00279246a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -395,6 +395,8 @@ impl Game<'_> { ], "chunks": g.sent_chunks.len(), "tracked": g.tracker.len(), + // Whether the host draws this guest lying in a bed. + "model_lying": h.models.get(&g.conn).map(|m| m.extra.ints[1] != 0), // The armour the host draws on this guest, head to feet. "model_armor": h.models.get(&g.conn).map(|m| { [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] @@ -735,6 +737,7 @@ impl Game<'_> { health: p.health.health(), attributes: horizon_client::lan::attributes::syncable(&p.attributes), living_flags: living_flags(self.using), + bed: self.sleeping, }) } @@ -1207,6 +1210,8 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // Lying in its bed (LivingEntity.getBedOrientation). + m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b)); // LivingEntity.updateSwingTime: the arm swing lan_swings started. m.anim.attack_anim_o = m.anim.attack_anim; horizon_client::mobs::ai::tick_swing(m); @@ -1218,6 +1223,20 @@ impl Game<'_> { } } + /// The bed at `head` as a sleeping model lies in it (`ints[1]`, + /// `villager::sleep_pose`): its `facing`. + pub(super) fn bed_facing(&self, head: [i32; 3]) -> i32 { + let state = self.world.block(head[0], head[1], head[2]); + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing")) + .map(String::as_str); + horizon_client::mobs::villager::bed_facing_code(facing) + } + /// The guests' models for the entity pass. pub(super) fn guest_model_geometry( &self, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5bb3e172c..ec6b35c1f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1544,6 +1544,18 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): another + // player lies down in their bed (drawn lying in it), or gets up. + if other { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + let code = bed.map_or(0, |b| self.bed_facing(b)); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.extra.ints[1] = code; + } + } + } + } // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this // player lies down in the bed, or gets up. if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { @@ -4102,6 +4114,13 @@ impl Game<'_> { .filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive()) .map(|m| m.id) .collect::>(), + // The other players this client draws lying in a bed (SLEEPING_POS). + "lying_players": self + .mobs + .iter() + .filter(|m| r.level_players.contains_key(&(m.id as i32)) && m.extra.ints[1] != 0) + .map(|m| m.id) + .collect::>(), // The player's own model exists (third person and the inventory draw it). "player_model": self.player_model.is_some(), "health": r.health.0, diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 9082e01fa..c1156001c 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -393,11 +393,13 @@ impl ServerEntity { .collect(); // A value back at its default is left out of the state, but the // clients still hold the old one: Entity's shared flags and pose go - // back to 0 (a player standing up again, a mob no longer on fire). + // back to 0 (a player standing up again, a mob no longer on fire), + // a sleeper's bed to none. for (index, kind, _) in &self.meta { let default = match (*index, *kind) { (0, serializer::BYTE) => Value::Byte(0), (6, serializer::POSE) => Value::Id(0), + (14, serializer::OPTIONAL_BLOCK_POS) => Value::OptPos(None), _ => continue, }; if !e.meta.iter().any(|m| m.0 == *index) { diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index a961d57a4..9c65e9292 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -85,6 +85,8 @@ pub struct HostState { pub attributes: Vec, /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use). pub living_flags: i8, + /// The bed the host sleeps in (`LivingEntity.SLEEPING_POS`). + pub bed: Option<[i32; 3]>, } /// Everything the hub needs from the game for one tick. @@ -1467,6 +1469,7 @@ impl Hub { on_ground: bool, flags: (bool, bool, bool, bool), living_flags: i8, + bed: Option<[i32; 3]>, skin: u8, health: f32, equipment: Vec<(u8, Option)>, @@ -1502,6 +1505,11 @@ impl Hub { // Always there: the trackers send the entries that changed, and an // item no longer in use is a change back to 0. meta.push((8, serializer::BYTE, Value::Byte(living_flags))); + // LivingEntity.SLEEPING_POS: the others draw the player lying in it, + // a player paired later too. + if let Some(bed) = bed.filter(|_| sleeping) { + meta.push((14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(Some(bed)))); + } if (health - 1.0).abs() > f32::EPSILON && health != 20.0 { meta.push((9, serializer::FLOAT, Value::Float(health))); } @@ -1565,8 +1573,9 @@ impl Hub { h.position, (h.yaw, h.pitch, h.head_yaw), h.on_ground, - (h.sneaking, h.sprinting, false, false), + (h.sneaking, h.sprinting, false, h.bed.is_some()), h.living_flags, + h.bed, 0x7F, h.health, equipment, @@ -1598,6 +1607,7 @@ impl Hub { g.on_ground, (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), g.living_flags, + g.bed, g.info.model_customisation, g.health, equipment, diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a0dce0e08..99548ec3f 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -749,7 +749,8 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = (m.age as f32 + alpha).floor(); body += (f64::from(ticks * 3.25).cos() * std::f64::consts::PI * 0.4) as f32; } - let sleep = (m.species() == Species::Villager) + // A sleeping villager, or another player lying in their bed. + let sleep = (m.species() == Species::Villager || m.kind.id == "minecraft:player") .then(|| super::villager::sleep_pose(m)) .flatten(); let rotation = match sleep { diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index f568cb47b..84c607933 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -98,12 +98,7 @@ pub fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) -> bool { if w.prop(p[0], p[1], p[2], "occupied") == Some("true") { return false; } - m.extra.ints[1] = match w.prop(p[0], p[1], p[2], "facing") { - Some("north") => 1, - Some("south") => 2, - Some("west") => 3, - _ => 4, - }; + m.extra.ints[1] = bed_facing_code(w.prop(p[0], p[1], p[2], "facing")); m.nav_stop(); ext_mut(m).last_slept = Some(w.game_time); m.velocity = horizon_core::geometry::Vec3::ZERO; @@ -144,6 +139,15 @@ pub fn stop_sleeping(m: &mut Mob, w: &MobWorld) { } /// `LivingEntityRenderer.sleepDirectionToRotation` and the bed's direction /// (the body is shifted back from the pillow by the standing eye height). +/// A bed's `facing` as `sleep_pose` keeps it in `ints[1]`. +pub fn bed_facing_code(facing: Option<&str>) -> i32 { + match facing { + Some("north") => 1, + Some("south") => 2, + Some("west") => 3, + _ => 4, + } +} pub fn sleep_pose(m: &Mob) -> Option<(f32, [f32; 2])> { Some(match m.extra.ints[1] { 1 => (270.0, [0.0, -1.0]), diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index ae70cccb8..bd22d6e0a 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -184,6 +184,7 @@ impl Server { equipment: Default::default(), health: 20.0, attributes: Vec::new(), + bed: None, living_flags: 0, }; let mut ctx = TickCtx { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 606321e99..8a20b3227 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -1219,6 +1219,11 @@ def check_sleep(host, guest, out): asleep = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), 'server': lan_guest(host).get('sleeping')} guest.shot(out, 'sleep-guest') + # The host draws the guest lying in its bed (#1045): in frame its model, on the server thread its + # client's (SLEEPING_POS), and a client pairing with the sleeper later too. + host.wait(5) + lying = {'host': lan_guest(host).get('model_lying') if not SERVER_THREAD else bool(remote(host)['lying_players'])} + host.shot(out, 'sleep-host-sees-guest') # Alone in bed: still night 120 ticks later (everyone must sleep). guest.wait(120) night = host('state')['time']['time_of_day'] @@ -1228,19 +1233,25 @@ def check_sleep(host, guest, out): up = guest('state').get('sleeping') guest.raw('interact', *guest_bed) host.raw('interact', *host_bed) - host.wait(130) + host.wait(5) + # Both in bed: the guest draws the host lying too. + lying['guest'] = bool(remote(guest)['lying_players']) + host.wait(125) after = {'guest': guest('state').get('sleeping'), 'host': host('state').get('sleeping'), 'time': host('state')['time']['time_of_day']} + lying['after'] = bool(remote(guest)['lying_players']) guest.shot(out, 'sleep-morning') for at in (guest_bed, host_bed): guest('command', command=f'fill {at[0] - 1} {at[1]} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') host('command', command='time set day') - detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after} + detail = {'asleep': asleep, 'night': night, 'up': up, 'after': after, 'lying': lying} assert asleep['guest'] == guest_bed and asleep['server'] == guest_bed, f'the guest is not in its bed: {detail}' assert asleep['host'] is None, f'the guest\'s bed put the host to sleep: {detail}' assert 13000 < night < 23000, f'one of two players asleep ended the night: {detail}' assert up is None, f'Escape did not get the guest up: {detail}' assert after['guest'] is None and after['host'] is None and after['time'] < 1000, f'no morning: {detail}' + assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}' + assert not lying['after'], f'a player up again is still drawn lying: {detail}' return detail def check_push(host, guest, out): guest('command', command='gamemode survival') From d7701e7e26ef9bbd78b10ec8167fdfe470c06f0a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:16:43 +0200 Subject: [PATCH 016/115] Ominous item spawners are saved with their chunk OminousItemSpawner.addAdditionalSaveData keeps its item and spawn_item_after_ticks; Horizon saved neither, so an ominous trial spawner's key or potion floating mid-wave vanished when the world closed or its chunk unloaded. They are now written with the chunk's entities (UUID and unmodelled fields kept), read back as live spawners whose tick count starts again from 0 (Entity.tickCount isn't saved), and leave the level with their chunk. Fixes #462 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity_nbt.rs | 69 +++++++++++++++++++ .../src/game/ominous_item_spawner.rs | 33 +++++++-- crates/horizon-client/src/game/persist.rs | 16 +++++ 3 files changed, 113 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index a42bc8ba6..d9cf20db5 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -918,6 +918,43 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option, +) -> Tag { + let base = Base { + id: "minecraft:ominous_item_spawner", + uuid, + position, + motion: Vec3::ZERO, + rotation: [0.0, 0.0], + on_ground: false, + fall_distance: 0.0, + }; + let mut tag = base.tag(raw); + put(&mut tag, "item", item_to_nbt(item)); + put( + &mut tag, + "spawn_item_after_ticks", + Tag::Long(spawn_item_after), + ); + tag +} +/// `OminousItemSpawner.readAdditionalSaveData`: the item, where it floats +/// and `spawn_item_after_ticks` (0 when absent). None without an item: +/// such a spawner would spawn nothing. +pub fn ominous_item_spawner_from_nbt(tag: &Tag) -> Option<(crate::items::ItemStack, Vec3, i64)> { + let item = tag.get("item").and_then(item_from_nbt)?; + let after = number(tag.get("spawn_item_after_ticks")).unwrap_or(0); + Some((item, position(tag)?, after)) +} + /// `ExperienceOrb`: Health, Age, Value, Count. pub fn orb_to_nbt(o: &ExperienceOrb, uuid: [i32; 4]) -> Tag { let base = Base { @@ -1505,6 +1542,38 @@ mod tests { use super::*; use crate::items::ItemStack; + /// The item, the spawn delay and the fields Horizon doesn't model come + /// back; a compound without an item is no spawner. + #[test] + fn ominous_item_spawner_round_trip() { + let item = ItemStack { + item: Arc::from("minecraft:ominous_trial_key"), + count: 1, + damage: 0, + extra: None, + }; + let raw = Tag::compound([("CustomName", string("kept"))]); + let at = Vec3::new(10.5, 64.25, -3.5); + let tag = ominous_item_spawner_to_nbt(&item, at, 97, [1, 2, 3, 4], Some(&raw)); + assert_eq!( + kind(&tag).as_deref(), + Some("minecraft:ominous_item_spawner") + ); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + assert!(matches!( + tag.get("spawn_item_after_ticks"), + Some(Tag::Long(97)) + )); + assert!(tag.get("CustomName").is_some()); + let (back, pos, after) = ominous_item_spawner_from_nbt(&tag).unwrap(); + assert_eq!( + (back.item.as_ref(), back.count), + ("minecraft:ominous_trial_key", 1) + ); + assert_eq!((pos, after), (at, 97)); + assert!(ominous_item_spawner_from_nbt(&raw).is_none()); + } + #[test] fn falling_block_round_trip_keeps_impact_distance_and_settings() { let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); diff --git a/crates/horizon-client/src/game/ominous_item_spawner.rs b/crates/horizon-client/src/game/ominous_item_spawner.rs index 1470a3124..8084faf9e 100644 --- a/crates/horizon-client/src/game/ominous_item_spawner.rs +++ b/crates/horizon-client/src/game/ominous_item_spawner.rs @@ -1,8 +1,7 @@ //! `OminousItemSpawner`: the item an ominous trial spawner drops on its //! fight. It floats, growing and turning (`OminousItemSpawnerRenderer`), for //! 60 to 120 ticks, then falls as an item or is fired straight down as a -//! projectile (`spawnItem`). Not saved: a spawner left in an unloaded chunk -//! is lost. +//! projectile (`spawnItem`). Saved with its chunk's entities (persist.rs). use super::Game; use horizon_assets::item_model::DisplayContext; use horizon_client::{ @@ -22,10 +21,14 @@ const TICKS_SCALING: f32 = 50.0; const ROTATION_SPEED: f32 = 40.0; pub(super) struct OminousItemSpawner { - item: ItemStack, - position: [f64; 3], - spawn_item_after: i64, + pub(super) item: ItemStack, + pub(super) position: [f64; 3], + pub(super) spawn_item_after: i64, tick_count: i64, + /// Its UUID, and the compound it was loaded from (fields Horizon doesn't + /// model survive a save). + pub(super) uuid: [i32; 4], + pub(super) raw: Option>, } /// `ProjectileItem.DispenseConfig` of the items fired down: power, @@ -66,6 +69,26 @@ impl Game<'_> { position, spawn_item_after: i64::from(delay), tick_count: 0, + uuid: horizon_client::save::random_uuid(), + raw: None, + }); + } + /// A saved spawner, as `readAdditionalSaveData` leaves it: its tick + /// count starts again from 0. + pub(super) fn load_ominous_item_spawner(&mut self, tag: horizon_world::nbt::Tag) { + let Some((item, at, spawn_item_after)) = + horizon_client::entity_nbt::ominous_item_spawner_from_nbt(&tag) + else { + return; + }; + self.ominous_spawners.push(OminousItemSpawner { + item, + position: [at.x, at.y, at.z], + spawn_item_after, + tick_count: 0, + uuid: horizon_client::entity_nbt::uuid(&tag) + .unwrap_or_else(horizon_client::save::random_uuid), + raw: Some(Box::new(tag)), }); } /// Every item spawner's tick: `commonTick`'s count, `tickServer` (the diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 3e824e72e..eb30ab5ed 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -274,6 +274,7 @@ impl Game<'_> { self.carts.push(c); } } + "minecraft:ominous_item_spawner" => self.load_ominous_item_spawner(tag), "minecraft:ender_dragon" => { let seed = self.world.random.next_long(); if self.dragon.is_none() @@ -685,6 +686,19 @@ impl Game<'_> { .push(c.to_nbt(uuid, raw.as_ref())); } } + for s in &self.ominous_spawners { + let at = Vec3::new(s.position[0], s.position[1], s.position[2]); + if keys.contains(&chunk_of(at)) { + let tag = entity_nbt::ominous_item_spawner_to_nbt( + &s.item, + at, + s.spawn_item_after, + s.uuid, + s.raw.as_deref(), + ); + out.entry(chunk_of(at)).or_default().push(tag); + } + } for c in &self.carts { if keys.contains(&chunk_of(c.position)) { let uuid = self @@ -774,6 +788,8 @@ impl Game<'_> { keep }); self.crystals.retain(|c| !gone(c.position)); + self.ominous_spawners + .retain(|s| !gone(Vec3::new(s.position[0], s.position[1], s.position[2]))); if self.dragon.as_ref().is_some_and(|d| gone(d.position)) { self.dragon = None; } From 33183952d54524a91c7c2bcdae1639268bc20602 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:15:17 +0200 Subject: [PATCH 017/115] Hurt and attack logs per player, read with `hurtlog` on the control socket Every hurt a player takes (PlayerMotion::hurt_blocking, which all player damage goes through) is kept: the damage type, the amount before blocking and armour, what a raised blocking item stopped, the health and absorption lost, the armour and armour toughness it met, the fire ticks, the health left and, for a mob's blow, the knockback it gave. Every melee blow on a mob is kept too: the damage after the attack strength (getAttackStrengthScale), the strength, a critical hit, the mob, whether it landed and killed. The last 64 of each are kept. `hurtlog` on the control socket hands them out, per player (the host and each LAN guest), and clears them: a harness can read what a fight did hit by hit and compare it with vanilla's numbers. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit fdfa952379cbed89db1b46077a4ce11b99083e5a) --- crates/horizon-client/src/game.rs | 19 +++++- crates/horizon-client/src/game/control.rs | 48 +++++++++++++++ crates/horizon-client/src/game/creatures.rs | 5 ++ crates/horizon-client/src/health.rs | 65 +++++++++++++++++++++ crates/horizon-client/src/motion.rs | 7 +++ 5 files changed, 143 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 460899bff..b1cac5ee7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -6808,7 +6808,24 @@ impl Game<'_> { Some(f) => self.attack_source(f), None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic), }; - if self.hurt_by_player(index, amount, source) { + let landed = self.hurt_by_player(index, amount, source); + if let Some(p) = self.player.as_mut() { + if p.attack_log.len() >= 64 { + p.attack_log.remove(0); + } + p.attack_log.push(horizon_client::health::AttackRecord { + game_time: p.health.game_time(), + target: target_kind.clone(), + id: self.mobs[index].id, + killed: landed && !self.mobs[index].alive(), + amount, + scale, + crit, + landed, + dealt: old_health - self.mobs[index].health, + }); + } + if landed { if knockback > 0.0 { let (xd, zd) = self.extra_knockback_direction(); self.mobs[index].knockback(f64::from(knockback), xd, zd); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 5cdf46110..c6c0e2225 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -24,6 +24,7 @@ const HELP: &[&str] = &[ "time TICKS set the time of day", "summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)", "mobs [RADIUS] list mobs near the player with their AI state", + "hurtlog the hurts taken and melee attacks made since the last call, per player (host and guests)", "fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of loaded blocks", "resume leave the pause menu", "screenshot PATH write the next frame as PNG", @@ -450,6 +451,10 @@ impl Game<'_> { let radius: f64 = words.get(1).map_or(Ok(64.0), |r| r.parse())?; Ok(Some(self.control_mobs(radius))) } + "hurtlog" => { + self.require_world()?; + Ok(Some(self.control_hurt_log())) + } "resume" => { if self.screen == Screen::Paused { self.screen = Screen::Playing; @@ -707,6 +712,49 @@ impl Game<'_> { } } + /// The hurts and melee attacks each player logged since the last call + /// (`PlayerMotion::hurt_log`, `attack_log`), taken out. + fn control_hurt_log(&mut self) -> Value { + fn drain(name: &str, p: &mut horizon_client::motion::PlayerMotion) -> Value { + let hurts: Vec = p + .hurt_log + .drain(..) + .map(|r| { + json!({ + "t": r.game_time, "source": r.source, "amount": r.amount, + "blocked": r.blocked, "taken": r.taken, "hurt": r.hurt, + "armor": r.armor, "toughness": r.toughness, "health": r.health, + "fire_ticks": r.fire_ticks, "knockback": r.knockback, + }) + }) + .collect(); + let attacks: Vec = p + .attack_log + .drain(..) + .map(|r| { + json!({ + "t": r.game_time, "target": r.target, "id": r.id, "killed": r.killed, "amount": r.amount, + "scale": r.scale, "crit": r.crit, "landed": r.landed, "dealt": r.dealt, + }) + }) + .collect(); + json!({ "name": name, "hurts": hurts, "attacks": attacks }) + } + let mut players = Vec::new(); + if let Some(p) = self.player.as_mut() { + players.push(drain("host", p)); + } + if let Some(host) = self.lan.as_mut() { + for g in &mut host.hub.guests { + let name = g.name.clone(); + if let Some(m) = g.motion.as_mut() { + players.push(drain(&name, m)); + } + } + } + json!({ "ok": true, "players": players }) + } + fn control_status(&self) -> Value { let player = self.player.as_ref().map(|p| { json!({ diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 113558e34..d1645c087 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1442,6 +1442,11 @@ impl Game<'_> { { let (xd, zd) = (from[0] - player.position.x, from[2] - player.position.z); self.knock_back_player(f64::from(0.4_f32), xd, zd); + if let Some(p) = self.player.as_mut() + && let Some(r) = p.hurt_log.last_mut() + { + r.knockback = Some([p.velocity.x, p.velocity.y, p.velocity.z]); + } self.hurt_armor(amount); self.thorns(from); } diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 493488732..442a826f0 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -231,6 +231,10 @@ impl PlayerHealth { .get(self.ids.absorption) .expect("validated absorption field") } + /// The game time the damage clock has counted. + pub fn game_time(&self) -> i64 { + self.game_time + } pub fn dead_or_dying(&self) -> bool { self.health() <= 0.0 || self.dead } @@ -274,6 +278,11 @@ impl PlayerMotion { .damage .source::<()>(source, None, None, None) .ok_or("unknown resident damage source")?; + let armor = self.attribute("minecraft:armor").unwrap_or(0.0) as f32; + let toughness = self.attribute("minecraft:armor_toughness").unwrap_or(0.0) as f32; + let before = self.health.health() + self.health.absorption(); + let fire_ticks = self.fire_ticks; + let source_name = source.definition().name.clone(); let totem_ready = self.health.totem_ready; let invulnerable = self.invulnerable; let h = &mut self.health; @@ -312,6 +321,23 @@ impl PlayerMotion { if outcome.hurt { h.hurt_animation_time = h.hurt.hurt_time; } + let after = h.health() + h.absorption(); + if self.hurt_log.len() >= HURT_LOG { + self.hurt_log.remove(0); + } + self.hurt_log.push(HurtRecord { + game_time: h.game_time, + source: source_name, + amount, + blocked: outcome.blocked, + taken: before - after, + hurt: outcome.hurt, + armor, + toughness, + health: after, + fire_ticks, + knockback: None, + }); Ok(outcome) } pub fn set_health(&mut self, value: f32, absorption: bool) -> Result<()> { @@ -363,6 +389,45 @@ pub struct Blocking { /// Angle between the head's view and the source position (pi without one). pub angle: f64, } +/// How many hurts `PlayerMotion::hurt_log` keeps. +const HURT_LOG: usize = 64; +/// One hurt as it was taken: what came in, what a raised blocking item +/// stopped, the armour it met and what health it left. +#[derive(Clone, Debug, PartialEq)] +pub struct HurtRecord { + pub game_time: i64, + /// The damage type. + pub source: String, + /// The damage before blocking, armour and effects. + pub amount: f32, + pub blocked: f32, + /// Health and absorption lost. + pub taken: f32, + pub hurt: bool, + /// `minecraft:armor` and `minecraft:armor_toughness` when it came. + pub armor: f32, + pub toughness: f32, + pub health: f32, + /// The fire ticks before the hurt. + pub fire_ticks: i32, + /// The push the hurt gave, if the caller applied one. + pub knockback: Option<[f64; 3]>, +} +/// One melee attack on a mob: the damage after the attack strength, the +/// strength (`getAttackStrengthScale`), and the health it took. +#[derive(Clone, Debug, PartialEq)] +pub struct AttackRecord { + pub game_time: i64, + pub target: String, + /// The mob's entity id, and whether the blow killed it. + pub id: u32, + pub killed: bool, + pub amount: f32, + pub scale: f32, + pub crit: bool, + pub landed: bool, + pub dealt: f32, +} /// The outcome of a hurt with a raised blocking item. #[derive(Clone, Copy, Debug, Default)] pub struct BlockOutcome { diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index a2fbd47ba..b25915085 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -290,6 +290,11 @@ pub struct PlayerMotion { /// The powder snow blocks this tick's movement went into: the game /// destroys them if the player is burning, then puts the fire out. pub powder_snow_entered: Vec, + /// The last hurts taken (`hurt_blocking`), newest last, for tests and + /// the control socket's `hurtlog`. + pub hurt_log: Vec, + /// The last melee attacks made on mobs, newest last. + pub attack_log: Vec, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -434,6 +439,8 @@ impl PlayerMotion { old_position: position, block_effects: true, powder_snow_entered: Vec::new(), + hurt_log: Vec::new(), + attack_log: Vec::new(), }) } /// `Entity.getTicksRequiredToFreeze`. From 169be6374c43ede203f7b0eb97eeebc4b5f68fcc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 12:09:18 +0200 Subject: [PATCH 018/115] hurtlog keeps a LAN guest's hurts across a respawn A guest's body is rebuilt when it respawns, and its hurt and attack logs went with the old one: the control socket's hurtlog lost the hurts that killed it whenever the death and the respawn fell between two reads. The logs now pass to the new body, and a dead guest's are read too. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit df9fa5f0185766f7a7338df5046200d1a2e67d22) --- crates/horizon-client/src/game/control.rs | 19 ++++++++++++------- crates/horizon-client/src/game/lan_actions.rs | 10 +++++++++- crates/horizon-client/src/lan/guest.rs | 8 ++++++++ 3 files changed, 29 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index c6c0e2225..bb1728ad3 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -715,9 +715,12 @@ impl Game<'_> { /// The hurts and melee attacks each player logged since the last call /// (`PlayerMotion::hurt_log`, `attack_log`), taken out. fn control_hurt_log(&mut self) -> Value { - fn drain(name: &str, p: &mut horizon_client::motion::PlayerMotion) -> Value { - let hurts: Vec = p - .hurt_log + fn drain( + name: &str, + hurt_log: &mut Vec, + attack_log: &mut Vec, + ) -> Value { + let hurts: Vec = hurt_log .drain(..) .map(|r| { json!({ @@ -728,8 +731,7 @@ impl Game<'_> { }) }) .collect(); - let attacks: Vec = p - .attack_log + let attacks: Vec = attack_log .drain(..) .map(|r| { json!({ @@ -742,13 +744,16 @@ impl Game<'_> { } let mut players = Vec::new(); if let Some(p) = self.player.as_mut() { - players.push(drain("host", p)); + players.push(drain("host", &mut p.hurt_log, &mut p.attack_log)); } if let Some(host) = self.lan.as_mut() { for g in &mut host.hub.guests { let name = g.name.clone(); if let Some(m) = g.motion.as_mut() { - players.push(drain(&name, m)); + players.push(drain(&name, &mut m.hurt_log, &mut m.attack_log)); + } else if let Some((mut hurts, mut attacks)) = g.logs_kept.take() { + // Dead, not yet respawned: what its last body logged. + players.push(drain(&name, &mut hurts, &mut attacks)); } } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..34fb88be5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -200,6 +200,11 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + let kept = host.hub.guests[i].logs_kept.take(); + if let (Some(m), Some((hurts, attacks))) = (host.hub.guests[i].motion.as_mut(), kept) { + m.hurt_log = hurts; + m.attack_log = attacks; + } } let mut play = host.play.remove(&conn).unwrap_or_default(); let g = &mut host.hub.guests[i]; @@ -1336,7 +1341,10 @@ impl Game<'_> { g.food = 20; g.saturation = 5.0; g.sent_health = None; - g.motion = None; + if let Some(m) = g.motion.take() { + let m = *m; + g.logs_kept = Some((m.hurt_log, m.attack_log)); + } let mut xp = Experience { level: g.xp_level, progress: g.xp_progress, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 91bf2709f..f46e37abc 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -122,6 +122,13 @@ pub struct Guest { pub tracker: Tracker, // Player state the gameplay code reads and writes. pub motion: Option>, + /// The hurt and attack logs of the body it had before it respawned, + /// until the new body takes them over (the control socket's `hurtlog` + /// reads across a death). + pub logs_kept: Option<( + Vec, + Vec, + )>, /// The 36 inventory slots (hotbar first), armor (head..feet) and off hand. pub inventory: Vec>, pub armor: [Option; 4], @@ -251,6 +258,7 @@ impl Guest { batch_quota: 0.0, tracker: Tracker::default(), motion: None, + logs_kept: None, inventory: vec![None; 36], armor: [None, None, None, None], offhand: None, From 369179f331290013a639bcefa42b33776a8bb1e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:22:11 +0200 Subject: [PATCH 019/115] The locator bar has one waypoint manager per level Vanilla keeps a ServerWaypointManager per level: a player in another level is neither a transmitter nor a receiver there. Horizon passed every player to one manager whatever their dimension, so a player who went to the Nether stayed tracked at their Nether coordinates by the players left in the Overworld (`track Bob block 0 100 0`), and nothing was re-tracked when they came back. Each level now has its own manager, ticked with the players in that level: a player changing level leaves the old one (untracked for everyone there, as ServerLevel.removePlayerImmediately) and joins the new one (addDuringTeleport). The player-targets and dimension-players harnesses now compare the waypoints too, instead of leaving them out. Fixes #843 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan.rs | 7 +- .../horizon-client/src/game/lan_waypoints.rs | 103 ++++++++++++------ tools/test_server_dimension_players_parity.py | 15 ++- tools/test_server_player_targets_parity.py | 8 +- 4 files changed, 87 insertions(+), 46 deletions(-) diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 18325828d..28965f0dc 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -59,9 +59,10 @@ pub(super) struct LanHost { pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). pub owner: Option, - /// The players' locator bars (game/lan_waypoints.rs), and the guests who - /// are dead, whose respawn replaces their waypoint. - pub waypoints: lan::waypoints::Waypoints, + /// The players' locator bars, one waypoint manager per level by + /// dimension id (game/lan_waypoints.rs), and the guests who are dead, + /// whose respawn replaces their waypoint. + pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). diff --git a/crates/horizon-client/src/game/lan_waypoints.rs b/crates/horizon-client/src/game/lan_waypoints.rs index 0d0ab69e4..44ca69939 100644 --- a/crates/horizon-client/src/game/lan_waypoints.rs +++ b/crates/horizon-client/src/game/lan_waypoints.rs @@ -1,5 +1,5 @@ //! The locator bar of the players on a served world (lan/waypoints.rs): what -//! each player looks like to the waypoint manager this tick. +//! each player looks like to their level's waypoint manager this tick. use super::{Game, lan::LanHost}; use horizon_client::{ items::ItemStack, @@ -27,8 +27,12 @@ impl Game<'_> { Some((team.name.clone(), color)) } + /// Each level's `ServerWaypointManager` ticked with the players in that + /// level: a player who changes level leaves the old one's manager + /// (`ServerLevel.removePlayerImmediately`: untracked for everyone there) + /// and joins the new one's (`addDuringTeleport`). pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) { - let mut players = Vec::new(); + let mut players: Vec<(&str, waypoints::Player)> = Vec::new(); if let Some(h) = state { let icon = self .cmds @@ -39,22 +43,25 @@ impl Game<'_> { color: i.color, }) .unwrap_or_default(); - players.push(waypoints::Player { - uuid: h.uuid, - conn: None, - position: h.position, - spectator: self.spectator(), - transmit_range: transmit_range( - h.sneaking, - self.potions.effects.get("invisibility").is_some(), - h.equipment[5].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: false, - view_distance: host.hub.config.view_distance, - team: self.waypoint_team(&h.name), - icon, - }); + players.push(( + self.dim.id(), + waypoints::Player { + uuid: h.uuid, + conn: None, + position: h.position, + spectator: self.spectator(), + transmit_range: transmit_range( + h.sneaking, + self.potions.effects.get("invisibility").is_some(), + h.equipment[5].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: false, + view_distance: host.hub.config.view_distance, + team: self.waypoint_team(&h.name), + icon, + }, + )); } let mut respawned = Vec::new(); for g in host.hub.guests.iter().filter(|g| g.placed) { @@ -66,27 +73,51 @@ impl Game<'_> { } // Player.updatePlayerPose: the shift key crouches unless flying. let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping; - players.push(waypoints::Player { - uuid: g.uuid, - conn: Some(g.conn), - position: g.position, - spectator: g.spectator(), - transmit_range: transmit_range( - crouching, - g.effects.get("invisibility").is_some(), - g.armor[0].as_ref(), - ), - receive_range: PLAYER_RANGE, - first_tick: g.ticks == 0, - view_distance: g.view_distance, - team: self.waypoint_team(&g.name), - icon: Icon::default(), - }); + players.push(( + &g.dimension, + waypoints::Player { + uuid: g.uuid, + conn: Some(g.conn), + position: g.position, + spectator: g.spectator(), + transmit_range: transmit_range( + crouching, + g.effects.get("invisibility").is_some(), + g.armor[0].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: g.ticks == 0, + view_distance: g.view_distance, + team: self.waypoint_team(&g.name), + icon: Icon::default(), + }, + )); } host.waypoint_dead - .retain(|uuid| players.iter().any(|p| p.uuid == *uuid)); + .retain(|uuid| players.iter().any(|(_, p)| p.uuid == *uuid)); let locator_bar = self.ui.rules.bool("locator_bar"); - for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) { + let mut levels: Vec = host.waypoints.keys().cloned().collect(); + for (level, _) in &players { + if !levels.iter().any(|l| l == level) { + levels.push((*level).to_owned()); + } + } + levels.sort(); + let mut out = Vec::new(); + for level in levels { + let here: Vec = players + .iter() + .filter(|(l, _)| *l == level) + .map(|(_, p)| p.clone()) + .collect(); + let manager = host.waypoints.entry(level.clone()).or_default(); + out.extend(manager.tick(&here, &respawned, locator_bar)); + // Nobody left in the level: nothing to remember there. + if here.is_empty() { + host.waypoints.remove(&level); + } + } + for (conn, packet) in out { if let Some(g) = host.hub.guest(conn) { g.send(&packet); } diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 77e1428e9..4ff594e96 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -93,9 +93,18 @@ def run_side(label, server_command, client_command, build, world): return out.read_text(encoding='utf-8').splitlines() +SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') + + def shown(lines): - """Each player's adds, removes and respawns, without the waypoints (the locator bar harness has those).""" - return [l for l in lines if l.split(' ', 2)[2:3] and l.split(' ', 2)[2].split(' ')[0] in ('add', 'remove', 'respawn')] + """Each player's adds, removes, respawns and waypoints, step by step; sorted within a step (the packets of one + step may leave in another order within the tick).""" + steps = {} + for line in lines: + parts = line.split(' ', 2) + if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: + steps.setdefault((parts[0], parts[1]), []).append(line) + return [l for key in steps for l in sorted(steps[key])] def main(): @@ -139,7 +148,7 @@ def main(): java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), scope='Two players on a dedicated server changing dimensions (Nether, End, back): the other players each ' - 'is sent and loses, and the dimensions it respawns into.')) + 'is sent and loses, the dimensions it respawns into and its locator bar waypoints.')) print(f'server dimension players: {len(vanilla)} lines identical') diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index f8f457143..4e925500f 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -11,8 +11,9 @@ vanilla generated first, with Alice and Bob as operators in creative. LocatorBar of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly, -in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints -and what a death does besides its messages are left to their own harnesses. +in sorted order (the packets of one step may leave in another order within the tick), with the locator bar's +waypoints (one manager per level: a player in another level is untracked). What a death does besides its messages +is left to its own harness. """ import hashlib import os @@ -78,7 +79,6 @@ SCRIPT = [ ] # What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does # besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`. -WAYPOINTS = ('track ', 'untrack ', 'update ') DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 @@ -134,7 +134,7 @@ def run_side(label, server_command, client_command, build, world): # At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla. death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed ')) or 'chat.type.advancement' in rest) - if rest.startswith(WAYPOINTS) or death_side: + if death_side: continue if step != 'step=start': steps.setdefault((who, step), []).append(line) From 815625e54731ee41e2dd2ffda887689220c2a99b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 20 Oct 2026 23:56:08 +0200 Subject: [PATCH 020/115] Advancement triggers test only the criteria that can pass; the log writes on its own thread Two main-thread costs from the hub tick (found on the companion branch with HORIZON_SPIKES, commit 060c795e; its companion and metering parts stay there): - Every inventory change tested all ~1,900 inventory_changed criteria, and every recipe unlocked (an iron ingot unlocks dozens) all ~1,300 recipe_unlocked ones: 1.5-5 ms on such a tick. The tree now indexes inventory_changed criteria by the items that can pass them (tags resolved; the few without an item list are always tried) and recipe_unlocked criteria by recipe, so a change tests the 20-40 that could match. Same answers: a criterion with an item-limited predicate can only pass with one of those items held. - Each log line was an unbuffered stderr write plus a latest.log write under a mutex on the calling thread; a full pipe or a slow disk held the tick. The logger now formats the line and keeps it for crash reports on the calling thread and hands the I/O to a "Log writer" thread; flush() waits for it (crash report, exit). (cherry picked from commit 060c795e, companion parts left out) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/advancements.rs | 191 ++++++++++++++++++ .../horizon-client/src/game/advancements.rs | 59 +++++- crates/horizon-client/src/logging.rs | 158 +++++++++++---- 3 files changed, 362 insertions(+), 46 deletions(-) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 16028e220..484fbfcf2 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -53,6 +53,10 @@ pub struct Tree { pub by_id: HashMap, /// trigger id -> (advancement index, criterion index). pub by_trigger: HashMap>, + /// `recipe_unlocked` criteria by the recipe they name (`index_recipes`); + /// those naming none in `recipes_any`. + by_recipe: HashMap>, + recipes_any: Vec<(usize, usize)>, } fn frame(v: &Value) -> Frame { match v.as_str() { @@ -93,12 +97,111 @@ impl Tree { tree.list.push(a); } } + tree.index_recipes(); tree } + /// Index the `recipe_unlocked` criteria by recipe: a grant that unlocks + /// twenty recipes tested every one of the ~1,300 recipe advancements' + /// criteria for each (several ms in one tick). + pub fn index_recipes(&mut self) { + self.by_recipe.clear(); + self.recipes_any.clear(); + for &(ai, ci) in self + .by_trigger + .get("minecraft:recipe_unlocked") + .into_iter() + .flatten() + { + match self.list[ai].criteria[ci].conditions["recipes"].as_str() { + Some(r) => self + .by_recipe + .entry(r.to_owned()) + .or_default() + .push((ai, ci)), + None => self.recipes_any.push((ai, ci)), + } + } + } + /// The `recipe_unlocked` criteria that could pass for `recipe`, in tree + /// order (the others name another recipe). + pub fn recipe_criteria(&self, recipe: &str) -> Vec<(usize, usize)> { + let mut out = self.recipes_any.clone(); + out.extend(self.by_recipe.get(recipe).into_iter().flatten()); + out.sort_unstable(); + out + } pub fn get(&self, id: &str) -> Option<&Advancement> { self.by_id.get(id).map(|&i| &self.list[i]) } } + +/// The `inventory_changed` criteria by the items they need. A criterion whose +/// item predicates include one limited to some items (an id, a `#tag`, a +/// list) can only pass with one of those in the inventory, so an inventory +/// change tests only the criteria of the items it holds, plus those that +/// need no particular item. The same answers as testing them all: the ~1,300 +/// recipe advancements each have one, and testing every one of them cost a +/// player 1–4 ms on every tick its inventory changed. +#[derive(Default)] +pub struct InventoryIndex { + by_item: HashMap>, + any: Vec<(usize, usize)>, +} +impl InventoryIndex { + /// `tag` gives a `#tag`'s item ids (none for a tag that doesn't exist, + /// which matches nothing). + pub fn build<'t>(tree: &Tree, tag: impl Fn(&str) -> Vec<&'t str>) -> Self { + fn ids<'t>(v: &Value, tag: &impl Fn(&str) -> Vec<&'t str>, out: &mut Vec) { + match v { + Value::String(s) => match s.strip_prefix('#') { + Some(t) => out.extend(tag(t).into_iter().map(str::to_owned)), + None => out.push(s.clone()), + }, + Value::Array(a) => a.iter().for_each(|x| ids(x, tag, out)), + _ => {} + } + } + let mut index = Self::default(); + let Some(list) = tree.by_trigger.get("minecraft:inventory_changed") else { + return index; + }; + for &(ai, ci) in list { + let items = &tree.list[ai].criteria[ci].conditions["items"]; + // `id_matches`: only a string or a list limits the items. + let limited = items.as_array().and_then(|a| { + a.iter() + .map(|p| &p["items"]) + .find(|v| v.is_string() || v.is_array()) + }); + match limited { + Some(v) => { + let mut out = Vec::new(); + ids(v, &tag, &mut out); + out.sort(); + out.dedup(); + for id in out { + index.by_item.entry(id).or_default().push((ai, ci)); + } + } + None => index.any.push((ai, ci)), + } + } + index + } + /// The criteria an inventory holding these item ids could pass, in + /// tree order. + pub fn candidates<'a>(&self, held: impl IntoIterator) -> Vec<(usize, usize)> { + let mut out = self.any.clone(); + for id in held { + if let Some(list) = self.by_item.get(id) { + out.extend_from_slice(list); + } + } + out.sort_unstable(); + out.dedup(); + out + } +} fn collect(root: &Path, dir: &Path, ns: &str, out: &mut Vec<(String, std::path::PathBuf)>) { let Ok(entries) = std::fs::read_dir(dir) else { return; @@ -1090,6 +1193,94 @@ mod tests { stack.id = "minecraft:tnt".into(); } } + /// Only the criteria the held items could pass are tested; those that + /// need no particular item always are. + #[test] + fn inventory_index_keeps_the_criteria_the_items_could_pass() { + let criteria = [ + serde_json::json!({"items": [{"items": "minecraft:diamond"}]}), + serde_json::json!({"items": [{"items": "#minecraft:planks"}]}), + serde_json::json!({"items": [{"count": {"min": 2}}]}), + serde_json::json!({"items": [{"count": 1}, {"items": ["minecraft:stick", "minecraft:apple"]}]}), + serde_json::json!({"slots": {"empty": 0}}), + serde_json::json!({"items": [{"items": "#minecraft:no_such_tag"}]}), + ]; + let mut tree = Tree::default(); + for (i, conditions) in criteria.into_iter().enumerate() { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:inventory_changed".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:inventory_changed".into()) + .or_default() + .push((i, 0)); + } + let index = InventoryIndex::build(&tree, |tag| match tag { + "minecraft:planks" => vec!["minecraft:oak_planks", "minecraft:birch_planks"], + _ => Vec::new(), + }); + let found = |held: &[&str]| -> Vec { + index + .candidates(held.iter().copied()) + .into_iter() + .map(|(ai, _)| ai) + .collect() + }; + assert_eq!(found(&[]), [2, 4]); + assert_eq!(found(&["minecraft:dirt"]), [2, 4]); + assert_eq!( + found(&["minecraft:oak_planks", "minecraft:diamond"]), + [0, 1, 2, 4] + ); + assert_eq!(found(&["minecraft:apple", "minecraft:apple"]), [2, 3, 4]); + } + /// A recipe unlocked tests only the criteria that name it. + #[test] + fn recipe_index_keeps_the_criteria_of_the_recipe() { + let mut tree = Tree::default(); + for (i, conditions) in [ + serde_json::json!({"recipes": "minecraft:oak_planks"}), + serde_json::json!({"recipes": "minecraft:stick"}), + serde_json::json!({}), + serde_json::json!({"recipes": "minecraft:oak_planks"}), + ] + .into_iter() + .enumerate() + { + tree.list.push(Advancement { + id: format!("test:{i}"), + parent: None, + display: None, + criteria: vec![Criterion { + name: "c".into(), + trigger: "minecraft:recipe_unlocked".into(), + conditions, + }], + requirements: vec![vec!["c".into()]], + rewards: Rewards::default(), + }); + tree.by_trigger + .entry("minecraft:recipe_unlocked".into()) + .or_default() + .push((i, 0)); + } + tree.index_recipes(); + assert_eq!( + tree.recipe_criteria("minecraft:oak_planks"), + [(0, 0), (2, 0), (3, 0)] + ); + assert_eq!(tree.recipe_criteria("minecraft:stick"), [(1, 0), (2, 0)]); + assert_eq!(tree.recipe_criteria("minecraft:torch"), [(2, 0)]); + } #[test] fn bucket_axolotl_block_advancements_require_the_placed_block() { let ctx = Entities { diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index d13ed6b13..b0f948c5d 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -91,6 +91,8 @@ pub(super) struct AdvState { /// The tree being read on another thread since the world opened /// (`prefetch_advancement_tree`), taken by the first `advancement_tree`. pub(super) pending_tree: Option>, + /// `inventory_changed`'s criteria by item, built for `tree`. + inventory_index: Option<(Arc, Arc)>, } /// The game's world for predicates. struct View<'a, 'g>(&'a Game<'g>); @@ -229,9 +231,31 @@ impl Game<'_> { _ => Tree::load(&self.options.resources.join("data")), }; self.adv.tree = Arc::new(tree); + // With the tree, while the world loads: built on the first + // inventory change it cost that tick ~10 ms. + self.inventory_index(); } self.adv.tree.clone() } + /// `inventory_changed`'s criteria by item, for the tree in place. + fn inventory_index(&mut self) -> Arc { + let tree = self.adv.tree.clone(); + if let Some((built, index)) = &self.adv.inventory_index + && Arc::ptr_eq(built, &tree) + { + return index.clone(); + } + let items = self.res.items(); + let index = Arc::new(adv::InventoryIndex::build(&tree, |tag| { + items + .item_tags + .get(tag) + .map(|t| t.iter().map(String::as_str).collect()) + .unwrap_or_default() + })); + self.adv.inventory_index = Some((tree, index.clone())); + index + } /// Start reading the advancement files on another thread while the world /// loads. The first tick's first criterion trigger used to read and parse /// all of them on the game thread (about 60 ms). @@ -394,6 +418,16 @@ impl Game<'_> { let Some(list) = tree.by_trigger.get(name) else { return; }; + self.trigger_criteria(&tree, list, test); + } + /// `trigger` for some of a trigger's criteria: (advancement, criterion) + /// indexes in `tree`, in tree order. + fn trigger_criteria( + &mut self, + tree: &Tree, + list: &[(usize, usize)], + test: impl Fn(&Value, &dyn adv::World) -> bool, + ) { let mut hits = Vec::new(); { let view = View(self); @@ -437,9 +471,14 @@ impl Game<'_> { } else { self.recipe_toast(unlocked); } + if unlocked.is_empty() || self.remote.is_some() || self.no_player_here() { + return; + } + self.load_advancements(); + let tree = self.adv.tree.clone(); for r in unlocked { - let r = r.clone(); - self.trigger("minecraft:recipe_unlocked", move |c, _| { + let list = tree.recipe_criteria(r); + self.trigger_criteria(&tree, &list, |c, _| { c["recipes"].as_str() == Some(r.as_str()) }); } @@ -560,7 +599,15 @@ impl Game<'_> { .is_some_and(|i| s.count >= i.max_stack) }) .count() as f64; - self.trigger("minecraft:inventory_changed", move |c, w| { + // Only the criteria the items held could pass (`InventoryIndex`). + if self.remote.is_some() || self.no_player_here() { + return; + } + self.load_advancements(); + let tree = self.adv.tree.clone(); + let index = self.inventory_index(); + let list = index.candidates(stacks.iter().map(|s| s.id.as_str())); + self.trigger_criteria(&tree, &list, move |c, w| { let slots = &c["slots"]; let range = |k: &str, v: f64| { let r = &slots[k]; @@ -965,10 +1012,8 @@ impl Game<'_> { }); positions.push((a.x, a.y)); } - let mut tree = Tree { - list, - ..Tree::default() - }; + let mut tree = Tree::default(); + tree.list = list; for (i, a) in tree.list.iter().enumerate() { tree.by_id.insert(a.id.clone(), i); } diff --git a/crates/horizon-client/src/logging.rs b/crates/horizon-client/src/logging.rs index cb7638f26..282831f67 100644 --- a/crates/horizon-client/src/logging.rs +++ b/crates/horizon-client/src/logging.rs @@ -12,7 +12,7 @@ use std::collections::VecDeque; use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::sync::{Mutex, mpsc}; use chrono::{DateTime, Local, NaiveDate}; @@ -201,16 +201,74 @@ pub fn open_latest(dir: &Path) -> io::Result> { Ok(Some(Latest { file, _lock: lock })) } -struct State { +/// What the writer thread is told. +enum Out { + /// Lines for the file, dated, and the message for stderr (Horizon's own). + Write { + date: NaiveDate, + lines: Vec, + stderr: Option, + }, + /// Answer once everything before is written. + Flush(mpsc::SyncSender<()>), +} + +/// The file side of the log, on its own thread: a line costs the thread that logs it a +/// format and a channel send, never a write that can wait (a full stderr pipe, a slow disk): +/// written on the game thread, a line could hold the tick for milliseconds while the CPU sat +/// idle. +struct Writer { file: Option, dir: PathBuf, /// The day the open file's lines belong to. date: NaiveDate, - recent: VecDeque, +} + +impl Writer { + fn run(mut self, out: mpsc::Receiver) { + let stderr = io::stderr(); + for msg in out { + match msg { + Out::Write { + date, + lines, + stderr: message, + } => { + if let Some(message) = message { + let _ = writeln!(stderr.lock(), "{message}"); + } + if date != self.date { + if let Some(latest) = &mut self.file + && let Err(e) = roll(&mut latest.file, &self.dir, self.date) + { + let _ = writeln!( + stderr.lock(), + "Horizon: could not roll over the log: {e}" + ); + } + self.date = date; + } + if let Some(latest) = &mut self.file { + let mut text = lines.join("\n"); + text.push('\n'); + let _ = latest.file.write_all(text.as_bytes()); + } + } + Out::Flush(done) => { + if let Some(latest) = &mut self.file { + let _ = latest.file.flush(); + } + let _ = done.send(()); + } + } + } + } } struct Logger { - state: Mutex, + out: mpsc::Sender, + /// The last lines, kept here (not on the writer) so a crash report has them at once. + recent: Mutex>, /// What the main thread is called in the log: "Render thread", or "Server thread" for the /// dedicated server, as in vanilla. main_thread: &'static str, @@ -233,53 +291,66 @@ impl log::Log for Logger { return; } let message = record.args().to_string(); - if ours(record.target()) { - eprintln!("{message}"); - } let current = std::thread::current(); let thread = match current.name() { Some("main") => self.main_thread, Some(name) => name, None => "unnamed", }; - self.write(thread, record.level(), &message); + let stderr = ours(record.target()).then(|| message.clone()); + self.send(thread, record.level(), &message, stderr); } + /// Waits (a second at most) until every line logged before is in the file. fn flush(&self) { - if let Some(latest) = &mut self.state.lock().unwrap_or_else(|e| e.into_inner()).file { - let _ = latest.file.flush(); + let (done, wait) = mpsc::sync_channel(1); + if self.out.send(Out::Flush(done)).is_ok() { + let _ = wait.recv_timeout(std::time::Duration::from_secs(1)); } } } impl Logger { fn write(&self, thread: &str, level: log::Level, message: &str) { + self.send(thread, level, message, None); + } + + fn send(&self, thread: &str, level: log::Level, message: &str, stderr: Option) { let now = Local::now(); - let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); - let state = &mut *state; - if now.date_naive() != state.date { - if let Some(latest) = &mut state.file - && let Err(e) = roll(&mut latest.file, &state.dir, state.date) - { - eprintln!("Horizon: could not roll over the log: {e}"); - } - state.date = now.date_naive(); - } // As log4j writes a multi-line message: the pattern once, the rest as it is. - for (i, line) in message.lines().enumerate() { - let line = if i == 0 { - format_line(&now, thread, level, line) - } else { - line.to_owned() - }; - if let Some(latest) = &mut state.file { - let _ = writeln!(latest.file, "{line}"); - } - state.recent.push_back(line); - if state.recent.len() > RECENT { - state.recent.pop_front(); + let lines: Vec = message + .lines() + .enumerate() + .map(|(i, line)| { + if i == 0 { + format_line(&now, thread, level, line) + } else { + line.to_owned() + } + }) + .collect(); + { + let mut recent = self.recent.lock().unwrap_or_else(|e| e.into_inner()); + for line in &lines { + if recent.len() == RECENT { + recent.pop_front(); + } + recent.push_back(line.clone()); } } + let msg = Out::Write { + date: now.date_naive(), + lines, + stderr, + }; + if let Err(mpsc::SendError(Out::Write { + stderr: Some(message), + .. + })) = self.out.send(msg) + { + // No writer (it could not start): the terminal still gets Horizon's messages. + eprintln!("{message}"); + } } } @@ -304,14 +375,24 @@ pub fn init(home: &Path, main_thread: &'static str) { None } }; - let logger = LOGGER.get_or_init(|| Logger { - state: Mutex::new(State { + let logger = LOGGER.get_or_init(|| { + let (out, receive) = mpsc::channel(); + let writer = Writer { file, dir, date: Local::now().date_naive(), - recent: VecDeque::new(), - }), - main_thread, + }; + if let Err(e) = std::thread::Builder::new() + .name("Log writer".into()) + .spawn(move || writer.run(receive)) + { + eprintln!("Horizon: could not start the log writer: {e}"); + } + Logger { + out, + recent: Mutex::new(VecDeque::new()), + main_thread, + } }); if log::set_logger(logger).is_ok() { log::set_max_level(log::LevelFilter::Info); @@ -341,10 +422,9 @@ pub fn write_as(thread: &str, level: log::Level, message: &str) { /// The last lines written, oldest first (for crash reports). pub fn recent_lines() -> Vec { LOGGER.get().map_or_else(Vec::new, |l| { - l.state + l.recent .lock() .unwrap_or_else(|e| e.into_inner()) - .recent .iter() .cloned() .collect() From cc84150f6c75194655a79100fd7baef932dcc8b8 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:09:18 +0200 Subject: [PATCH 021/115] A player leaving a level loses its waypoints there ServerWaypointManager.removePlayer disconnects every waypoint the player was receiving: a player who goes to another level gets an untrack for each player it tracked in the one it left. Horizon's per-level managers tick with the players in their own level only, so the untrack had no connection to go to and the player kept the old level's markers. Each level's manager now also gets the connections of the players in the other levels, for these untracks. The player-targets and dimension-players harnesses compare the waypoints as each step leaves them (the last packet for each waypoint): arriving in a level, vanilla sends the same waypoint up to three times within the step, and the packet by packet order is test_locator_bar_parity's. Both pass: 123 and 40 lines identical. Part of #843 Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/src/game/lan_waypoints.rs | 7 ++- crates/horizon-client/src/lan/waypoints.rs | 51 ++++++++++++++++++- tools/test_server_dimension_players_parity.py | 17 +++++-- tools/test_server_player_targets_parity.py | 15 +++++- 4 files changed, 83 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/lan_waypoints.rs b/crates/horizon-client/src/game/lan_waypoints.rs index 44ca69939..ba1512a00 100644 --- a/crates/horizon-client/src/game/lan_waypoints.rs +++ b/crates/horizon-client/src/game/lan_waypoints.rs @@ -110,8 +110,13 @@ impl Game<'_> { .filter(|(l, _)| *l == level) .map(|(_, p)| p.clone()) .collect(); + let away: Vec<(u128, u32)> = players + .iter() + .filter(|(l, _)| *l != level) + .filter_map(|(_, p)| Some((p.uuid, p.conn?))) + .collect(); let manager = host.waypoints.entry(level.clone()).or_default(); - out.extend(manager.tick(&here, &respawned, locator_bar)); + out.extend(manager.tick_level(&here, &away, &respawned, locator_bar)); // Nobody left in the level: nothing to remember there. if here.is_empty() { host.waypoints.remove(&level); diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs index 852cfc4fb..3e92d820d 100644 --- a/crates/horizon-client/src/lan/waypoints.rs +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -153,6 +153,9 @@ pub struct Waypoints { /// One tick's players, and the packets for their connections. struct Tick<'a> { players: HashMap, + /// The connections of the players in other levels: one who just left this level is + /// still told of the waypoints it loses (`removePlayer` disconnects them). + away: &'a [(u128, u32)], view: HashMap, /// Players a respawn replaced this tick: a new ServerPlayer, on its first tick. fresh: &'a [u128], @@ -169,7 +172,17 @@ impl<'a> Tick<'a> { icon: &Icon, target: WaypointTarget, ) { - let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else { + let Some(conn) = self + .players + .get(&receiver) + .and_then(|p| p.conn) + .or_else(|| { + self.away + .iter() + .find(|(uuid, _)| *uuid == receiver) + .map(|&(_, conn)| conn) + }) + else { return; }; self.out @@ -449,9 +462,22 @@ impl Waypoints { players: &[Player], respawned: &[u128], locator_bar: bool, + ) -> Vec<(u32, C)> { + self.tick_level(players, &[], respawned, locator_bar) + } + + /// [`Self::tick`] for one level of several: `away` are the connections of the players + /// in the other levels, for the untracks owed to one who has just left this one. + pub fn tick_level( + &mut self, + players: &[Player], + away: &[(u128, u32)], + respawned: &[u128], + locator_bar: bool, ) -> Vec<(u32, C)> { let mut t = Tick { players: players.iter().map(|p| (p.uuid, p)).collect(), + away, view: HashMap::default(), fresh: respawned, enabled: locator_bar, @@ -632,6 +658,29 @@ mod tests { assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]); } + #[test] + fn a_player_leaving_the_level_loses_its_waypoints() { + let (a, b) = ( + player(1, 10, [0.5, 64.0, 0.5]), + player(2, 20, [4.5, 64.0, 0.5]), + ); + let mut w = Waypoints::default(); + w.tick(&[a.clone(), b.clone()], &[], true); + let mut moved = b.clone(); + moved.position = [5.5, 64.0, 0.5]; + w.tick(&[a.clone(), moved], &[], true); + // B goes to another level: A loses B, and B (reached through `away`) loses A. + let out = w.tick_level(std::slice::from_ref(&a), &[(2, 20)], &[], true); + assert_eq!( + to(&out, 10), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + assert_eq!( + to(&out, 20), + vec![(waypoint_operation::UNTRACK, WaypointTarget::Empty)] + ); + } + #[test] fn team_colours() { assert_eq!(team_rgb("red"), Some(0xFF5555)); diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 4ff594e96..8453d14af 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -96,15 +96,26 @@ def run_side(label, server_command, client_command, build, world): SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(' ') + return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def shown(lines): - """Each player's adds, removes, respawns and waypoints, step by step; sorted within a step (the packets of one - step may leave in another order within the tick).""" + """Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a + step (the packets of one step may leave in another order within the tick).""" steps = {} for line in lines: parts = line.split(' ', 2) if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: steps.setdefault((parts[0], parts[1]), []).append(line) - return [l for key in steps for l in sorted(steps[key])] + return [l for key in steps for l in sorted(settled(steps[key]))] def main(): diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index 4e925500f..71416223b 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -12,7 +12,7 @@ of vanilla's protocol code) and records, step by step, the system chat each rece about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly, in sorted order (the packets of one step may leave in another order within the tick), with the locator bar's -waypoints (one manager per level: a player in another level is untracked). What a death does besides its messages +waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages is left to its own harness. """ import hashlib @@ -83,6 +83,17 @@ DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(' ') + return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def run_side(label, server_command, client_command, build, world): directory = build / label port = server_dir(directory, world) @@ -140,7 +151,7 @@ def run_side(label, server_command, client_command, build, world): steps.setdefault((who, step), []).append(line) order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) - return [l for k in keys for l in sorted(steps[k])], errors + return [l for k in keys for l in sorted(settled(steps[k]))], errors def main(): From 3fdf210ccb736b19b45f4f76b27fc61fb9cdcd5d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:40:52 +0200 Subject: [PATCH 022/115] Advancement index: measured on vanilla's tree An ignored test reads vanilla's advancements and item tags from the prepared resources (HORIZON_RESOURCES) and reports what an inventory change and a recipe unlock test now. On the Mac mini (release): inventory_changed has 1914 criteria, the index is built once in 0.75 ms with the tree (off the tick), and a nine-stack inventory tests 67 of them (found in 16 us); recipe_unlocked has 1739, an iron pickaxe tests 1. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/advancements.rs | 71 +++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 484fbfcf2..6706532b7 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -1095,6 +1095,77 @@ impl Tree { #[cfg(test)] mod tests { use super::*; + + /// The criteria an inventory change and a recipe unlock test, on vanilla's tree: + /// `cargo test -p horizon-client --lib -- --ignored --nocapture index_on_vanilla_tree` + /// with HORIZON_RESOURCES set to the prepared resources. + #[test] + #[ignore = "needs the prepared resources"] + fn index_on_vanilla_tree() { + let Some(root) = std::env::var_os("HORIZON_RESOURCES").map(std::path::PathBuf::from) else { + return; + }; + let data = root.join("data"); + let t = std::time::Instant::now(); + let tree = Tree::load(&data); + let load = t.elapsed(); + let tags = data.join("minecraft/tags/item"); + let tag_items: HashMap> = std::fs::read_dir(&tags) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let v: Value = + serde_json::from_str(&std::fs::read_to_string(e.path()).ok()?).ok()?; + let name = format!("minecraft:{}", e.path().file_stem()?.to_string_lossy()); + let values = v["values"] + .as_array()? + .iter() + .filter_map(|x| x.as_str().map(str::to_owned)); + Some((name, values.collect())) + }) + .collect(); + let t = std::time::Instant::now(); + let index = InventoryIndex::build(&tree, |tag| { + tag_items + .get(tag) + .map(|v| v.iter().map(String::as_str).collect()) + .unwrap_or_default() + }); + let build = t.elapsed(); + let all = tree + .by_trigger + .get("minecraft:inventory_changed") + .map_or(0, Vec::len); + let held = [ + "minecraft:iron_ingot", + "minecraft:oak_log", + "minecraft:cobblestone", + "minecraft:diamond_pickaxe", + "minecraft:bread", + "minecraft:torch", + "minecraft:oak_planks", + "minecraft:stick", + "minecraft:coal", + ]; + let t = std::time::Instant::now(); + let mut candidates = 0; + for _ in 0..1000 { + candidates = index.candidates(held).len(); + } + let per_change = t.elapsed() / 1000; + let recipes = tree + .by_trigger + .get("minecraft:recipe_unlocked") + .map_or(0, Vec::len); + let per_recipe = tree.recipe_criteria("minecraft:iron_pickaxe").len(); + eprintln!( + "tree {load:?}; inventory_changed: {all} criteria, index built in {build:?}, \ + a 9-stack inventory tests {candidates} (looked up in {per_change:?}); \ + recipe_unlocked: {recipes} criteria, iron_pickaxe tests {per_recipe}" + ); + assert!(candidates < all / 10); + } struct Flat; impl World for Flat { fn dimension(&self) -> &str { From 385abe5f0c5cde2651872850fcfd7206461812ca Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:23:55 +0200 Subject: [PATCH 023/115] docs/versioning.md: the 0.2 numbering, the way over for old installs, the go-day steps Ludovic decided (2026-10-21) that the next release is 0.2 for both the game and the launcher, with one clear scheme instead of vYYYY.MM.DD(.N) and launcher-vX.Y.Z. This page is the design the other 0.2 pull requests implement: - tags vX.Y.Z and launcher@X.Y.Z (launcher-v0.2.0 is taken), on a line in .github/release-line.txt; betas stay pre-releases under their final tag; semver pre-release tags reserved for previews; - one order for every reader: each 0.2 tag above every tag from before; - how release.yml, launcher.yml and promote.yml map onto it (HORIZON_VERSION, HORIZON_LAUNCHER_TAG); - what launchers and servers from before 0.2 do with it, and the bridges that move them (launcher-v0.17.0, the last dated game release made latest before v0.2.0); - the orchestrator's steps for the day Ludovic says go, freeze off included. Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/versioning.md | 122 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 123 insertions(+) create mode 100644 docs/versioning.md diff --git a/docs/README.md b/docs/README.md index ffe8e3654..1e268b4d7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -16,6 +16,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Mods](mods.md): Horizon's own mod system (Rust, sandboxed WebAssembly), how to make and install mods, and [what carries over from Java mods](research/java-mod-compat.md). - [Modpacks](modpacks.md): porting whole packs (ATM10 and smaller): import, inventory, carry-over, an agent per mod with a harness against the Java original, coverage, and how "10x" is measured. - [Launcher](../launcher/README.md): installs, updates and starts builds; its CLI and MCP server; releasing it. +- [Versioning](versioning.md): how releases are numbered from 0.2 (`v0.2.x`, `launcher@0.2.x`), how installs from before 0.2 get there, and the steps for the day 0.2 ships. - [Resource packs](resource-packs.md): everything a 26.3 resource pack can change, whether Horizon honours it, and the proof. - [Opt-in data collection](telemetry.md): the consent, exactly what is sent, how it is stored and sent. - [Benchmark report format](benchmark-report.md): the versioned JSON every benchmark writes (game, launcher, `tools/perf_bench.py`), the local log and, with consent, the upload. diff --git a/docs/versioning.md b/docs/versioning.md new file mode 100644 index 000000000..7a5324bc7 --- /dev/null +++ b/docs/versioning.md @@ -0,0 +1,122 @@ +# Versioning + +How Horizon's releases are numbered from 0.2 on, how that maps onto the release workflows, and how every install +made before 0.2 gets there. The workflows themselves are in [release-flow.md](release-flow.md). + +Until 0.2 the game was tagged by date (`v2026.10.19.15`) and the launcher counted on its own (`launcher-v0.16.0`). +From 0.2 both follow [semantic versioning](https://semver.org) and share one release line: **Horizon 0.2.x** is the +game and the launcher of the 0.2 line. + +## Tags + +| | Game | Launcher | +| --- | --- | --- | +| From 0.2 | `v0.2.0`, `v0.2.1`, … | `launcher@0.2.0`, `launcher@0.2.1`, … | +| Before 0.2 | `v2026.10.19`, `v2026.10.19.15`, … | `launcher-v0.1.1` … `launcher-v0.16.0` (and the bridge, `launcher-v0.17.0`) | +| Release title | `Horizon 0.2.3: ` | `Horizon launcher 0.2.1` | +| The program says | `horizon-server 0.2.3`, `v0.2.3` in crash reports and telemetry | `horizon-launcher 0.2.1` | + +- **The line** (`MAJOR.MINOR`) is in `.github/release-line.txt`, one line such as `0.2`. Ludovic decides when it + moves; moving it is a one-line pull request (`0.3`), and the new line's first releases (`v0.3.0`, + `launcher@0.3.0`) go out as soon as it merges. Without the file, the release train keeps the tags from before + 0.2. A `feature` label no longer bumps anything: it only lists the change under **New**. +- **Patch releases** are every release the train makes: the patch after the newest release tagged on the line, game + and launcher counted separately (the game releases more often, so `v0.2.14` can go with `launcher@0.2.3`). +- **Betas** are not separate tags. As before, every game release is published as a GitHub pre-release (a beta) under + its final tag and promoted in place to stable after 6 hours ([Channels](release-flow.md#channels)). `v0.2.4` is + the same build whether it is still a beta or already stable. +- **Pre-release tags** (`v0.3.0-rc.1`, `v0.3.0-beta.2`) are semver's and are reserved for a hand-made preview of a + new line; the train never makes them. Every reader orders them before their release and after the release + before (`v0.2.9` < `v0.3.0-beta.1` < `v0.3.0-rc.1` < `v0.3.0`). +- **`launcher@`, not `launcher-v`**: `launcher-v0.2.0` and `launcher-v0.2.1` were taken long before 0.2, and a + launcher from before 0.2 must not mistake a new 0.2.x for an older release (see below). + +### The order every reader uses + +Every 0.2 tag is newer than every tag from before 0.2. Within each: + +- before 0.2: number by number, missing numbers as zero (`v2026.10.19` = `v2026.10.19.0`); +- from 0.2: semver: major, minor, patch as numbers, then a release after its pre-releases, whose identifiers + compare one by one (numbers before words, numbers as numbers, a shorter list first). + +A tag is a 0.2 tag when it is `v` or `launcher@` followed by exactly three numbers (and an optional `-PRE`) with a +major below 1000; a date's first number is a year, so `v2026.10.21` never is. The rule is written once per +language, with the same tests: `crates/horizon-server/src/update.rs` (`newer`), `launcher/src/backend.rs` +(`release_order`), `tools/release_train.py` (`tag_key`, also used by `tools/release_channels.py`) and +`website/src/versions.js`. + +## The workflows + +- **`release.yml`**: `tools/release_train.py decide --kind game` picks the tag (`next_game_tag`); the build gets the + version without its `v` in `HORIZON_VERSION`, so `horizon_core::release::VERSION` (and `--version`, the user + agents, crash reports and telemetry) say `0.2.3`. No version-bump commits: `Cargo.toml` versions are what builds + from source say. The build checks that `horizon-server --version` and `horizon-prepare --version` say it. +- **`launcher.yml`**: `decide --kind launcher` picks `launcher@0.2.N`; the build gets `HORIZON_LAUNCHER_VERSION` + (`0.2.N`) and `HORIZON_LAUNCHER_TAG` (`launcher@0.2.N`). The tag tells the launcher which line it is on: a release + built with only the version (every launcher before 0.2) is a `launcher-v` one. +- **`promote.yml`**: `tools/release_channels.py` promotes the newest due beta, never one older than the stable + release; with the shared order, `v0.2.0` follows the last dated stable release and no dated beta can follow + `v0.2.0`. +- **Notes**: a line's first release (`X.Y.0`) opens with a paragraph saying so; `v0.2.0`'s and `launcher@0.2.0`'s say + that releases are numbered from now on, and how a server that says it is up to date takes 0.2.0. +- **A line's first release** goes out as soon as the release train runs after the line changes, without waiting for + a pull request, but never while `RELEASES_PAUSED` is set. + +## Existing installs: the way to 0.2 + +Installs made before 0.2 run old code that compares tags number by number, so to them `v0.2.0` is older than +`v2026.10.19.15` and launcher 0.2.0 older than 0.16.0. What each one does, and what moves it: + +| Install | What its old code does with 0.2 | How it gets there | +| --- | --- | --- | +| Launcher 0.16.0 and older, updating itself | Looks only at `launcher-v` tags and takes one above its own version. Never sees `launcher@`. | **The bridge**: one last `launcher-v0.17.0`, built with the new code. Old launchers take it as usual; it knows it is a `launcher-v` release and takes `launcher@0.2.0` next. Two updates, both by themselves. | +| Launcher 0.16.0 and older, installing games | Sorts `v0.2.0` below every dated release and below the versions it has installed, so it never offers it. | Once the launcher has updated itself (above), it offers `v0.2.0` like any update. Until then a player can install `v0.2.0` by hand on the Versions page (it is listed last). | +| Launcher that never updates itself (`HORIZON_LAUNCHER_NO_SELF_UPDATE`, a package) | As above, without the bridge. | Update the package, or install `v0.2.0` by hand. | +| `horizon-server` from before the bridge | Reads GitHub's *latest* release and installs it only if its tag compares higher: `v0.2.0` never does. `--version ` skips the comparison. | **The game bridge**: the last dated release, built with the new code, made stable (*latest*) before `v0.2.0` is published. `v0.2.0` then spends 6 hours as a beta, so *latest* stays the bridge for at least that long; a server updated to it takes `v0.2.0` by itself. A server that missed it says it is up to date and needs, once, `horizon-server update --version v0.2.0` (0.2.0's notes say so). | +| Servers the launcher hosts (Servers page) | Set up from the launcher's installed versions. | Follow the launcher. | +| `install.sh`, `install.ps1` | Install *latest*. | Nothing to do. | +| Crash reports and telemetry of releases before 0.2 | Report the folder name (`v2026.10.19.15`). | Unchanged; 0.2 builds report `v0.2.x` from the built-in version. | + +No change on the feed side alone could do it: the dated releases can't be hidden (old launchers also compare with the +versions they have installed, and *latest* is a single release), and GitHub's release JSON can't be rewritten. So the +bridges are required, and must never be withdrawn or deleted: `launcher-v0.17.0` stays the step every old launcher +takes, for as long as any is around. + +Outside this repository, whatever reads tags must accept `vX.Y.Z` and `launcher@X.Y.Z` too: Kira's release posts, +the fleet's `release-kick` and the orchestrator's heartbeat prompts. + +## The day Ludovic says go + +Run by the orchestrator, in this order. Until step 3, nothing is published. + +1. Merge, in order: this page, the `horizon-server update` order, the launcher order, the release line (train, + workflows), the version sources and the website pull requests. Not the switch pull request yet. Wait for main's + `checks` to pass. +2. Turn the freeze off: + ```sh + gh workflow enable release && gh workflow enable launcher && gh workflow enable promote + gh variable delete RELEASES_PAUSED + U=$(id -u); launchctl enable gui/$U/dev.fleet.release-kick + launchctl bootstrap gui/$U ~/Library/LaunchAgents/dev.fleet.release-kick.plist # on the Mac mini + ``` +3. The bridges go out by themselves within about 25 minutes (the pull requests merged during the freeze count): a + dated game beta (`v2026.10.DD`) and `launcher-v0.17.0`. Check: + ```sh + gh release list --limit 5 + gh run list --workflow launcher --limit 1 # its build log shows horizon-launcher 0.17.0 + ``` +4. Make the game bridge stable now, so servers see it as *latest*: + `gh workflow run promote -f tag=v2026.10.DD` (add `-f force=true` only if it has no smoke test). +5. Mark the switch pull request ready and merge it (`.github/release-line.txt` = `0.2`, and the docs that talk about + 0.2). On the next run, about 10 minutes, the train publishes `v0.2.0` as a beta and `launcher@0.2.0`, both "the + first release of 0.2", built from the same code as the bridges plus that pull request. +6. Check the way over from an old launcher, in a scratch folder: + ```sh + export HORIZON_LAUNCHER_HOME=$(mktemp -d) + # with launcher-v0.16.0's binary: update --check --json -> "launcher": "0.17.0" + # with launcher-v0.17.0's binary: update --check --json -> "launcher": "0.2.0", "horizon": "v0.2.0" (with Beta builds on) + ``` + and `gh release view v0.2.0 --json assets`, `horizon-server --version` in the Linux server archive. +7. `v0.2.0` becomes stable after 6 hours (or `gh workflow run promote -f tag=v0.2.0`). From then on everything is + automatic again: `v0.2.1`, `launcher@0.2.1`, …. +8. Point Kira, `release-kick` and the heartbeat prompts at the new tags (outside this repository). From fde383c6e8460b29814a37a5b667df48e2cea192 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:22:21 +0200 Subject: [PATCH 024/115] Website: read 0.2 tags (v0.2.0, launcher@0.2.0) as newer than the dated ones From 0.2 the game is tagged vX.Y.Z and the launcher launcher@X.Y.Z (docs/versioning.md). The site took only vYYYY.MM.DD as a game release and launcher-v as a launcher, so it would keep offering launcher 0.16 and showing the last dated patch notes. src/versions.js holds the tag test and order (every 0.2 tag above every tag from before, semver within, a pre-release before its release), shared by build.mjs and main.js; the download button picks the newest launcher by tag, the notes the newest stable game releases, and the launcher lookup falls back to launcher@ tags before launcher-v. Nothing shows "0.2" until a 0.2 release exists. `npm test` runs its tests (node --test). Co-Authored-By: Claude Opus 5.5 --- website/build.mjs | 17 +++++----- website/package.json | 3 +- website/src/main.js | 22 +++++++------ website/src/releases.js | 2 +- website/src/versions.js | 59 +++++++++++++++++++++++++++++++++++ website/src/versions.test.mjs | 21 +++++++++++++ 6 files changed, 104 insertions(+), 20 deletions(-) create mode 100644 website/src/versions.js create mode 100644 website/src/versions.test.mjs diff --git a/website/build.mjs b/website/build.mjs index 28c9c99fd..acb121538 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -12,6 +12,7 @@ import { join, dirname } from "node:path"; import { fileURLToPath } from "node:url"; import { markdown, inline, section, escape } from "./src/markdown.js"; import { releasesHtml } from "./src/releases.js"; +import { isGame, isLauncher, launcherVersion, newestFirst } from "./src/versions.js"; import { contributorsFrom, contributorsHtml } from "./src/contributors.js"; const site = dirname(fileURLToPath(import.meta.url)); @@ -46,7 +47,7 @@ try { if (res.ok) releases = (await res.json()).filter((r) => !r.draft); else console.warn(`releases: ${res.status} from GitHub; the page will load them itself`); // A day of betas can push the stable release out of the newest 100: it is GitHub's "latest" (betas never are). - if (res.ok && !releases.some((r) => /^v\d{4}\./.test(r.tag_name) && !r.prerelease)) { + if (res.ok && !releases.some((r) => isGame(r.tag_name) && !r.prerelease)) { const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: githubHeaders, signal: AbortSignal.timeout(15000) }); if (latest.ok) releases.push(await latest.json()); } @@ -111,11 +112,11 @@ const parityHeadline = matching === body.length ? "Every subsystem matches vanil // --- The latest notes ------------------------------------------------- -const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); -const isLauncher = (tag) => tag.startsWith("launcher-v"); -// Stable releases only: betas become stable 6 hours later (docs/release-flow.md, "Channels"). -const game = releases.filter((r) => isGame(r.tag_name) && !r.prerelease).slice(0, 3); -const launcher = releases.find((r) => isLauncher(r.tag_name) && !r.prerelease); +// Stable releases only: betas become stable 6 hours later (docs/release-flow.md, "Channels"). Newest first by +// tag: every 0.2 tag is newer than the dated ones (src/versions.js). +const byTag = (a, b) => newestFirst(a.tag_name, b.tag_name); +const game = releases.filter((r) => isGame(r.tag_name) && !r.prerelease).sort(byTag).slice(0, 3); +const launcher = releases.filter((r) => isLauncher(r.tag_name) && !r.prerelease).sort(byTag)[0]; // --- The page -------------------------------------------------------------------------- @@ -151,7 +152,7 @@ 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)); -for (const file of ["markdown.js", "releases.js", "contributors.js", "main.js"]) { +for (const file of ["markdown.js", "releases.js", "contributors.js", "versions.js", "main.js"]) { const code = rewrite(await readFile(join(site, "src", file), "utf8")); names[file] = `${file.replace(".js", "")}.${fingerprint(code)}.js`; await writeFile(join(dist, "assets", names[file]), code); @@ -195,7 +196,7 @@ const values = { PARITY_HEADLINE: parityHeadline, SUBSYSTEMS: String(body.length), NOTES: notesHtml, - LAUNCHER_META: `${launcher ? `Launcher ${escape(launcher.tag_name.replace("launcher-v", ""))} for` : "For"} Linux x86-64, macOS on Apple Silicon and Windows x64.`, + LAUNCHER_META: `${launcher ? `Launcher ${escape(launcherVersion(launcher.tag_name))} for` : "For"} Linux x86-64, macOS on Apple Silicon and Windows x64.`, DISCORD: escape(links.discord || DEFAULT_LINKS.discord), SPONSOR: escape(links.sponsor || DEFAULT_LINKS.sponsor), CONTRIBUTORS: contributorsHtml(contributors), diff --git a/website/package.json b/website/package.json index e99c7bf5a..0ffacae14 100644 --- a/website/package.json +++ b/website/package.json @@ -8,7 +8,8 @@ "start": "node serve.mjs", "dev": "node build.mjs && node serve.mjs", "assets": "node scripts/assets.mjs", - "shots": "node scripts/shots.mjs" + "shots": "node scripts/shots.mjs", + "test": "node --test src/" }, "devDependencies": { "sharp": "^0.34.4", diff --git a/website/src/main.js b/website/src/main.js index 825de1f25..a461a6e83 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -4,6 +4,7 @@ import { escape } from "./markdown.js"; import { releasesHtml } from "./releases.js"; import { contributorsFrom, contributorsHtml } from "./contributors.js"; +import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; const REPO = "ludovic111/horizon"; const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher-v&expanded=true`; @@ -39,15 +40,12 @@ const slim = (r) => ({ body: r.body || "", assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), }); -const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); -const isLauncher = (r) => r.tag_name.startsWith("launcher-v") && !r.prerelease; -const versionKey = (tag) => tag.replace("launcher-v", "").split(".").map(Number); -const newer = (a, b) => versionKey(b).reduce((d, n, i) => d || n - (versionKey(a)[i] || 0), 0); +const isLauncher = (r) => isLauncherTag(r.tag_name) && !r.prerelease; // The newest 100 releases (GitHub's most per page). Game betas come out several times a day, so the stable game // release and the newest launcher release can both be older than all of them. The stable game release is then // GitHub's "latest" (betas and launcher releases are never marked latest); the launcher release is looked up by its -// tag (the newest launcher-v tag with a published release). +// tag (the newest launcher@ tag with a published release, or launcher-v before 0.2: docs/versioning.md). async function loadReleases() { const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); if (!list.some((r) => isGame(r.tag_name) && !r.prerelease)) { @@ -55,8 +53,12 @@ async function loadReleases() { if (latest && !latest.draft) list.push(slim(latest)); } if (list.some(isLauncher)) return list; - const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/launcher-v`).catch(() => []); - const tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter((t) => /^launcher-v\d+\.\d+\.\d+$/.test(t)).sort(newer); + let tags = []; + for (const prefix of ["launcher@", "launcher-v"]) { + if (tags.length) break; + const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/${prefix}`).catch(() => []); + tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter(isLauncherTag).sort(newestFirst); + } for (const tag of tags.slice(0, 3)) { const release = await get(`https://api.github.com/repos/${REPO}/releases/tags/${tag}`).catch(() => null); if (release && !release.draft) return [...list, slim(release)]; @@ -91,9 +93,9 @@ function platform() { async function setUpDownload() { const os = platform(); const list = await releases; - const launcher = list.find((r) => r.tag_name.startsWith("launcher-v") && !r.prerelease); + const launcher = list.filter(isLauncher).sort((a, b) => newestFirst(a.tag_name, b.tag_name))[0]; if (!launcher) return; - const version = launcher.tag_name.replace("launcher-v", ""); + const version = launcherVersion(launcher.tag_name); const asset = os && launcher.assets.find((a) => a.name.includes(os.key)); const others = `Other platforms`; document.querySelectorAll("[data-download]").forEach((a) => (a.href = asset ? asset.browser_download_url : launcher.html_url || RELEASES_PAGE)); @@ -107,7 +109,7 @@ async function setUpDownload() { // --- Patch notes and the links from main --------------------------------- async function setUpNotes() { - const list = (await releases).filter((r) => isGame(r.tag_name) && !r.prerelease); + const list = (await releases).filter((r) => isGame(r.tag_name) && !r.prerelease).sort((a, b) => newestFirst(a.tag_name, b.tag_name)); if (list.length) document.getElementById("releases").innerHTML = releasesHtml(list.slice(0, 3)); } diff --git a/website/src/releases.js b/website/src/releases.js index 38810f10b..1b7011999 100644 --- a/website/src/releases.js +++ b/website/src/releases.js @@ -4,7 +4,7 @@ import { markdown, escape } from "./markdown.js"; const REPO = "ludovic111/horizon"; -// "Horizon 2026.10.13: 100% of harnessed vanilla parity" reads as the version and its line. +// "Horizon 0.2.3: Cave culling, weather" (before 0.2, "Horizon 2026.10.13: …") reads as the version and its line. function parts(r) { const version = r.tag_name.replace(/^v/, ""); const name = r.name || ""; diff --git a/website/src/versions.js b/website/src/versions.js new file mode 100644 index 000000000..b2483b4ed --- /dev/null +++ b/website/src/versions.js @@ -0,0 +1,59 @@ +// Horizon's release tags (docs/versioning.md). From 0.2 the game is vX.Y.Z and the launcher launcher@X.Y.Z; +// before, vYYYY.MM.DD[.N] and launcher-vX.Y.Z. Every 0.2 tag is newer than every tag from before. Shared by +// build.mjs and main.js, and the same order as the launcher's and tools/release_train.py's. + +const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/; +// Semver's majors stay below this; a date tag's first number is a year. +const FIRST_YEAR = 1000; + +const semver = (version) => { + const m = SEMVER.exec(version); + return m && Number(m[1]) < FIRST_YEAR ? m : null; +}; + +export const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}(\.\d+)?$/.test(tag) || (tag.startsWith("v") && !!semver(tag.slice(1))); + +// The version in a launcher tag (launcher@0.2.0, launcher-v0.16.0), or null. +export function launcherVersion(tag) { + if (tag.startsWith("launcher@") && semver(tag.slice(9))) return tag.slice(9); + const old = /^launcher-v(\d+\.\d+\.\d+)$/.exec(tag); + return old ? old[1] : null; +} + +export const isLauncher = (tag) => launcherVersion(tag) !== null; + +// [line, numbers, pre-release]: tags from before 0.2 by their numbers, then 0.2 tags in semver's order. +function key(tag) { + const version = tag.startsWith("launcher@") ? tag.slice(9) : tag.startsWith("v") ? tag.slice(1) : null; + const m = version !== null && semver(version); + if (!m) return [0, (tag.match(/\d+/g) || []).map(Number), []]; + const pre = m[4] ? m[4].split(".").map((id) => (/^\d+$/.test(id) ? [0, Number(id)] : [1, id])) : null; + return [1, [m[1], m[2], m[3]].map(Number), pre]; +} + +const cmpList = (a, b, cmp) => { + for (let i = 0; i < Math.min(a.length, b.length); i++) { + const d = cmp(a[i], b[i]); + if (d) return d; + } + return a.length - b.length; +}; +const cmpNumbers = (a, b) => { + const strip = (l) => { const c = [...l]; while (c.length && c[c.length - 1] === 0) c.pop(); return c; }; + return cmpList(strip(a), strip(b), (x, y) => x - y); +}; +const cmpId = ([ka, va], [kb, vb]) => ka - kb || (ka ? (va < vb ? -1 : va > vb ? 1 : 0) : va - vb); + +// Negative when tag a is older than tag b. +export function compareTags(a, b) { + const [la, na, pa] = key(a); + const [lb, nb, pb] = key(b); + if (la !== lb) return la - lb; + const d = cmpNumbers(na, nb); + if (d || !la) return d; + // A release follows its pre-releases. + if (!pa || !pb) return (pa ? -1 : 0) - (pb ? -1 : 0); + return cmpList(pa, pb, cmpId); +} + +export const newestFirst = (a, b) => compareTags(b, a); diff --git a/website/src/versions.test.mjs b/website/src/versions.test.mjs new file mode 100644 index 000000000..eed334429 --- /dev/null +++ b/website/src/versions.test.mjs @@ -0,0 +1,21 @@ +// node --test website/src/ (npm test in website/) +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { compareTags, isGame, isLauncher, launcherVersion, newestFirst } from "./versions.js"; + +test("0.2 tags follow every tag from before", () => { + const order = ["v2026.10.19.15", "v2026.10.21", "v0.2.0-beta.1", "v0.2.0", "v0.2.1-beta", "v0.2.1-beta.2", + "v0.2.1-beta.11", "v0.2.1-rc.1", "v0.2.1", "v0.2.9", "v0.2.10", "v0.3.0-1", "v0.3.0-alpha", "v0.3.0", "v1.0.0"]; + assert.deepEqual([...order].reverse().sort(compareTags), order); + assert.deepEqual(["launcher-v0.16.0", "launcher@0.2.0", "launcher-v0.17.0", "launcher@0.2.1"].sort(newestFirst), + ["launcher@0.2.1", "launcher@0.2.0", "launcher-v0.17.0", "launcher-v0.16.0"]); + assert.equal(compareTags("v2026.10.19", "v2026.10.19.0"), 0); +}); + +test("game and launcher tags never mix", () => { + for (const tag of ["v0.2.0", "v0.3.0-rc.1", "v2026.10.21", "v2026.10.19.15"]) assert.ok(isGame(tag), tag); + for (const tag of ["launcher@0.2.0", "launcher-v0.16.0", "v0.2", "vnext", "v2026.10.21-x"]) assert.ok(!isGame(tag), tag); + assert.equal(launcherVersion("launcher@0.2.0"), "0.2.0"); + assert.equal(launcherVersion("launcher-v0.16.0"), "0.16.0"); + assert.ok(!isLauncher("v0.2.0") && !isLauncher("launcher-vnext")); +}); From a56317f943eb67cdb8b3952e7763b727b3c3f6b2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:15:07 +0200 Subject: [PATCH 025/115] docs/versioning.md: servers don't update themselves, a decision on v2026.10.21, bridge soaks first, irreversible list Co-Authored-By: Claude Sonnet 5.5 --- docs/versioning.md | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/docs/versioning.md b/docs/versioning.md index 7a5324bc7..f60073ac8 100644 --- a/docs/versioning.md +++ b/docs/versioning.md @@ -58,7 +58,8 @@ language, with the same tests: `crates/horizon-server/src/update.rs` (`newer`), release; with the shared order, `v0.2.0` follows the last dated stable release and no dated beta can follow `v0.2.0`. - **Notes**: a line's first release (`X.Y.0`) opens with a paragraph saying so; `v0.2.0`'s and `launcher@0.2.0`'s say - that releases are numbered from now on, and how a server that says it is up to date takes 0.2.0. + that releases are numbered from now on, and tell server owners to run `horizon-server update` (or, if their server + says it is up to date, `horizon-server update --version v0.2.0`). - **A line's first release** goes out as soon as the release train runs after the line changes, without waiting for a pull request, but never while `RELEASES_PAUSED` is set. @@ -72,7 +73,7 @@ Installs made before 0.2 run old code that compares tags number by number, so to | Launcher 0.16.0 and older, updating itself | Looks only at `launcher-v` tags and takes one above its own version. Never sees `launcher@`. | **The bridge**: one last `launcher-v0.17.0`, built with the new code. Old launchers take it as usual; it knows it is a `launcher-v` release and takes `launcher@0.2.0` next. Two updates, both by themselves. | | Launcher 0.16.0 and older, installing games | Sorts `v0.2.0` below every dated release and below the versions it has installed, so it never offers it. | Once the launcher has updated itself (above), it offers `v0.2.0` like any update. Until then a player can install `v0.2.0` by hand on the Versions page (it is listed last). | | Launcher that never updates itself (`HORIZON_LAUNCHER_NO_SELF_UPDATE`, a package) | As above, without the bridge. | Update the package, or install `v0.2.0` by hand. | -| `horizon-server` from before the bridge | Reads GitHub's *latest* release and installs it only if its tag compares higher: `v0.2.0` never does. `--version ` skips the comparison. | **The game bridge**: the last dated release, built with the new code, made stable (*latest*) before `v0.2.0` is published. `v0.2.0` then spends 6 hours as a beta, so *latest* stays the bridge for at least that long; a server updated to it takes `v0.2.0` by itself. A server that missed it says it is up to date and needs, once, `horizon-server update --version v0.2.0` (0.2.0's notes say so). | +| `horizon-server` from before the bridge | Reads GitHub's *latest* release and installs it only if its tag compares higher: `v0.2.0` never does. `--version ` skips the comparison. A server never updates itself: its supervisor only logs a notice every 6 hours, and the running process keeps its old code until the service restarts. | **The game bridge**: the last dated release, built with the new code, made stable (*latest*) before `v0.2.0` is published. `v0.2.0` then spends at least 6 hours as a beta, so *latest* stays the bridge for that long (the longer it stays a beta, the more servers are caught). An owner who runs `horizon-server update` in that time gets the bridge, and the command runs the new code at once, so the next `horizon-server update` takes `v0.2.0` once it is stable. The log notice only changes after the service restarts. An owner on old code after that time is told the server is up to date, and runs `horizon-server update --version v0.2.0` once. 0.2.0's notes say so. | | Servers the launcher hosts (Servers page) | Set up from the launcher's installed versions. | Follow the launcher. | | `install.sh`, `install.ps1` | Install *latest*. | Nothing to do. | | Crash reports and telemetry of releases before 0.2 | Report the folder name (`v2026.10.19.15`). | Unchanged; 0.2 builds report `v0.2.x` from the built-in version. | @@ -85,6 +86,15 @@ takes, for as long as any is around. Outside this repository, whatever reads tags must accept `vX.Y.Z` and `launcher@X.Y.Z` too: Kira's release posts, the fleet's `release-kick` and the orchestrator's heartbeat prompts. +## Irreversible + +**None of these can be undone.** + +- Once 0.2 is published, dated tags can never be used again: every reader ranks them below `v0.2.0`. +- After `launcher-v0.17.0`, no other `launcher-v` release may ever go out: old launchers would take it. +- `.github/release-line.txt` must never be removed. +- The bridges (`launcher-v0.17.0` and the last dated game release) must never be withdrawn or deleted. + ## The day Ludovic says go Run by the orchestrator, in this order. Until step 3, nothing is published. @@ -99,17 +109,25 @@ Run by the orchestrator, in this order. Until step 3, nothing is published. U=$(id -u); launchctl enable gui/$U/dev.fleet.release-kick launchctl bootstrap gui/$U ~/Library/LaunchAgents/dev.fleet.release-kick.plist # on the Mac mini ``` + **Decision for Ludovic first:** the pre-freeze beta `v2026.10.21` would be promoted. A dry run says + `Would promote: v2026.10.21` (`python3 tools/release_channels.py promote --dry-run`). The first promote run after + this step (at :13 or :43) makes it stable and *latest*, hours before the bridge is due. Either he accepts that build as + stable, or it is held: leave `gh workflow enable promote` out of this step and run it once the bridge has been out + 6 hours (a run promotes only the newest due beta, which is then the bridge). An open `release-blocker` issue + would hold the bridge too, so it is no way to hold just this one. Do not run this step before he has said which. 3. The bridges go out by themselves within about 25 minutes (the pull requests merged during the freeze count): a dated game beta (`v2026.10.DD`) and `launcher-v0.17.0`. Check: ```sh gh release list --limit 5 gh run list --workflow launcher --limit 1 # its build log shows horizon-launcher 0.17.0 ``` -4. Make the game bridge stable now, so servers see it as *latest*: - `gh workflow run promote -f tag=v2026.10.DD` (add `-f force=true` only if it has no smoke test). -5. Mark the switch pull request ready and merge it (`.github/release-line.txt` = `0.2`, and the docs that talk about - 0.2). On the next run, about 10 minutes, the train publishes `v0.2.0` as a beta and `launcher@0.2.0`, both "the - first release of 0.2", built from the same code as the bridges plus that pull request. +4. Let the game bridge become stable on its normal schedule: about 6 hours after it was published, the promote run + makes it *latest*. Do not force it (`promote` with `force=true`): it carries about 43 player-facing pull requests + from the freeze and needs its beta like any release. Check it is *latest*: + `gh api repos/ludovic111/horizon/releases/latest --jq .tag_name`. +5. Only then mark the switch pull request (#1132) ready and merge it (`.github/release-line.txt` = `0.2`, and the + docs that talk about 0.2). On the next run, about 10 minutes, the train publishes `v0.2.0` as a beta and + `launcher@0.2.0`, both "the first release of 0.2", built from the same code as the bridges plus that pull request. 6. Check the way over from an old launcher, in a scratch folder: ```sh export HORIZON_LAUNCHER_HOME=$(mktemp -d) @@ -117,6 +135,7 @@ Run by the orchestrator, in this order. Until step 3, nothing is published. # with launcher-v0.17.0's binary: update --check --json -> "launcher": "0.2.0", "horizon": "v0.2.0" (with Beta builds on) ``` and `gh release view v0.2.0 --json assets`, `horizon-server --version` in the Linux server archive. -7. `v0.2.0` becomes stable after 6 hours (or `gh workflow run promote -f tag=v0.2.0`). From then on everything is - automatic again: `v0.2.1`, `launcher@0.2.1`, …. +7. `v0.2.0` becomes stable after 6 hours (or `gh workflow run promote -f tag=v0.2.0`). While it is a beta, *latest* + stays the bridge, so keeping it in beta for longer catches more servers (Ludovic's call). From then on everything + is automatic again: `v0.2.1`, `launcher@0.2.1`, …. 8. Point Kira, `release-kick` and the heartbeat prompts at the new tags (outside this repository). From 0ee03671ba4a465d97a4d6e5158762214c5597f2 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:15:09 +0200 Subject: [PATCH 026/115] Website: the fallback releases link matches launcher@ and launcher-v tags Co-Authored-By: Claude Sonnet 5.5 --- website/src/main.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/src/main.js b/website/src/main.js index a461a6e83..e61453730 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -7,7 +7,7 @@ import { contributorsFrom, contributorsHtml } from "./contributors.js"; import { isGame, isLauncher as isLauncherTag, launcherVersion, newestFirst } from "./versions.js"; const REPO = "ludovic111/horizon"; -const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher-v&expanded=true`; +const RELEASES_PAGE = `https://github.com/${REPO}/releases?q=launcher&expanded=true`; const baked = JSON.parse(document.getElementById("baked").textContent); const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)").matches; From 52eb549aec94498418d401e98989d38a821c6d02 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:21:35 +0200 Subject: [PATCH 027/115] Particles: add 26.3's sulfur bubbles over potent sulfur PotentSulfurBlock.animateTick sends two sulfur_bubbles up through a water source above a wet potent sulfur block, and one time in ten plays block.potent_sulfur.noxious_gas. SulfurBubbleParticle rises at -0.04 gravity with 0.85 friction, wiggles sideways, grows from 0.02 to 0.15 and pops when it leaves a water source, stops rising or travels 3 blocks. Its provider passes yAux as the Z speed, which is kept. The particle providers harness gets water worlds for sulfur_bubbles, bubble and bubble_column_up. Co-Authored-By: Claude Opus 5.5 --- .../examples/particle_providers_probe.rs | 32 +++++---- crates/horizon-client/src/animate_tick.rs | 25 +++++++ crates/horizon-client/src/particles.rs | 69 +++++++++++++++++++ crates/horizon-client/src/settings.rs | 5 +- .../VanillaParticleProvidersOracle.java | 15 ++-- tools/test_particle_providers_parity.py | 12 +++- 6 files changed, 138 insertions(+), 20 deletions(-) diff --git a/crates/horizon-client/examples/particle_providers_probe.rs b/crates/horizon-client/examples/particle_providers_probe.rs index 989895c07..8b8bd1e0d 100644 --- a/crates/horizon-client/examples/particle_providers_probe.rs +++ b/crates/horizon-client/examples/particle_providers_probe.rs @@ -112,21 +112,26 @@ fn state(s: &ParticleSnapshot) -> String { } out } -fn world(assets: &Assets, facts: &BlockFacts, floor: bool) -> Result { +fn world(assets: &Assets, facts: &BlockFacts, floor: bool, water: bool) -> Result { let mut world = World::new(facts.air, 0); - let stone = assets - .registry - .default_state("minecraft:stone") - .ok_or("missing stone")?; + let state = |name: &str| assets.registry.default_state(name).ok_or("missing block"); + let (stone, still) = (state("minecraft:stone")?, state("minecraft:water")?); for cz in -3..=2 { for cx in -3..=2 { world .chunks .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); - if floor { - for z in 0..16 { - for x in 0..16 { - world.set(cx * 16 + x, 63, cz * 16 + z, stone)?; + for z in 0..16 { + for x in 0..16 { + let (x, z) = (cx * 16 + x, cz * 16 + z); + if floor { + world.set(x, 63, z, stone)?; + } + // The oracle's water: still sources from y 64 to 67. + if water { + for y in 64..=67 { + world.set(x, y, z, still)?; + } } } } @@ -142,8 +147,10 @@ fn main() -> Result<()> { let facts = BlockFacts::load(root, assets.registry)?; let collision = collisions::load(root, assets.registry)?; let worlds = [ - world(&assets, &facts, false)?, - world(&assets, &facts, true)?, + world(&assets, &facts, false, false)?, + world(&assets, &facts, true, false)?, + world(&assets, &facts, false, true)?, + world(&assets, &facts, true, true)?, ]; let mut engine = ParticleEngine::new(root, &HashMap::new()); for (ty, item) in [ @@ -174,7 +181,8 @@ fn main() -> Result<()> { engine.requested = Some(Vec::new()); engine.sounds.clear(); let level = ParticleLevel { - world: &worlds[usize::from(case["floor"].as_bool() == Some(true))], + world: &worlds[usize::from(case["floor"].as_bool() == Some(true)) + + 2 * usize::from(case["water"].as_bool() == Some(true))], facts: &facts, collision: &collision, player: None, diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index b391c0cbf..ce34df510 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -61,6 +61,8 @@ enum Animate { Fire, /// An active sculk sensor. SculkSensor, + /// Potent sulfur that is not dry. + PotentSulfur, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,9 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { } } "respawn_anchor" if prop("charges").is_some_and(|c| c != "0") => Animate::RespawnAnchor, + "potent_sulfur" if prop("potent_sulfur_state").is_some_and(|s| s != "dry") => { + Animate::PotentSulfur + } "bubble_column" => Animate::BubbleColumn { drag: prop("drag").as_deref() == Some("true"), }, @@ -819,6 +824,26 @@ fn block_animate_tick( } } } + Animate::PotentSulfur => { + // PotentSulfurBlock.animateTick: under a water source, two + // bubbles and, one time in ten, the noxious gas. + let above = ctx.facts.get(ctx.state([pos[0], pos[1] + 1, pos[2]])); + if above.fluid == Fluid::Water && above.fluid_level == 8 && !above.fluid_falling { + for _ in 0..2 { + let r = engine.random(); + let p = [ + fx + f64::from(r.next_float()), + fy + 1.0 + f64::from(r.next_float()), + fz + f64::from(r.next_float()), + ]; + add(engine, T::SulfurBubbles, p, [0.0; 3]); + } + if next_int(engine.random(), 10) == 0 { + let name = "minecraft:block.potent_sulfur.noxious_gas"; + sound(engine, name, [fx, fy, fz], 1.0, 1.0); + } + } + } Animate::Mycelium => { let r = engine.random(); if next_int(r, 10) == 0 { diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 29bf5b030..55a7a5120 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -73,6 +73,7 @@ particle_types! { Splash = "splash", Rain = "rain", Bubble = "bubble", + SulfurBubbles = "sulfur_bubbles", BubblePop = "bubble_pop", BubbleColumnUp = "bubble_column_up", CurrentDown = "current_down", @@ -352,6 +353,14 @@ enum Behaviour { }, WaterDrop, Bubble, + /// `SulfurBubbleParticle`: rises three blocks through still water, + /// growing to 0.15. + SulfurBubble { + y_start: f64, + y_end: f64, + size_start: f32, + y_prev: f64, + }, BubblePop, BubbleColumnUp, CurrentDown { @@ -1099,6 +1108,11 @@ impl ParticleLevel<'_> { }; (s.fluid, height) } + /// The fluid at a block and whether it is a source (`FluidState.isSource`). + fn fluid_source(&self, b: [i32; 3]) -> (Fluid, bool) { + let s = self.facts.get(self.world.block(b[0], b[1], b[2])); + (s.fluid, s.fluid_level == 8 && !s.fluid_falling) + } /// `getCollisionShape(...).max(Y, x, z)` for cached shapes. fn collision_top(&self, b: [i32; 3], fx: f64, fz: f64) -> f64 { let state = self.world.block(b[0], b[1], b[2]); @@ -1933,6 +1947,27 @@ impl ParticleEngine { } q } + T::SulfurBubbles => { + let mut q = Particle::at(r, ty, p); + q.gravity = -0.04; + q.friction = 0.85; + q.set_size(0.02, 0.02); + q.velocity[0] = + v[0] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + // The provider passes `yAux` as `za`, so the Z speed comes from Y. + q.velocity[2] = + v[1] * f64::from(0.2f32) + f64::from((r.next_float() * 2.0 - 1.0) * 0.02); + let size_start = 0.02 + 0.02 * r.next_float(); + q.size = size_start; + q.lifetime = i32::MAX; + q.behaviour = Behaviour::SulfurBubble { + y_start: p[1], + y_end: p[1] + 4.0 - 1.0, + size_start, + y_prev: p[1], + }; + q + } T::BubblePop => { let mut q = Particle::at(r, ty, p); q.lifetime = 4; @@ -3172,6 +3207,40 @@ impl ParticleEngine { p.removed = true; } } + Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev, + } => { + p.base_tick(level); + let (fluid, source) = level.fluid_source(ParticleLevel::block_at(p.position)); + if !p.removed && !(fluid == Fluid::Water && source) { + p.removed = true; + } + if !p.removed && p.position[1] >= y_end { + p.removed = true; + } + if !p.removed && p.position[1] <= y_prev { + p.removed = true; + } + // randomHorizontalWiggling, then a second, horizontal move. + let wiggle = |r: &mut LegacyRandom| { + let f = r.next_float() * 0.003; + f64::from(if r.next_boolean() { f } else { -f }) * 0.5 + }; + p.velocity[0] += wiggle(&mut p.random); + p.velocity[2] += wiggle(&mut p.random); + p.move_by(level, [p.velocity[0], 0.0, p.velocity[2]]); + let progress = ((p.position[1] - y_start) / (y_end - y_start)) as f32; + p.size = size_start + progress * (0.15 - size_start); + p.behaviour = Behaviour::SulfurBubble { + y_start, + y_end, + size_start, + y_prev: p.position[1], + }; + } Behaviour::BubbleColumnUp => { p.base_tick(level); if !p.removed && level.fluid(ParticleLevel::block_at(p.position)).0 != Fluid::Water diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 34b945626..1fadacf57 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -48,7 +48,10 @@ pub fn sound_source(event: &str) -> usize { "zombified_piglin", "wither_skeleton", ]; - if e.starts_with("music_disc.") { + if e == "block.potent_sulfur.noxious_gas" { + // PotentSulfurBlock.animateTick, its only caller, plays it as AMBIENT. + index("ambient") + } else if e.starts_with("music_disc.") { index("record") } else if e.starts_with("music.") { index("music") diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java index f060351b3..85fb5ecd9 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaParticleProvidersOracle.java @@ -48,8 +48,9 @@ import org.jspecify.annotations.Nullable; /** Builds each particle through its real registered ParticleProvider (the real * ParticleResources, sprite sets bound to stand-in sprites named after the * vanilla particles/*.json textures) in a stand-in ClientLevel (air, an - * optional stone floor at y 63, no fluids), then ticks it and records its - * state, the particles and sounds it asks the level for, tick by tick. + * optional stone floor at y 63, optionally still water from y 64 to 67), + * then ticks it and records its state, the particles and sounds it asks the + * level for, tick by tick. * * Each vanilla Particle owns a RandomSource.create() random seeded from the * clock; its seed is recovered after construction (the SEED_UNIQUIFIER value @@ -67,13 +68,18 @@ public final class VanillaParticleProvidersOracle { static T make(Class type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); } static final class Level0 extends ClientLevel { - boolean floor; + boolean floor, water; List events; Level0() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + // Water: still water sources from y 64 to 67 (above the floor, below the open air). + boolean wet(BlockPos p) { return water && p.getY() >= 64 && p.getY() <= 67; } @Override public BlockState getBlockState(BlockPos p) { + if (wet(p)) return Blocks.WATER.defaultBlockState(); return floor && p.getY() == 63 ? Blocks.STONE.defaultBlockState() : Blocks.AIR.defaultBlockState(); } - @Override public FluidState getFluidState(BlockPos p) { return Fluids.EMPTY.defaultFluidState(); } + @Override public FluidState getFluidState(BlockPos p) { + return wet(p) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); + } @Override public @Nullable BlockGetter getChunkForCollisions(int x, int z) { return this; } @Override public boolean hasChunkAt(BlockPos p) { return false; } @Override public void addParticle(ParticleOptions o, double x, double y, double z, double xd, double yd, double zd) { @@ -258,6 +264,7 @@ public final class VanillaParticleProvidersOracle { long seed = c.get("seed").getAsLong(); RandomSource random = null; level.floor = c.get("floor").getAsBoolean(); + level.water = c.has("water") && c.get("water").getAsBoolean(); level.events.clear(); var p = c.getAsJsonArray("pos"); var v = c.getAsJsonArray("vel"); Particle particle = null; diff --git a/tools/test_particle_providers_parity.py b/tools/test_particle_providers_parity.py index afd283359..2fdd510d9 100644 --- a/tools/test_particle_providers_parity.py +++ b/tools/test_particle_providers_parity.py @@ -35,7 +35,7 @@ spore_blossom_air totem_of_undying underwater vault_connection warped_spore whit sweep_attack glow wax_on wax_off electric_spark scrape squid_ink glow_squid_ink item_slime item_snowball item_cobweb sulfur_cube_goo firefly trial_spawner_detection trial_spawner_detection_ominous trial_omen raid_omen ominous_spawning spit fishing dust_plume red_poplar_leaves orange_poplar_leaves yellow_poplar_leaves pause_mob_growth -reset_mob_growth""".split() +reset_mob_growth sulfur_bubbles""".split() def options(kind, rng): @@ -78,6 +78,12 @@ def cases(rng): for vel in velocities: yield dict(type=kind, options=options(kind, rng), pos=pos, vel=vel, floor=floor, seed=rng.randrange(-2**63, 2**63), ticks=80) + # In still water (sources from y 64 to 67): the bubbles rise until they leave it. + for kind in ['sulfur_bubbles', 'bubble', 'bubble_column_up']: + for (pos, floor) in [([0.3125, 64.046875, -0.40625], True), ([-5.75, 66.59375, 3.125], False)]: + for vel in velocities: + yield dict(type=kind, options={}, pos=pos, vel=vel, floor=floor, water=True, + seed=rng.randrange(-2**63, 2**63), ticks=80) def make_cases(build): @@ -215,10 +221,10 @@ def main(): client_jar_sha256=lab.digest(jars['client'], 'sha256'), matched_output_lines=matched, output_sha256=lab.digest(build / 'rust.txt', 'sha256'), libm_tolerated_lines=tolerance, scope=('Real ParticleResources providers for every type Horizon implements, ticked in an air level with an optional ' - 'stone floor: construction (provider, level, SpellParticle and particle-local random draws), per-tick ' + 'stone floor and, for the bubbles, still water: construction (provider, level, SpellParticle and particle-local random draws), per-tick ' 'position, previous position, motion, age, lifetime, removal, onGround, quad size at partial 0 and 0.5, ' 'colour, alpha, roll, sprite, UVs and light at partial 0.5 (unloaded chunk), and the particles and sounds ' - 'requested from the level. Fluids, block light, render layers/facing and the ParticleEngine group limits ' + 'requested from the level. Flowing fluids, block light, render layers/facing and the ParticleEngine group limits ' 'are not exercised.'))) print(f'{units:,} particle cases match the pinned client ({matched:,} output lines, {tolerance} within ' f'the libm tolerance): {report}', flush=True) From da314fa658e9b07b0e1c8d5552a126bbeb9c7bc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 19:28:55 +0000 Subject: [PATCH 028/115] Server tick: cheaper view requeue and chunk ticket levels Two costs that grow with players on the server thread: - Hub::update_view rebuilt a player's chunk queue on every chunk crossing by scanning the queue (a Vec) once for each chunk of the view. It now checks a set. Same queue, same order (differential test against the old scan). 111 -> 16 us per crossing at view 10, 6.5 ms -> 0.13 ms at 32. - ChunkTickets rebuilt a hash map of every ticketed chunk whenever any player changed chunk, and every block entity, mob and ticking chunk hashed into it. Levels are now a grid over the tickets' bounding box, with the map kept for tickets spread too far apart. At 50 players: build 0.23 -> 0.08 ms, lookups about 2x faster (differential test over 200 random ticket layouts). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/lan/hub.rs | 112 ++++++++-- crates/horizon-client/src/ticket_levels.rs | 232 ++++++++++++++++++++- 2 files changed, 322 insertions(+), 22 deletions(-) diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index a961d57a4..76a9551fe 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -240,6 +240,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// The view's queue around a new centre: the queued chunks still tracked, then +/// the tracked ones neither sent nor queued, closest first (a stable sort, so +/// equally close chunks keep their order). +fn requeue( + queue: &mut Vec<(i32, i32)>, + sent: &crate::fast_hash::FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, +) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + // A walking player changes chunk every few ticks with hundreds of chunks + // queued: a set, not a scan of the queue for each of the view's chunks. + let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect(); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); +} + /// What a level's players were last told of its clock and weather. #[derive(Clone, Copy)] struct LevelSync { @@ -1288,20 +1312,7 @@ impl Hub { g.sent_chunks.remove(&(x, z)); g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); } - g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); - for dz in -r - 2..=r + 2 { - for dx in -r - 2..=r + 2 { - let key = (cx + dx, cz + dz); - if tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } - } - } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r); } /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, @@ -2457,3 +2468,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C { w.bool(frozen); raw(ids::TICKING_STATE, w.data) } + +#[cfg(test)] +mod tests { + use super::*; + use crate::fast_hash::FxHashSet; + + /// `requeue` as it was, scanning the queue for each chunk of the view. + fn requeue_scan( + queue: &mut Vec<(i32, i32)>, + sent: &FxHashSet<(i32, i32)>, + (cx, cz): (i32, i32), + r: i32, + ) { + queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key) + { + queue.push(key); + } + } + } + queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// A player walking a loop, sending a few chunks a tick: the queue + /// after every move is the one the scan built. + #[test] + fn requeue_matches_the_scan() { + for r in [2, 5, 10, 12, 32] { + let (mut a, mut b) = (Vec::new(), Vec::new()); + let mut sent = FxHashSet::default(); + for step in 0..60i32 { + let center = ((step % 17) - 8, (step * 3 % 11) - 5); + requeue(&mut a, &sent, center, r); + requeue_scan(&mut b, &sent, center, r); + assert_eq!(a, b, "radius {r}, step {step}"); + for key in a.drain(..a.len().min(7)) { + sent.insert(key); + } + b.drain(..b.len().min(7)); + sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z)); + } + } + } + + /// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture + #[test] + #[ignore] + fn requeue_cost() { + for r in [10, 16, 32] { + for (name, f) in [ + ("scan", requeue_scan as fn(&mut _, &_, _, _)), + ("set", requeue as fn(&mut _, &_, _, _)), + ] { + let sent = FxHashSet::default(); + let mut queue = Vec::new(); + let start = std::time::Instant::now(); + let moves = 200; + for step in 0..moves { + // Nothing sent yet (an explorer waiting on generation). + f(&mut queue, &sent, (step, 0), r); + } + let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves); + println!( + "view {r}: {name} {per:.1} us per chunk crossed, {} queued", + queue.len() + ); + } + } + } +} diff --git a/crates/horizon-client/src/ticket_levels.rs b/crates/horizon-client/src/ticket_levels.rs index 216815de1..de2c427ad 100644 --- a/crates/horizon-client/src/ticket_levels.rs +++ b/crates/horizon-client/src/ticket_levels.rs @@ -45,13 +45,52 @@ pub struct Sources { /// block ticking or lower; `None` ticks everywhere (a game with no server and /// no player: the headless fixtures). #[derive(Clone, Default)] -pub struct Levels(Option>>); +pub struct Levels(Option>); + +/// The levels by chunk: a grid over the tickets' bounding box while it is +/// small (players near each other, the usual case), a map otherwise. Every +/// block entity, mob and ticking chunk asks each tick, so an index beats a +/// hash; and a player crossing into another chunk rebuilds it all. +enum Map { + Grid { + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[(u8, u8)]>, + }, + Sparse(FxHashMap<(i32, i32), (u8, u8)>), +} + +/// The largest grid, in chunks: 1 MiB of levels, a box 724 chunks wide. +const GRID_CELLS: u64 = 1 << 19; + +impl Map { + fn get(&self, x: i32, z: i32) -> (u8, u8) { + match self { + Self::Grid { + x0, + z0, + width, + depth, + cells, + } => { + let (dx, dz) = (x.wrapping_sub(*x0) as u32, z.wrapping_sub(*z0) as u32); + if dx < *width && dz < *depth { + cells[(dz * width + dx) as usize] + } else { + NONE + } + } + Self::Sparse(map) => map.get(&(x, z)).copied().unwrap_or(NONE), + } + } +} impl Levels { /// Chunk coordinates. fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { - let map = self.0.as_ref()?; - Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + Some(self.0.as_ref()?.get(x, z)) } /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: /// where entities tick. @@ -112,19 +151,89 @@ impl ChunkTickets { } } -fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { +/// How far a player's tickets reach, and the simulation ticket's level. +fn reach(s: &Sources) -> (i32, i32, i32) { let view = s.view_distance.clamp(0, 32); let simulation = s.simulation_distance.clamp(0, 32); + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + (view, player_sim, reach) +} + +fn compute(s: &Sources) -> Map { + let (view, player_sim, reach) = reach(s); + let boxes = s + .players + .iter() + .map(|&p| (p, reach)) + .chain(s.forced.iter().map(|&f| (f, 1))); + let Some((x0, z0, x1, z1)) = boxes.fold(None, |b, ((x, z), r)| { + let (lo_x, lo_z, hi_x, hi_z) = ( + i64::from(x) - i64::from(r), + i64::from(z) - i64::from(r), + i64::from(x) + i64::from(r), + i64::from(z) + i64::from(r), + ); + Some(match b { + None => (lo_x, lo_z, hi_x, hi_z), + Some((a, b, c, d)) => (lo_x.min(a), lo_z.min(b), hi_x.max(c), hi_z.max(d)), + }) + }) else { + return Map::Sparse(FxHashMap::default()); + }; + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + if width * depth > GRID_CELLS { + return Map::Sparse(compute_sparse(s)); + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![NONE; (width * depth) as usize].into_boxed_slice(); + let mut lower = |x: i32, z: i32, loading: i32, sim: i32| { + let i = ((z - z0) as u32 * width + (x - x0) as u32) as usize; + let e = &mut cells[i]; + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + px + dx, + pz + dz, + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower(fx + dx, fz + dz, level, level); + } + } + } + Map::Grid { + x0, + z0, + width, + depth, + cells, + } +} + +/// The levels as a map, for tickets spread too far apart for a grid. +fn compute_sparse(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let (view, player_sim, reach) = reach(s); let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); let mut lower = |key, loading: i32, sim: i32| { let e = levels.entry(key).or_insert(NONE); e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); }; - // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the - // player's chunk (`getPlayerTicketLevel`: never below 0). - let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); - let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); for &(px, pz) in &s.players { for dz in -reach..=reach { for dx in -reach..=reach { @@ -229,4 +338,111 @@ mod tests { t.update(None); assert!(t.levels().0.is_none()); } + + /// The grid answers as the map does, everywhere around the tickets. + #[test] + fn grid_matches_the_map() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut next = |n: i32| { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed % (2 * n as u64 + 1)) as i32 - n + }; + for case in 0..200 { + let spread = [3, 20, 80][case % 3]; + let players: Vec<_> = (0..1 + case % 12) + .map(|_| (next(spread), next(spread))) + .collect(); + let forced: Vec<_> = (0..case % 4) + .map(|_| (next(spread), next(spread))) + .collect(); + let s = Sources { + players, + forced, + view_distance: 2 + next(12).abs(), + simulation_distance: 2 + next(12).abs(), + }; + let Map::Grid { .. } = compute(&s) else { + panic!("case {case} fell back to the map"); + }; + let (grid, map) = (compute(&s), Map::Sparse(compute_sparse(&s))); + let r = spread + 50; + for z in -r..=r { + for x in -r..=r { + assert_eq!(grid.get(x, z), map.get(x, z), "case {case} at ({x}, {z})"); + } + } + } + } + + #[test] + fn far_apart_tickets_use_the_map() { + let l = levels( + &[(0, 0), (100_000, -100_000)], + &[(i32::MAX - 2, i32::MIN + 2)], + 10, + 10, + ); + assert!(matches!(**l.0.as_ref().unwrap(), Map::Sparse(_))); + assert!(l.entity_ticking(100_010, -100_010) && !l.block_ticking(50_000, 0)); + assert!(l.entity_ticking(i32::MAX - 2, i32::MIN + 2)); + } + + /// cargo test --release -p horizon-client --lib ticket_levels::tests::levels_cost -- --ignored --nocapture + #[test] + #[ignore] + fn levels_cost() { + for players in [1usize, 10, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let at: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + ((a.cos() * d) as i32, (a.sin() * d) as i32) + }) + .collect(); + let s = Sources { + players: at.clone(), + forced: Vec::new(), + view_distance: 10, + simulation_distance: 10, + }; + let rounds = 200; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute_sparse(std::hint::black_box(&s))); + } + let map_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(compute(std::hint::black_box(&s))); + } + let grid_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64; + // A tick's questions: every chunk within 12 of every player. + let (map, grid) = (Map::Sparse(compute_sparse(&s)), compute(&s)); + let ask = |m: &Map| { + let t = std::time::Instant::now(); + let mut n = 0u32; + for _ in 0..rounds { + for &(px, pz) in &at { + for z in pz - 12..=pz + 12 { + for x in px - 12..=px + 12 { + n += + u32::from(std::hint::black_box(m.get(x, z)).0 <= BLOCK_TICKING); + } + } + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / rounds as f64 + }; + println!( + "{players} players: build {map_build:.3} -> {grid_build:.3} ms, {} lookups {:.3} -> {:.3} ms", + players * 625, + ask(&map), + ask(&grid) + ); + } + } } From 62874d8dc43d131c93b2800a767e68f37b0b4be6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:31:00 +0000 Subject: [PATCH 029/115] Furnaces: look up the cooking recipe in an index, without cloning it Every lit furnace, smoker and blast furnace called Recipes::cook each tick, which scanned all cooking recipes (string compares and hash lookups) and the furnace then cloned the recipe found, its ingredient's item set included. Recipes now keeps, built at the first lookup, the first recipe of each kind for each item, which is what the scan returned; the furnace borrows it. 1000 lookups over 320 recipes: 2.07 -> 0.08 ms Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/containers.rs | 2 +- crates/horizon-client/src/crafting.rs | 96 +++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 6a135799c..854332815 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -528,7 +528,7 @@ impl Furnace { let has_fuel = self.items[1].is_some(); if lit || has_fuel && has_ingredient { if let Some(ingredient) = self.items[0].clone() { - if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient).cloned() { + if let Some(recipe) = recipes.cook(self.kind.recipe_type(), &ingredient) { if self.cooking_timer == 0 { self.cooking_total = total_time(recipe.time, self.speed); } diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e96ca0067..d0b8906ee 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1102,7 +1102,11 @@ pub struct Recipes { facts: HashMap, Facts>, /// The `#minecraft:curse` enchantments. curses: HashSet, + /// The first cooking recipe of each kind taking each item, built at the + /// first lookup (furnaces look theirs up every tick). + cook_index: std::sync::OnceLock, } +type CookIndex = HashMap>; /// `MinMaxBounds.Ints` as (min, max) with the given defaults. fn bounds(v: Option<&Value>, default: (i64, i64), open: (i64, i64)) -> (i64, i64) { match v { @@ -1421,6 +1425,7 @@ impl Recipes { meta, facts, curses, + cook_index: Default::default(), }) } /// Match a `size`x`size` grid (row-major) against the crafting recipes. @@ -1606,6 +1611,22 @@ impl Recipes { out } pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { + let index = self.cook_index.get_or_init(|| { + let mut index = CookIndex::new(); + for (i, c) in self.cooking.iter().enumerate() { + let of_kind = index.entry(c.kind.clone()).or_default(); + for item in &c.ingredient.0 { + of_kind.entry(item.clone()).or_insert(i); + } + } + index + }); + let i = *index.get(kind)?.get(&*input.item)?; + self.cooking.get(i) + } + /// `cook` by scanning every recipe, as it was before the index. + #[cfg(test)] + fn cook_scan(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> { self.cooking .iter() .find(|c| c.kind == kind && c.ingredient.test(input)) @@ -1625,6 +1646,80 @@ mod tests { s.data_mut().banner_patterns = vec![BannerLayer::new("minecraft:cross", "red")]; s } + /// About vanilla's count of cooking recipes: four kinds, ingredients of + /// one to twelve items, overlapping (several recipes take some items). + fn cooking_book() -> Recipes { + let kinds = ["smelting", "blasting", "smoking", "campfire_cooking"]; + let cooking = (0..320usize) + .map(|i| Cooking { + id: format!("r{i}"), + category: "misc".into(), + group: String::new(), + kind: kinds[i % 4].into(), + ingredient: ingredient( + &(0..1 + i % 12) + .map(|k| format!("minecraft:item_{}", (i * 7 + k * 13) % 400)) + .collect::>() + .iter() + .map(String::as_str) + .collect::>(), + ), + result: ItemStack::new("minecraft:stone", 1), + experience: 0.1, + time: 200, + }) + .collect(); + Recipes { + crafting: Vec::new(), + cooking, + meta: HashMap::new(), + facts: HashMap::new(), + curses: HashSet::new(), + cook_index: Default::default(), + } + } + #[test] + fn cook_finds_the_first_recipe_the_scan_finds() { + let recipes = cooking_book(); + for kind in [ + "smelting", + "blasting", + "smoking", + "campfire_cooking", + "other", + ] { + for n in 0..420 { + let stack = ItemStack::new(&format!("minecraft:item_{n}"), 1); + let a = recipes.cook(kind, &stack).map(|c| &c.id); + let b = recipes.cook_scan(kind, &stack).map(|c| &c.id); + assert_eq!(a, b, "{kind} item_{n}"); + } + } + } + /// A furnace's recipe lookup, once per lit furnace per tick. + #[test] + #[ignore] + fn cook_cost() { + let recipes = cooking_book(); + let stacks: Vec = (0..1000) + .map(|n| ItemStack::new(&format!("minecraft:item_{}", n % 400), 1)) + .collect(); + let t = std::time::Instant::now(); + let a = stacks + .iter() + .filter(|s| recipes.cook_scan("smelting", s).cloned().is_some()) + .count(); + let before = t.elapsed().as_secs_f64() * 1e3; + recipes.cook("smelting", &stacks[0]); + let t = std::time::Instant::now(); + let b = stacks + .iter() + .filter(|s| recipes.cook("smelting", s).is_some()) + .count(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("1000 furnace lookups (scan and clone -> index): {before:.3} ms -> {after:.3} ms"); + } fn run(special: &Special, cells: &[ItemStack]) -> Option { let recipes = Recipes { crafting: Vec::new(), @@ -1632,6 +1727,7 @@ mod tests { meta: HashMap::new(), facts: HashMap::new(), curses: HashSet::new(), + cook_index: Default::default(), }; let ctx = Context { recipes: &recipes, From c4d6b341724103a581cc41e461615c568fdd8c41 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 22:46:48 +0200 Subject: [PATCH 030/115] Other players' block cracks are drawn On a server or a world open to LAN, a player saw only their own crack. The server sent each new stage to the others (ClientboundBlockDestruction), but a client of a server ignored the packet, and the host of a LAN world neither drew its guests' cracks nor sent its own to them. Vanilla keeps the cracks per breaker (ClientLevel.destroyBlockProgress: a progress outside 0..9 removes it, 400 ticks without news drops it) and draws, within 32 blocks, the furthest one on each block (LevelExtractor.extractBlockDestroyAnimation). Horizon now does the same: a client of a server takes the packet, a LAN host records its guests' stages and sends its own (each new stage, then -1 when it stops), and every crack is drawn with its own stage. A guest's crack also goes when the block it digs is gone before its STOP_DESTROY_BLOCK (its own tick broke it), as ServerPlayerGameMode.tick clears it on air: the others kept its last stage for 400 ticks. Each crack vertex carries its stage sprite's atlas origin in its light bytes (the crumbling pass is unlit); the shader keeps the shared sprite size. lan_e2e `cracks`: each side watches the block the other mines and sees its crack grow; no crack is left once the blocks break. The screenshots from both sides show the cracks. Fixes #1096 Co-Authored-By: Claude Opus 5.5 --- .../examples/breaking_fixture.rs | 6 +- .../horizon-client/src/block_entity_render.rs | 15 +- crates/horizon-client/src/breaking.rs | 56 +++++-- crates/horizon-client/src/entity.wgsl | 6 +- crates/horizon-client/src/game.rs | 144 +++++++++++------- crates/horizon-client/src/game/control.rs | 7 + crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 88 +++++++++-- crates/horizon-client/src/game/remote.rs | 4 + crates/horizon-client/src/gfx.rs | 6 +- tools/lan_e2e.py | 49 +++++- 11 files changed, 294 insertions(+), 90 deletions(-) diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index 2016fd613..da696b88e 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -14,6 +14,8 @@ use std::{ io::{BufRead, BufReader, BufWriter, Write}, path::Path, }; +/// The stage sprite origin the cracks carry (the oracle compares the geometry and UVs only). +const STAGE: [f32; 2] = [0.25, 0.5]; fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); @@ -47,7 +49,7 @@ fn main() -> Result<(), Box> { .iter() .any(|(_, m)| m.faces.iter().any(|f| f.translucent)); for (_, m) in models { - breaking::geometry(m, origin, translucent, &mut vertices); + breaking::geometry(m, origin, translucent, STAGE, &mut vertices); } } let quads: Vec<_> = vertices @@ -58,7 +60,7 @@ fn main() -> Result<(), Box> { q.iter() .map(|v| { assert_eq!(v.color, 0xffff_ffff); - assert_eq!(v.light, 240 | (240 << 8)); + assert_eq!(v.light, breaking::stage_light(STAGE)); assert_eq!(v.layer, if translucent { 12 } else { 11 }); [v.pos[0], v.pos[1], v.pos[2], v.uv[0], v.uv[1]] }) diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index db6bf7b79..21376d698 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -939,7 +939,14 @@ impl BlockEntityRenderer { !matches!(self.kind(state), Kind::None) } /// ChestRenderer and BannerRenderer submit their animated models for crumbling. - pub fn render_breaking(&self, scene: &Scene, pos: [i32; 3], state: u32, out: &mut Vec) { + pub fn render_breaking( + &self, + scene: &Scene, + pos: [i32; 3], + state: u32, + stage: [f32; 2], + out: &mut Vec, + ) { if !matches!(self.kind(state), Kind::Banner { .. } | Kind::Chest { .. }) { return; } @@ -958,7 +965,7 @@ impl BlockEntityRenderer { false, out, ); - crate::breaking::entity_geometry(&mut out[start..], origin); + crate::breaking::entity_geometry(&mut out[start..], origin, stage); } /// `ChestRenderer.extractRenderState`'s openness for the chest of `state` /// at `pos`: `ChestBlock.combine` (`DoubleBlockCombiner.combineWithNeigbour`) @@ -1942,7 +1949,7 @@ mod tests { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); let mut cracks = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut cracks); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut cracks); assert!(!cracks.is_empty()); assert_eq!( base.iter().map(|v| v.pos).collect::>(), @@ -1956,7 +1963,7 @@ mod tests { scene.lid = &|_| 1.0; } let mut animated = Vec::new(); - renderer.render_breaking(&scene, [0; 3], state, &mut animated); + renderer.render_breaking(&scene, [0; 3], state, [0.0; 2], &mut animated); assert!(cracks.iter().zip(&animated).any(|(a, b)| a.pos != b.pos)); scene.game_time = 0; scene.lid = &|_| 0.0; diff --git a/crates/horizon-client/src/breaking.rs b/crates/horizon-client/src/breaking.rs index c7ee19206..84eedae75 100644 --- a/crates/horizon-client/src/breaking.rs +++ b/crates/horizon-client/src/breaking.rs @@ -23,7 +23,21 @@ pub fn decal_uv([x, y, z]: [f32; 3], direction: Direction) -> [f32; 2] { [-p[0], -p[1]] } -pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: &mut Vec) { +/// The light bytes of a crack vertex: the pass is unlit, so they carry the origin of the +/// vertex's destroy stage sprite (each crack in `LevelRenderer.destroyingBlocks` has its own +/// stage; every stage sprite has the same size, `crumbling_sprite.zw`). +pub fn stage_light([u0, v0]: [f32; 2]) -> u32 { + let q = |x: f32| (x.clamp(0.0, 1.0) * 65535.0).round() as u32; + q(u0) | (q(v0) << 16) +} + +pub fn geometry( + model: &BakedModel, + origin: glam::Vec3, + translucent: bool, + stage: [f32; 2], + out: &mut Vec, +) { // Vanilla visits all six cull groups and then the unculled faces, even beside solid neighbours. for cull in Direction::ALL.map(Some).into_iter().chain([None]) { for face in model.faces.iter().filter(|face| face.quad.cull == cull) { @@ -33,7 +47,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: uv: decal_uv(pos, face.quad.facing), layer: if translucent { 12 } else { 11 }, color: 0xffff_ffff, - light: 240 | (240 << 8), + light: stage_light(stage), normal: [0; 4], }); } @@ -42,7 +56,7 @@ pub fn geometry(model: &BakedModel, origin: glam::Vec3, translucent: bool, out: } /// Project a block entity's transformed quads onto the same destroy-stage pass. -pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { +pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3, stage: [f32; 2]) { for quad in vertices.as_chunks_mut::<4>().0 { let positions = [0, 1, 2].map(|i| glam::Vec3::from(quad[i].pos)); let normal = (positions[1] - positions[0]).cross(positions[2] - positions[0]); @@ -65,7 +79,7 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { vertex.uv = decal_uv((glam::Vec3::from(vertex.pos) - origin).to_array(), facing); vertex.layer = 11; vertex.color = 0xffff_ffff; - vertex.light = 240 | (240 << 8); + vertex.light = stage_light(stage); } } } @@ -73,6 +87,24 @@ pub fn entity_geometry(vertices: &mut [Vertex], origin: glam::Vec3) { #[cfg(test)] mod tests { use super::*; + + #[test] + fn stage_origin_survives_the_light_bytes() { + // entity.wgsl's `wrap`: the low and high 16 bits over 65535. + for origin in [[0.0, 0.0], [0.5, 0.25], [0.123_456, 0.987_654], [1.0, 1.0]] { + let light = stage_light(origin); + let back = [ + (light & 0xffff) as f32 / 65535.0, + (light >> 16) as f32 / 65535.0, + ]; + for k in 0..2 { + assert!( + (back[k] - origin[k]).abs() <= 0.5 / 65535.0, + "{origin:?} -> {back:?}" + ); + } + } + } use crate::models::catalog::BakedFace; use horizon_assets::{bake::ModelQuad, model::Material}; fn slab_top() -> BakedModel { @@ -109,7 +141,13 @@ mod tests { fn slab_overlay_follows_baked_top_not_unit_cube() { let model = slab_top(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::new(2.0, 3.0, 4.0), false, &mut vertices); + geometry( + &model, + glam::Vec3::new(2.0, 3.0, 4.0), + false, + [0.0; 2], + &mut vertices, + ); assert_eq!(vertices.len(), 4); for (v, p) in vertices.iter().zip(model.faces[0].quad.positions) { assert_eq!(v.pos, [p[0] + 2.0, p[1] + 3.0, p[2] + 4.0]); @@ -120,14 +158,14 @@ mod tests { fn entity_overlay_uses_block_local_projected_uvs() { let origin = glam::Vec3::new(12.0, -3.0, 8.0); let mut expected = Vec::new(); - geometry(&slab_top(), origin, false, &mut expected); + geometry(&slab_top(), origin, false, [0.0; 2], &mut expected); let mut actual = expected.clone(); for vertex in &mut actual { vertex.uv = [0.0; 2]; vertex.layer = 0; vertex.color = 0; } - entity_geometry(&mut actual, origin); + entity_geometry(&mut actual, origin, [0.0; 2]); assert_eq!( bytemuck::cast_slice::<_, u8>(&actual), bytemuck::cast_slice::<_, u8>(&expected) @@ -143,7 +181,7 @@ mod tests { #[test] fn translucent_overlay_has_its_own_pass() { let mut vertices = Vec::new(); - geometry(&slab_top(), glam::Vec3::ZERO, true, &mut vertices); + geometry(&slab_top(), glam::Vec3::ZERO, true, [0.0; 2], &mut vertices); assert!(vertices.iter().all(|v| v.layer == 12)); } #[test] @@ -151,7 +189,7 @@ mod tests { let mut model = slab_top(); model.faces.clear(); let mut vertices = Vec::new(); - geometry(&model, glam::Vec3::ZERO, false, &mut vertices); + geometry(&model, glam::Vec3::ZERO, false, [0.0; 2], &mut vertices); assert!(vertices.is_empty()); } } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index c6305c697..9ca871f47 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -71,7 +71,8 @@ fn entity_vertex(position: vec3, uv: vec2, let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u || overlay == 11u || overlay == 12u; out.light_color = select(lm, vec4(1.0), unlit); - // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. + // Overlay 6 (beacon beams): the light bytes carry the sprite's v range; 11 and 12 + // (cracks): the destroy stage sprite's origin. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; // minecraft_mix_light: the vertex colour times the cardinal light only. var c = color; @@ -147,7 +148,8 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { var uv = in.uv; if in.overlay == 6u { uv.y = in.wrap.x + fract(in.uv.y) * in.wrap.y; } if in.overlay == 11u || in.overlay == 12u { - uv = globals.crumbling_sprite.xy + fract(in.uv) * globals.crumbling_sprite.zw; + // Each crack's stage sprite origin comes in its light bytes (breaking::stage_light). + uv = in.wrap + fract(in.uv) * globals.crumbling_sprite.zw; } var color = textureSample(atlas, atlas_sampler, uv) * select(in.back_color, in.color, front); if in.overlay == 9u || in.overlay == 10u { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 460899bff..40dedd8ed 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1136,6 +1136,9 @@ struct Game<'a> { potions: potions::PotionState, scratch_slot: Option, mining: Option, + /// The other players' cracks (`LevelRenderer.destroyingBlocks`): breaker id to the block, + /// the stage (0..=9) and the game time it last changed. + destroying: HashMap, destroy_delay: u32, use_delay: u32, creative: bool, @@ -6433,19 +6436,11 @@ impl Game<'_> { .block_entity_render() .render(&scene, visible, &mut out); } - if let Some(mining) = &self.mining - && mining.progress > 0.0 - && self.gui.atlas.sprites.contains_key(&format!( - "block/destroy_stage_{}", - ((mining.progress * 10.0) as u32).min(9) - )) - { - let state = self - .world - .block(mining.pos[0], mining.pos[1], mining.pos[2]); + for (pos, stage) in self.cracks(camera) { + let state = self.world.block(pos[0], pos[1], pos[2]); self.res .block_entity_render() - .render_breaking(&scene, mining.pos, state.0, &mut out); + .render_breaking(&scene, pos, state.0, stage, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. @@ -6563,50 +6558,90 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.gui.atlas; - // Breaking progress overlay (destroy_stage_0..9). - if let Some(m) = &self.mining - && m.progress > 0.0 - { - let stage = ((m.progress * 10.0) as u32).min(9); - if atlas - .sprites - .contains_key(&format!("block/destroy_stage_{stage}")) + // Breaking progress overlays (destroy_stage_0..9): ours and the other players'. + for (pos, stage) in self.cracks(camera) { + let o = (glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + - camera) + .as_vec3(); + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().get(state).render_shape + == horizon_client::blocks::RenderShape::Model + && let Ok(models) = self + .pack + .render + .model_catalog + .collect(state, BlockPos::new(pos[0], pos[1], pos[2])) { - let o = (glam::DVec3::new( - f64::from(m.pos[0]), - f64::from(m.pos[1]), - f64::from(m.pos[2]), - ) - camera) - .as_vec3(); - let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - if self.res.facts().get(state).render_shape - == horizon_client::blocks::RenderShape::Model - && let Ok(models) = self - .pack - .render - .model_catalog - .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) - { - let offset = self - .pack - .context - .tables - .offset(state, m.pos[0], m.pos[2]) - .unwrap_or([0.0; 3]); - let origin = o + glam::DVec3::from(offset).as_vec3(); - let translucent = models - .iter() - .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); - for (_, model) in models { - horizon_client::breaking::geometry(model, origin, translucent, &mut out); - } + let offset = self + .pack + .context + .tables + .offset(state, pos[0], pos[2]) + .unwrap_or([0.0; 3]); + let origin = o + glam::DVec3::from(offset).as_vec3(); + let translucent = models + .iter() + .any(|(_, model)| model.faces.iter().any(|f| f.translucent)); + for (_, model) in models { + horizon_client::breaking::geometry(model, origin, translucent, stage, &mut out); } } } out } + /// `LevelRenderer.destroyBlockProgress`: a player's crack on a block (0..=9), or none + /// (any other progress). Cracks not updated for 400 ticks are dropped. + pub(crate) fn destroy_block_progress(&mut self, breaker: i32, pos: [i32; 3], progress: i32) { + let now = self.world.game_time; + self.destroying + .retain(|_, c| now.saturating_sub(c.2) <= 400); + if (0..10).contains(&progress) { + self.destroying.insert(breaker, (pos, progress as u8, now)); + } else { + self.destroying.remove(&breaker); + } + } + + /// The cracks to draw and their stage sprite's atlas origin: our own mining and the + /// other players' (`renderBlockDestroyAnimation`: within 32 blocks of the camera, the + /// furthest progress on each block). + fn cracks(&self, camera: glam::DVec3) -> Vec<([i32; 3], [f32; 2])> { + let mut stages: Vec<([i32; 3], u32)> = Vec::new(); + let mut add = |pos: [i32; 3], stage: u32| match stages.iter_mut().find(|c| c.0 == pos) { + Some(c) => c.1 = c.1.max(stage), + None => stages.push((pos, stage)), + }; + if let Some(m) = &self.mining + && m.progress > 0.0 + { + add(m.pos, ((m.progress * 10.0) as u32).min(9)); + } + let now = self.world.game_time; + for (pos, stage, at) in self.destroying.values() { + if now.saturating_sub(*at) <= 400 { + add(*pos, u32::from(*stage)); + } + } + stages + .into_iter() + .filter(|(pos, _)| { + let d = glam::DVec3::new(f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])) + + 0.5 + - camera; + d.length_squared() <= 1024.0 + }) + .filter_map(|(pos, stage)| { + let r = self + .gui + .atlas + .sprites + .get(&format!("block/destroy_stage_{stage}"))?; + Some((pos, [r.u0, r.v0])) + }) + .collect() + } + fn sky_darken(&self) -> i32 { if self.dim == Dim::Nether { return 11; @@ -9599,14 +9634,10 @@ impl Game<'_> { game_time: self.world.game_time as f32, shader_game_time: ((self.world.game_time % 24000) as f32 + alpha as f32) / 24000.0, crumbling_sprite: self - .mining - .as_ref() - .and_then(|m| { - self.gui.atlas.sprites.get(&format!( - "block/destroy_stage_{}", - ((m.progress * 10.0) as u32).min(9) - )) - }) + .gui + .atlas + .sprites + .get("block/destroy_stage_0") .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { self.gui @@ -11148,6 +11179,7 @@ impl<'a> Game<'a> { potions: Default::default(), scratch_slot: None, mining: None, + destroying: HashMap::new(), destroy_delay: 0, use_delay: 0, creative, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 5cdf46110..04b0cd53b 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -769,6 +769,12 @@ impl Game<'_> { "pending_observations": self.lod_observe.len(), "refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()), }); + // The other players' cracks this client draws (LevelRenderer.destroyingBlocks). + let destroying: Vec<_> = self + .destroying + .iter() + .map(|(id, (pos, stage, _))| json!({ "id": id, "pos": pos, "stage": stage })) + .collect(); let mut status = json!({ "screen": self.screen_name(), "debug": { @@ -832,6 +838,7 @@ impl Game<'_> { status["lod"]["target_tiles"] = target.into(); status["lod"]["sampled_target_tiles"] = sampled.into(); status["pending_uploads"] = self.pending_uploads.len().into(); + status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 18325828d..b08eccfc3 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -44,6 +44,8 @@ pub(super) struct LanHost { pub host_entity: i32, /// The host's swings the guests were told of (`Game::swings_started`). pub host_swings: u32, + /// The host's crack the guests were told of: the block and its stage. + pub host_crack: Option<([i32; 3], i32)>, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -519,6 +521,7 @@ impl Game<'_> { settings: LanSettings { port, ..settings }, host_entity, host_swings: self.swings_started, + host_crack: None, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index af127f42a..ab89d2920 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -717,6 +717,7 @@ impl Game<'_> { conn, &C::BlockUpdate(play::BlockUpdate { pos: a.pos, state }), ); + self.destroy_block_progress(host.hub.guests[gi].entity_id, a.pos, -1); host.hub.broadcast_near( [ f64::from(a.pos[0]), @@ -1684,7 +1685,12 @@ impl Game<'_> { play.mining = None; let start = play.dig_start; let state = self.world.block(pos[0], pos[1], pos[2]); - if !dug || self.res.facts().is_air(state) { + if !dug { + return; + } + if self.res.facts().is_air(state) { + // Already broken (the guest's own tick dug it out): only the crack goes. + self.guest_crack_gone(host, conn, pos); return; } let progress = self @@ -1733,18 +1739,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { let _ = g.break_block(pos); }); - if let Some(g) = host.hub.guest(conn) { - host.hub.broadcast_near( - [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], - 64.0, - &C::BlockDestruction(play::BlockDestruction { - id: g.entity_id, - pos, - progress: 255, - }), - Some(conn), - ); - } + self.guest_crack_gone(host, conn, pos); } /// The crack animation other players see. @@ -1756,6 +1751,18 @@ impl Game<'_> { let Some((pos, _)) = play.digging else { return; }; + // ServerPlayerGameMode.tick: a block gone while it is dug (the guest's own tick broke + // it, or something else did) clears the crack. + if play.last_progress >= 0 + && self + .res + .facts() + .is_air(self.world.block(pos[0], pos[1], pos[2])) + { + play.last_progress = -1; + self.guest_crack_gone(host, conn, pos); + return; + } let progress = play .mining .as_ref() @@ -1763,6 +1770,8 @@ impl Game<'_> { let swinging = play.swing.swinging(); if progress != play.last_progress && progress >= 0 { play.last_progress = progress; + // The host player sees it too (on the server thread its window is a guest). + self.destroy_block_progress(host.hub.guests[gi].entity_id, pos, progress); host.hub.broadcast_near( [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], 64.0, @@ -1777,6 +1786,25 @@ impl Game<'_> { let _ = swinging; } + /// `level.destroyBlockProgress(id, pos, -1)` for a guest: its crack on `pos` is gone, for the + /// host and the other guests. + fn guest_crack_gone(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) { + let Some(id) = host.hub.guest(conn).map(|g| g.entity_id) else { + return; + }; + self.destroy_block_progress(id, pos, -1); + host.hub.broadcast_near( + [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])], + 64.0, + &C::BlockDestruction(play::BlockDestruction { + id, + pos, + progress: 255, + }), + Some(conn), + ); + } + /// Dropped items touching a guest go into their inventory. fn guest_pickups(&mut self, host: &mut LanHost, gi: usize) { let (conn, mode, position, id) = { @@ -1981,6 +2009,7 @@ impl Game<'_> { } play.swing.tick(); } + self.lan_host_crack(host); if self.swings_started != host.host_swings { host.host_swings = self.swings_started; if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) { @@ -1992,6 +2021,39 @@ impl Game<'_> { } } +impl Game<'_> { + /// The host player's crack, for the guests (`ServerLevel.destroyBlockProgress` from the + /// host's mining): each new stage, and -1 once it stops or breaks the block. + fn lan_host_crack(&mut self, host: &mut LanHost) { + let now = self + .mining + .as_ref() + .and_then(|m| (m.progress > 0.0).then(|| (m.pos, ((m.progress * 10.0) as i32).min(9)))); + if now == host.host_crack { + return; + } + let packet = |pos: [i32; 3], progress: u8| { + C::BlockDestruction(play::BlockDestruction { + id: host.host_entity, + pos, + progress, + }) + }; + let near = |pos: [i32; 3]| [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; + if let Some((pos, _)) = host.host_crack + && now.is_none_or(|(p, _)| p != pos) + { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, 255), None); + } + if let Some((pos, stage)) = now { + host.hub + .broadcast_near(near(pos), 64.0, &packet(pos, stage as u8), None); + } + host.host_crack = now; + } +} + /// ClientboundSwingAnimationPacket: the hand and the animation (its type and /// base duration; each client applies the swinger's haste and fatigue). fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5bb3e172c..6dbe850b6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1342,6 +1342,10 @@ impl Game<'_> { })); } C::BlockUpdate(p) => self.server_block(p.pos, p.state), + // ClientPacketListener.handleBlockDestruction: another player's crack. + C::BlockDestruction(p) => { + self.destroy_block_progress(p.id, p.pos, i32::from(p.progress)); + } C::SectionBlocksUpdate(p) => { let [sx, sy, sz] = p.section; for change in p.changes { diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 5141b6089..246c09e0c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -108,7 +108,8 @@ struct Globals { end_portal_sprites: [[f32; 4]; 2], /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused. time: [f32; 4], - /// Atlas rect of the current destroy stage (entity.wgsl). + /// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same, + /// and each crack carries its own stage's origin). crumbling_sprite: [f32; 4], /// Framebuffer size, selection stroke width, perspective layering scale. outline_params: [f32; 4], @@ -212,7 +213,8 @@ pub struct Frame<'a> { /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png /// (`rendertype_end_portal`'s Sampler0 and Sampler1). pub end_portal_sprites: [[f32; 4]; 2], - /// Current destroy-stage sprite: projected UVs repeat inside this atlas rect. + /// A destroy-stage sprite: projected UVs repeat inside a rect of this size, from the + /// origin each crack vertex carries (`breaking::stage_light`). pub crumbling_sprite: [f32; 4], pub ticks: u64, /// The darkness effect on the lightmap: the brightness it takes off the diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 606321e99..266e804b3 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -68,6 +68,8 @@ address. The script then checks, from both sides, what a guest's game used to ge the guest steps off (#848). - swings: each side sees the other's arm swing while it mines a block, and the guest sees its own swing when its hoe tills dirt (the server's use) (#848). +- cracks: each side sees the other player's crack on the block they mine grow, and go once it breaks + (#1096). - time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the server's game time after the guest's game stalls for a few seconds (#848). - growth: far from the host, the chunks around the guest tick (#890): water placed there flows @@ -109,7 +111,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1346,6 +1348,49 @@ def check_swings(host, guest, out): return detail +def check_cracks(host, guest, out): + # Another player's crack (#1096): ServerLevel.destroyBlockProgress sends each new stage to the + # others (ClientboundBlockDestructionPacket), drawn by LevelRenderer from destroyingBlocks. + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + guest('command', command=f'setblock {gx} {gy} {gz + 1} minecraft:stone') + host('command', command=f'setblock {hx} {hy} {hz + 1} minecraft:stone') + host.wait(10) + shots = [] + + def cracks(game, pos, name): + stage = max((c['stage'] for c in game('status')['destroying'] if tuple(c['pos']) == pos), default=None) + if stage is not None and stage >= 2 and name not in shots: + shots.append(name) + game.shot(out, name) + return stage + + def watch(miner, watcher, pos, name): + # The watcher looks at the block the other mines. + watcher.raw('look-at', f'{pos[0] + 0.5:.2f}', f'{pos[1] + 0.5:.2f}', f'{pos[2] + 0.5:.2f}') + watcher.wait(5) + return watch_mining(miner, pos, lambda: cracks(watcher, pos, name)) + host_sees = watch(guest, host, (gx, gy, gz + 1), 'cracks-guest-mines') + face_each_other(host, guest) + guest_sees = watch(host, guest, (hx, hy, hz + 1), 'cracks-host-mines') + host.wait(10) + # The breaker's -1 (ServerLevel.destroyBlockProgress once the block is broken) clears each crack. + gone = {name: [(c['pos'], game.raw('block', *c['pos'])['block']) for c in game('status')['destroying']] + for name, game in (('host', host), ('guest', guest))} + detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'after': gone} + stages = lambda s: [x for x in s if x is not None] + assert len(stages(host_sees)) >= 3 and stages(host_sees) == sorted(stages(host_sees)), \ + f'the host does not see the guest\'s crack grow: {detail}' + assert len(stages(guest_sees)) >= 3 and stages(guest_sees) == sorted(stages(guest_sees)), \ + f'the guest does not see the host\'s crack grow: {detail}' + assert not any(gone.values()), f'a crack stays after the block broke: {detail}' + return detail + + def check_eating(host, guest, out): for g in (host, guest): g('command', command='gamemode survival') @@ -1655,7 +1700,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, - 'swings': check_swings, + 'swings': check_swings, 'cracks': check_cracks, 'time': check_time, 'growth': check_growth} From 6216b846691aab89cf46a105a66e871703670401 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 23:54:13 +0000 Subject: [PATCH 031/115] Mob tick: build the mob world once a tick, index the snapshot tick_creature_entities called mob_world_base for every mob. That rebuilt the player view (its allies set scans every mob UUID) and, with any scoreboard team, an owned copy of every mob's team, each a clone of the team's player set: cubic in the mobs on a team. The base is now built once and cloned per mob, with the teams borrowed behind an Arc. 100 mobs, half on a team: 37.7 ms -> 0.06 ms per tick 500 mobs, half on a team: 4297 ms -> 0.31 ms per tick MobWorld::seen looked mobs up by scanning the snapshot; the mob ticks now pass an id index (first slot wins, as the scan did): 2000 lookups over 2000 mobs 1.09 -> 0.01 ms. The nearest-living-entity sensors, the look-at goal, the ravager's roar and MobWorld::nearby read candidates from the tick's position grid instead of every mob, in the same order: 2000 mobs 0.39 -> 0.11 ms per tick. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/game/creatures.rs | 20 +- crates/horizon-client/src/game/scoreboard.rs | 8 +- crates/horizon-client/src/mobs.rs | 253 +++++++++++++++++- .../horizon-client/src/mobs/animal_brain.rs | 2 +- crates/horizon-client/src/mobs/goals.rs | 3 +- .../horizon-client/src/mobs/monster_brain.rs | 2 +- crates/horizon-client/src/mobs/ravager.rs | 2 +- .../horizon-client/src/mobs/villager_brain.rs | 2 +- .../horizon-client/src/mobs/warden_brain.rs | 2 +- crates/horizon-client/src/mobs/world.rs | 18 +- 10 files changed, 285 insertions(+), 27 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 113558e34..d538b5828 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -389,6 +389,7 @@ impl Game<'_> { player, others, others_grid: None, + others_index: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, game_time: self.world.game_time, day_time: self.world.day_time, @@ -401,7 +402,7 @@ impl Game<'_> { end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, - teams: self.mob_teams(), + teams: std::sync::Arc::new(self.mob_teams()), items: Some(self.res.items()), difficulty: self.local_difficulty( self.player @@ -502,9 +503,22 @@ impl Game<'_> { let mut keep = Vec::with_capacity(mobs.len()); let mut grid = horizon_client::mobs::seen_grid::SeenGrid::new(snapshot.iter().map(|s| s.bounds)); + // All but the snapshot is the same for every mob of the tick, so + // build it once: the player view and the teams scan every UUID. + let base = self.mob_world_base(&[]); + // Each mob keeps its snapshot slot all tick; the first slot of an + // id answers, as a scan would. + let mut index = horizon_client::fast_hash::FxHashMap::::default(); + for (i, s) in snapshot.iter().enumerate() { + index.entry(s.id).or_insert(i as u32); + } for i in 0..mobs.len() { - let mut w = self.mob_world_base(&snapshot); - w.others_grid = Some(&grid); + let mut w = MobWorld { + others: &snapshot, + others_grid: Some(&grid), + others_index: Some(&index), + ..base.clone() + }; let m = &mut mobs[i]; w.nearest_player = super::natural_spawning::nearest_player( &players, diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 99dae39a5..e01d6ed03 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -431,20 +431,18 @@ impl Game<'_> { self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). - pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { + pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams<'_> { let board = &self.score.board; if board.teams.is_empty() { return Default::default(); } horizon_client::mobs::Teams { - player: self.player_team().cloned(), + player: self.player_team(), mobs: self .persist .uuids .iter() - .filter_map(|(id, uuid)| { - Some((*id, board.players_team(&uuid_text(*uuid))?.clone())) - }) + .filter_map(|(id, uuid)| Some((*id, board.players_team(&uuid_text(*uuid))?))) .collect(), } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index c8155984c..10d5c19cb 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1404,6 +1404,7 @@ pub struct PlayerView { /// (`EntitySelector.pushableBy` on the client). pub remote: bool, } +#[derive(Clone)] pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, @@ -1418,6 +1419,8 @@ pub struct MobWorld<'a> { pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, + /// Where each id stands in `others`, when the caller keeps one. + pub others_index: Option<&'a crate::fast_hash::FxHashMap>, pub daylight: bool, pub game_time: i64, pub day_time: i64, @@ -1436,22 +1439,23 @@ pub struct MobWorld<'a> { pub world_seed: i64, /// `Level.getSeaLevel` (63 in the overworld, -63 in a flat world). pub sea_level: i32, - /// The scoreboard teams of the player and the mobs (collision rules). - pub teams: Teams, + /// The scoreboard teams of the player and the mobs (collision rules), + /// shared: the mob ticks build them once a tick, not once a mob. + pub teams: std::sync::Arc>, /// Item data (max stack sizes), when the host has it. pub items: Option<&'a crate::items::Items>, } /// `Entity.getTeam` of the player and of the mobs on a team. #[derive(Clone, Debug, Default)] -pub struct Teams { - pub player: Option, - pub mobs: HashMap, +pub struct Teams<'a> { + pub player: Option<&'a crate::scoreboard::Team>, + pub mobs: HashMap, } -impl Teams { - pub fn of(&self, who: Who) -> Option<&crate::scoreboard::Team> { +impl<'a> Teams<'a> { + pub fn of(&self, who: Who) -> Option<&'a crate::scoreboard::Team> { match who { - Who::Player => self.player.as_ref(), - Who::Mob(id) => self.mobs.get(&id), + Who::Player => self.player, + Who::Mob(id) => self.mobs.get(&id).copied(), } } } @@ -2132,3 +2136,234 @@ mod elytra_tests { assert!((wings.angles[1] - 0.08726646).abs() < 0.00001); } } +#[cfg(test)] +mod teams_tests { + use super::*; + use crate::save::uuid_text; + use crate::scoreboard::{Scoreboard, Team}; + + /// A board where every other mob is on the player's team, as with a + /// datapack that colours its mobs' names. + fn board(mobs: u32) -> (Scoreboard, HashMap) { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Steve", "red"); + let uuids: HashMap = (0..mobs) + .map(|id| (id, [id as i32, 7, -(id as i32), 11])) + .collect(); + for (id, uuid) in &uuids { + if id % 2 == 0 { + board.add_to_team(&uuid_text(*uuid), "red"); + } + } + (board, uuids) + } + /// `Game::mob_teams` as built for each mob before: owned clones of the teams. + fn owned(board: &Scoreboard, uuids: &HashMap) -> HashMap { + uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?.clone()))) + .collect() + } + fn borrowed<'a>(board: &'a Scoreboard, uuids: &HashMap) -> Teams<'a> { + Teams { + player: board.players_team("Steve"), + mobs: uuids + .iter() + .filter_map(|(id, u)| Some((*id, board.players_team(&uuid_text(*u))?))) + .collect(), + } + } + + #[test] + fn borrowed_teams_answer_as_the_clones() { + let (board, uuids) = board(40); + let teams = borrowed(&board, &uuids); + let old = owned(&board, &uuids); + for id in 0..41 { + assert_eq!(teams.of(Who::Mob(id)), old.get(&id), "mob {id}"); + } + assert_eq!(teams.of(Who::Player).map(|t| t.name.as_str()), Some("red")); + } + + /// One tick's worth of team building: once per mob (before) against once. + #[test] + #[ignore] + fn teams_cost() { + for mobs in [100u32, 250, 500] { + let (board, uuids) = board(mobs); + let t = std::time::Instant::now(); + for _ in 0..mobs { + std::hint::black_box(owned(&board, &uuids)); + } + let before = t.elapsed(); + let t = std::time::Instant::now(); + let reps = 20; + for _ in 0..reps { + std::hint::black_box(borrowed(&board, &uuids)); + } + let after = t.elapsed() / reps; + println!( + "{mobs} mobs, half on a team: per tick {:.3} ms -> {:.3} ms", + before.as_secs_f64() * 1e3, + after.as_secs_f64() * 1e3 + ); + } + } +} +#[cfg(test)] +mod sensor_scan_tests { + use super::*; + use horizon_core::geometry::Vec3; + use serde_json::json; + + fn kind() -> Arc { + Arc::new(MobType { + id: "minecraft:cow".into(), + species: Species::Cow, + width: 0.9, + height: 1.4, + eye_height: 1.3, + category: "creature".into(), + max_health: 10.0, + speed: 0.2, + flying_speed: 0.4, + attack_damage: 0.0, + attack_knockback: 0.0, + follow_range: 16.0, + step_height: 0.6, + armor: 0.0, + armor_toughness: 0.0, + knockback_resistance: 0.0, + jump_strength: 0.42, + attributes: Arc::default(), + gravity: 0.08, + safe_fall_distance: 3.0, + fall_damage_multiplier: 1.0, + water_efficiency: 0.0, + water_slowdown: 0.8, + air_speed: 0.02, + baby_scale: 0.5, + head_rot_speed: 10.0, + max_head_x_rot: 40.0, + max_head_y_rot: 75.0, + ambient_interval: 120, + flags: Flags { + animal: true, + ..Default::default() + }, + model: Arc::new(Part::parse("root", &json!({}))), + layers: HashMap::new(), + texture: String::new(), + brain: Brain::Passive, + anim: Anim::Rabbit, + sounds: [""; 3], + step_sound: None, + food: Arc::default(), + tempt: Arc::default(), + }) + } + /// `n` mobs in pens of 20 spread over a square of `side` blocks, as on a + /// server's farms; their snapshot and its grid. + fn herd(n: u32, side: f64) -> (Vec, seen_grid::SeenGrid) { + let kind = kind(); + let mut seed = 0x9e37_79b9_7f4a_7c15u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut pen = Vec3::ZERO; + let seen: Vec = (0..n) + .map(|id| { + if id % 20 == 0 { + pen = Vec3::new(next(side), 64.0, next(side)); + } + let at = Vec3::new(pen.x + next(8.0), 64.0, pen.z + next(8.0)); + Mob::new(id, kind.clone(), at, 0.0).seen(None) + }) + .collect(); + let grid = seen_grid::SeenGrid::new(seen.iter().map(|s| s.bounds)); + (seen, grid) + } + /// `NearestLivingEntitySensor` over every mob, as the brains ran it. + fn scan(seen: &[Seen], me: &Seen, area: Aabb) -> Vec { + seen.iter() + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + fn indexed(seen: &[Seen], grid: &seen_grid::SeenGrid, me: &Seen, area: Aabb) -> Vec { + let mut near = Vec::new(); + assert!(grid.candidates(area, &mut near)); + near.iter() + .map(|&i| &seen[i as usize]) + .filter(|o| o.id != me.id && o.alive && o.bounds.intersects(area)) + .map(|o| o.id) + .collect() + } + + #[test] + fn the_grid_finds_what_the_scan_finds() { + let (seen, grid) = herd(600, 160.0); + for me in &seen { + let area = me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0)); + assert_eq!(indexed(&seen, &grid, me, area), scan(&seen, me, area)); + } + } + + /// `MobWorld::seen` once per mob (a target, a breeding partner...), by + /// scan as before and by the tick's id index. + #[test] + #[ignore] + fn lookup_cost() { + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 256.0); + let index: crate::fast_hash::FxHashMap = seen + .iter() + .enumerate() + .map(|(i, s)| (s.id, i as u32)) + .collect(); + let wanted: Vec = (0..n).map(|i| (i * 7919) % n).collect(); + let t = std::time::Instant::now(); + let a: usize = wanted + .iter() + .filter_map(|&id| seen.iter().find(|s| s.id == id)) + .map(|s| s.id as usize) + .sum(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let b: usize = wanted + .iter() + .filter_map(|&id| index.get(&id).map(|&i| &seen[i as usize])) + .map(|s| s.id as usize) + .sum(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} lookups over {n} mobs ({} B each): {before:.3} ms -> {after:.3} ms", + std::mem::size_of::() + ); + } + } + + /// One tick of sensing: a twentieth of the mobs fire their sensor. + #[test] + #[ignore] + fn sensor_cost() { + for (n, side) in [(500u32, 256.0), (1000, 384.0), (2000, 512.0)] { + let (seen, grid) = herd(n, side); + let time = |f: &dyn Fn(&Seen, Aabb) -> usize| { + let t = std::time::Instant::now(); + let mut found = 0; + for me in &seen { + found += f(me, me.bounds.inflate(Vec3::new(16.0, 16.0, 16.0))); + } + (t.elapsed().as_secs_f64() * 1e3 / 20.0, found) + }; + let (before, a) = time(&|me, area| scan(&seen, me, area).len()); + let (after, b) = time(&|me, area| indexed(&seen, &grid, me, area).len()); + assert_eq!(a, b); + println!("{n} mobs: per tick {before:.3} ms -> {after:.3} ms"); + } + } +} diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 9920235a9..331870b4a 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -606,7 +606,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 9419a23ba..38108f8bc 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -970,8 +970,7 @@ impl Goal for LookAtPlayer { let (id, only) = (m.id, self.only); let at = Vec3::new(m.position.x, m.eye_y(), m.position.z); let candidates: Vec<(u32, Vec3)> = - cx.w.others - .iter() + cx.w.others_near(area) .filter(|s| s.id != id && s.alive && s.bounds.intersects(area)) .filter(|s| only.is_none_or(|o| s.species == o)) .map(|s| (s.id, s.position)) diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 238653dad..eeb2c42f2 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -299,7 +299,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/ravager.rs b/crates/horizon-client/src/mobs/ravager.rs index ef71b8f77..49bac4d9f 100644 --- a/crates/horizon-client/src/mobs/ravager.rs +++ b/crates/horizon-client/src/mobs/ravager.rs @@ -177,7 +177,7 @@ fn roar(m: &mut Mob, w: &MobWorld, events: &mut Vec) { velocity: fling(p.position), }); } - for s in w.others.iter() { + for s in w.others_near(area) { if s.id == m.id || !s.alive || s.species == Species::Ravager || !s.bounds.intersects(area) { continue; } diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 5b8500c0d..d401ea6da 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -568,7 +568,7 @@ fn sense_living(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 41353fc83..518347e77 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -492,7 +492,7 @@ fn sense_entities(m: &mut Mob, w: &MobWorld) { let r = m.attrs.follow_range; let area = m.bounds().inflate(Vec3::new(r, r, r)); let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others { + for o in w.others_near(area) { if o.id != m.id && o.alive && o.bounds.intersects(area) { found.push((Who::Mob(o.id), m.distance_sqr(o.position))); } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index cc4110dd7..79bbaa30c 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -226,7 +226,13 @@ impl MobWorld<'_> { .chain(all.into_iter().flatten()) } pub fn seen(&self, id: u32) -> Option<&Seen> { - self.others.iter().find(|s| s.id == id) + match self.others_index { + Some(index) => index + .get(&id) + .and_then(|&i| self.others.get(i as usize)) + .filter(|s| s.id == id), + None => self.others.iter().find(|s| s.id == id), + } } /// Living mobs of the given species within `range` of `from`, nearest first. pub fn nearby<'s>( @@ -235,9 +241,15 @@ impl MobWorld<'_> { range: f64, pred: impl Fn(&Seen) -> bool + 's, ) -> impl Iterator + 's { + // A position within `range` puts the box's bottom face in this area + // (one block wider, as the box test is strict). + let r = range + 1.0; + let area = Aabb::new( + Vec3::new(from.x - r, from.y - r, from.z - r), + Vec3::new(from.x + r, from.y + r, from.z + r), + ); let mut v: Vec<&Seen> = self - .others - .iter() + .others_near(area) .filter(|s| { s.alive && (s.position.x - from.x).abs() <= range From 67ca65bb3b003999c511a4bd729274acc0f6da38 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 23:20:00 +0000 Subject: [PATCH 032/115] Mob tick: drop gone mobs' guest bindings with a set, not a scan per binding On a server every ticked mob is bound to its nearest player, and each tick the bindings of mobs that are gone were dropped by scanning every mob for each binding. Mob is 1.5 KB, so the scan misses the cache on every mob: with 1000 loaded mobs that was 0.44 ms a tick, with 2000 1.86 ms; a set of the live ids makes it 0.02 and 0.04 ms (stand-in structs of Mob's size). Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/game/creatures.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 113558e34..053047b42 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -588,7 +588,11 @@ impl Game<'_> { if let Some(host) = self.lan.as_mut() && !guests.is_empty() { - bindings.retain(|id, _| mobs.iter().any(|m| m.id == *id)); + // A set: a scan of every mob for each binding is quadratic, and a + // server's loaded mobs run into the thousands. + let live: horizon_client::fast_hash::FxHashSet = + mobs.iter().map(|m| m.id).collect(); + bindings.retain(|id, _| live.contains(id)); host.mob_players = bindings; } self.mobs.append(&mut mobs); From 3b21a975bb04548d8f64a5adde7d4b24859332ce Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 01:01:03 +0000 Subject: [PATCH 033/115] Mob goals: read nearby mobs from the tick's grid in four more places FollowParentGoal (every baby, every tick), the pufferfish's puff check, the enderman's block placing and the iron golem's DefendVillage scanned every mob. They now read candidates from the position grid around the area they test (one block wider where they test positions, as a box whose bottom face holds the position meets it), in snapshot order, and test exactly as before. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/mobs/aquatic.rs | 2 +- crates/horizon-client/src/mobs/enderman.rs | 11 +++++------ crates/horizon-client/src/mobs/goals.rs | 13 +++++++++++-- crates/horizon-client/src/mobs/golem.rs | 5 ++++- 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 702e3740d..adb2cbe3a 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -438,7 +438,7 @@ impl Goal for PufferfishPuff { .as_ref() .is_some_and(|p| p.alive && !p.creative && area.intersects(p.bounds)); // TARGETING_CONDITIONS: not other fish (not_scary_for_pufferfish) and alive. - let mob = cx.w.others.iter().any(|s| { + let mob = cx.w.others_near(area).any(|s| { s.id != m.id && s.alive && !matches!( diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 13e6c8a44..fcfba832e 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -391,12 +391,11 @@ impl Goal for LeaveBlock { let target = cx.w.world.block(x, y, z); let below = cx.w.world.block(x, y - 1, z); let bf = cx.w.facts.get(below); - let free = !cx.w.others.iter().any(|s| { - s.bounds.intersects(Aabb::new( - Vec3::new(f64::from(x), f64::from(y), f64::from(z)), - Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), - )) - }); + let block = Aabb::new( + Vec3::new(f64::from(x), f64::from(y), f64::from(z)), + Vec3::new(f64::from(x + 1), f64::from(y + 1), f64::from(z + 1)), + ); + let free = !cx.w.others_near(block).any(|s| s.bounds.intersects(block)); if cx.w.facts.is_air(target) && !cx.w.facts.is_air(below) && &*bf.name != "minecraft:bedrock" diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 38108f8bc..c12f9e7ee 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1,7 +1,11 @@ //! Vanilla's `GoalSelector` (priorities, MOVE/LOOK/JUMP/TARGET control flags, //! interruption) and the shared goals of `net.minecraft.world.entity.ai.goal`. use super::{Mob, MobEvent, MobWorld, Seen, Species, Who, world::TargetInfo}; -use horizon_core::{geometry::Vec3, jmath, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + jmath, + random::RandomSource, +}; use std::sync::Arc; pub const MOVE: u8 = 1; @@ -1901,7 +1905,12 @@ impl Goal for FollowParent { let species = m.species(); let pos = m.position; let mut best: Option<(u32, f64)> = None; - for s in cx.w.others.iter().filter(|s| { + // Every position in range puts the box's bottom face in this area. + let area = Aabb::new( + Vec3::new(pos.x - 9.0, pos.y - 5.0, pos.z - 9.0), + Vec3::new(pos.x + 9.0, pos.y + 5.0, pos.z + 9.0), + ); + for s in cx.w.others_near(area).filter(|s| { s.alive && s.species == species && !s.baby diff --git a/crates/horizon-client/src/mobs/golem.rs b/crates/horizon-client/src/mobs/golem.rs index d4d67660b..c41c34f11 100644 --- a/crates/horizon-client/src/mobs/golem.rs +++ b/crates/horizon-client/src/mobs/golem.rs @@ -68,7 +68,10 @@ impl Goal for DefendVillage { if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 { return false; } - let bad = cx.w.others.iter().any(|s| { + // A position inside `b` puts the box's bottom face there (one block + // wider, as the box test is strict). + let near = b.inflate(Vec3::new(1.0, 1.0, 1.0)); + let bad = cx.w.others_near(near).any(|s| { s.species == Species::Villager && s.alive && s.player_rep <= -100 From a893fa6125eacaa13ea9db58d2c8d0e278bee1f3 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:54:15 +0000 Subject: [PATCH 034/115] Villagers: count the others' POI tickets once per search pois_in_range (AcquirePoi and the job, bed and meeting point searches) asked, for every candidate POI in range, how many tickets it had, and each answer scanned every other mob for villagers holding it: POIs times mobs per search. The others' tickets are now counted into a map at the first candidate and read from it; this villager's own memories are still checked per POI, as before. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- .../horizon-client/src/mobs/villager_brain.rs | 26 +++++++++++++------ 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 5b8500c0d..e981e4dda 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -898,8 +898,9 @@ fn poi_matches(m: &Mob, f: PoiFilter, p: Poi) -> bool { _ => false, } } -/// Tickets taken on a POI: by this villager's memories and by others'. -fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { +/// Tickets taken on a POI: by this villager's memories and by others' +/// (counted once per search by [`others_tickets`]). +fn tickets(m: &Mob, others: &crate::fast_hash::FxHashMap<[i32; 3], usize>, p: [i32; 3]) -> usize { let mut n = 0; if let Some(mm) = mem_ref(m) { for s in [ @@ -913,16 +914,22 @@ fn tickets(m: &Mob, w: &MobWorld, p: [i32; 3]) -> usize { } } } + n + others.get(&p).copied().unwrap_or(0) +} +/// The tickets the other living villagers' POIs take, by POI. +fn others_tickets(m: &Mob, w: &MobWorld) -> crate::fast_hash::FxHashMap<[i32; 3], usize> { + let mut taken = crate::fast_hash::FxHashMap::default(); for o in w.others { if o.id != m.id && o.alive && o.species == Species::Villager { - for q in [o.job, o.bed, o.potential_job, o.meeting] { - if q == Some(p) { - n += 1; - } + for q in [o.job, o.bed, o.potential_job, o.meeting] + .into_iter() + .flatten() + { + *taken.entry(q).or_insert(0) += 1; } } } - n + taken } /// The POIs of chunk `(qx, qz)` from `y0` to `y1` (within the world), in /// scan order: y, then z, then x. Only the indexed POI blocks of the sections @@ -962,6 +969,8 @@ fn pois_in_range( ) -> Vec<(Poi, [i32; 3])> { let c = block_of(m.position); let mut found = Vec::new(); + // Every candidate asks how taken it is: count the others' once. + let mut taken = None; let r2 = i64::from(radius) * i64::from(radius); let (cx, cz) = (c[0] >> 4, c[2] >> 4); let chunks = radius.div_euclid(16) + 1; @@ -974,7 +983,8 @@ fn pois_in_range( || (p[2] - c[2]).abs() > radius || dist_sqr(p, c) > r2 || !poi_matches(m, f, poi) - || tickets(m, w, p) >= poi.max_tickets() + || tickets(m, taken.get_or_insert_with(|| others_tickets(m, w)), p) + >= poi.max_tickets() { return; } From 3917f35e3e781954186d7c2c5be5fa739a333e5e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:07:18 +0000 Subject: [PATCH 035/115] Natural spawning: answer mob box queries from a grid after a few scans GameLevel's isUnobstructed, noCollision (living shulkers) and the spawners' entity count each scanned every mob, computing each 1.5 KB mob's box. A spawn pass holds the game immutably, so after eight queries it builds a grid of the mobs' boxes once and reads candidates from it; the first queries still scan, as the build costs a few scans. 100 box tests, 2000 mobs: 3.48 -> 0.31 ms (grid build included) Also gives the mob_ai_probe example the new others_index field. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- .../horizon-client/examples/mob_ai_probe.rs | 1 + .../src/game/natural_spawning.rs | 88 ++++++++++++++++--- crates/horizon-client/src/mobs.rs | 52 +++++++++++ 3 files changed, 127 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 2a4969221..66d06aa84 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1027,6 +1027,7 @@ fn main() -> horizon_client::Result<()> { nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, + others_index: None, daylight: (world.day_time.rem_euclid(24000)) < 12000, game_time: world.game_time, day_time: world.day_time, diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 0fab09bde..6e7ddf500 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -9,6 +9,7 @@ use horizon_client::{ mobs::{ Mob, MobWorld, Species, data::{self, MobData}, + seen_grid::SeenGrid, spawn_rules::{Dimension, SpawnLevel}, spawn_selection::{ self, Category, Counted, Heightmap, NaturalLevel, SpawnCost, SpawnPlayer, SpawnRequest, @@ -75,8 +76,72 @@ pub(super) struct GameLevel<'g, 'a> { pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. pub(super) pending_ids: std::cell::RefCell>, + /// The game's mobs by box, built once a pass has asked more than + /// [`SCANNED_QUERIES`] box queries (the mobs do not change while it + /// holds the game); the first ones scan, as the build costs a few scans. + pub(super) boxes: std::cell::OnceCell, + pub(super) box_queries: std::cell::Cell, +} +const SCANNED_QUERIES: u32 = 8; +/// A mob not removed: its index in `Game::mobs`, box, alive, and whether +/// it is a living shulker. +type MobBox = (usize, Aabb, bool, bool); +fn mob_box(i: usize, m: &Mob) -> MobBox { + let alive = m.alive(); + ( + i, + m.bounds(), + alive, + alive && m.species() == Species::Shulker, + ) +} +/// The boxes of the game's mobs not removed, and a grid over them. +pub(super) struct MobBoxes { + entries: Vec, + grid: SeenGrid, +} +impl MobBoxes { + fn new(mobs: &[Mob]) -> Self { + let entries: Vec<_> = mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)) + .collect(); + let grid = SeenGrid::new(entries.iter().map(|e| e.1)); + Self { entries, grid } + } + /// The entries whose boxes meet `area` (and possibly a few more). + fn near(&self, area: Aabb) -> impl Iterator + '_ { + let mut near = Vec::new(); + let indexed = self.grid.candidates(area, &mut near); + let all = (!indexed).then(|| self.entries.iter()); + near.into_iter() + .map(|i| self.entries[i as usize]) + .chain(all.into_iter().flatten().copied()) + } } impl GameLevel<'_, '_> { + /// The mobs not removed whose boxes may meet `area` (callers test them). + fn mobs_near(&self, area: Aabb) -> Box + '_> { + let asked = self.box_queries.get() + 1; + self.box_queries.set(asked); + if asked <= SCANNED_QUERIES && self.boxes.get().is_none() { + return Box::new( + self.game + .mobs + .iter() + .enumerate() + .filter(|(_, m)| !m.removed) + .map(|(i, m)| mob_box(i, m)), + ); + } + Box::new( + self.boxes + .get_or_init(|| MobBoxes::new(&self.game.mobs)) + .near(area), + ) + } fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; Some(self.game.res.biomes().get(chunk.biome(x, y, z))) @@ -218,12 +283,9 @@ impl NaturalLevel for GameLevel<'_, '_> { // getEntityCollisions(null, box): living shulkers are solid. let grown = bounds.inflate(Vec3::new(1e-7, 1e-7, 1e-7)); no_collision_empty(&mut scene, bounds) - && !self.game.mobs.iter().any(|m| { - m.species() == Species::Shulker - && m.alive() - && !m.removed - && m.bounds().intersects(grown) - }) + && !self + .mobs_near(grown) + .any(|(_, b, _, shulker)| shulker && b.intersects(grown)) && !self .pending_ids .borrow() @@ -238,10 +300,8 @@ impl NaturalLevel for GameLevel<'_, '_> { !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self - .game - .mobs - .iter() - .any(|m| m.alive() && !m.removed && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .any(|(_, b, alive, _)| alive && b.intersects(bounds)) } fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") @@ -283,10 +343,8 @@ impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self - .game - .mobs - .iter() - .filter(|m| !m.removed && m.kind.id == id && m.bounds().intersects(bounds)) + .mobs_near(bounds) + .filter(|&(i, b, ..)| self.game.mobs[i].kind.id == id && b.intersects(bounds)) .count(); let pending = self .pending_ids @@ -305,6 +363,8 @@ impl<'a> Game<'a> { players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), + boxes: Default::default(), + box_queries: Default::default(), } } /// Creates a mob the spawner accepted, finalized the game's way; the diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 10d5c19cb..ecce6fede 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -2346,6 +2346,58 @@ mod sensor_scan_tests { } } + /// Natural spawning's `isUnobstructed` box test against every mob (real + /// `Mob`s), by scan and by a grid built once for the pass. + #[test] + #[ignore] + fn spawn_box_cost() { + let kind = kind(); + for n in [500u32, 1000, 2000] { + let (seen, _) = herd(n, 384.0); + let mobs: Vec = seen + .iter() + .map(|s| Mob::new(s.id, kind.clone(), s.position, 0.0)) + .collect(); + let mut seed = 7u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let queries: Vec = (0..100) + .map(|_| { + let (x, z) = (next(384.0), next(384.0)); + Aabb::new(Vec3::new(x, 64.0, z), Vec3::new(x + 0.9, 65.4, z + 0.9)) + }) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = queries + .iter() + .map(|&q| { + mobs.iter() + .any(|m| m.alive() && !m.removed && m.bounds().intersects(q)) + }) + .collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let boxes: Vec = mobs.iter().map(|m| m.bounds()).collect(); + let grid = seen_grid::SeenGrid::new(boxes.iter().copied()); + let build = t.elapsed().as_secs_f64() * 1e3; + let mut near = Vec::new(); + let b: Vec = queries + .iter() + .map(|&q| { + assert!(grid.candidates(q, &mut near)); + near.iter().any(|&i| boxes[i as usize].intersects(q)) + }) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!( + "{n} mobs, 100 spawn box tests: {before:.3} ms -> {after:.3} ms (grid build {build:.3} ms included)" + ); + } + } + /// One tick of sensing: a twentieth of the mobs fire their sensor. #[test] #[ignore] From 863a3091612f065e9118fc94c709249fa14ada68 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:34:52 +0000 Subject: [PATCH 036/115] Allays and piglins: hoist per-tick lookups out of the per-mob loop tick_allays scanned every block entity of the level for each allay, every tick, to find a playing jukebox within 10 blocks. The playing jukeboxes are now collected once, at the first allay (no allay starts or stops one). piglin_pickups looked up the piglin_loved tag and hashed every item entity's id once per piglin. Each item's flag is now computed once and kept until an item is added (always pushed at the end under a new id) or removed. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/game/allays.rs | 22 ++++++++++++++++------ crates/horizon-client/src/game/piglins.rs | 14 +++++++++++++- 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index 52dfa7e1c..bed835663 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -9,18 +9,28 @@ impl Game<'_> { pub(super) fn tick_allays(&mut self) { let griefing = self.ui.rules.bool("mob_griefing"); let player = self.player.as_ref().map(|p| p.position); + // The playing jukeboxes, found at the first allay: no allay starts + // or stops one, and the block entities run into the thousands. + let mut jukeboxes: Option> = None; for i in 0..self.mobs.len() { if self.mobs[i].species() != Species::Allay || !self.mobs[i].alive() { continue; } let pos = self.mobs[i].position; // Dancing: a playing jukebox within 10 blocks. - let dancing = self.world.block_entities.iter().any(|(k, e)| { - matches!(e, BlockEntity::Jukebox(j) if j.playing) - && (f64::from(k.0) + 0.5 - pos.x).powi(2) - + (f64::from(k.1) + 0.5 - pos.y).powi(2) - + (f64::from(k.2) + 0.5 - pos.z).powi(2) - <= 100.0 + let jukeboxes = jukeboxes.get_or_insert_with(|| { + self.world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Jukebox(j) if j.playing)) + .map(|(k, _)| *k) + .collect() + }); + let dancing = jukeboxes.iter().any(|k| { + (f64::from(k.0) + 0.5 - pos.x).powi(2) + + (f64::from(k.1) + 0.5 - pos.y).powi(2) + + (f64::from(k.2) + 0.5 - pos.z).powi(2) + <= 100.0 }); self.mobs[i].extra.flag = dancing && !horizon_client::mobs::goals::should_panic(&self.mobs[i]); diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 9df5311aa..6a1e2d6b7 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -34,6 +34,9 @@ impl Game<'_> { if !self.ui.rules.bool("mob_griefing") { return; } + // Whether each item is piglin-loved, kept until an item is added or + // removed (added ones are pushed at the end under a new id). + let mut loved: (Option<(usize, Option)>, Vec) = (None, Vec::new()); for i in 0..self.mobs.len() { let m = &self.mobs[i]; if m.species() != Species::Piglin @@ -46,11 +49,20 @@ impl Game<'_> { continue; } let pos = m.position; + let key = (self.dropped.len(), self.dropped.last().map(|e| e.id)); + if loved.0 != Some(key) { + loved.0 = Some(key); + loved.1 = self + .dropped + .iter() + .map(|e| self.piglin_loved(&e.stack.item)) + .collect(); + } let best = self .dropped .iter() .enumerate() - .filter(|(_, e)| self.piglin_loved(&e.stack.item)) + .filter(|&(j, _)| loved.1[j]) .map(|(j, e)| (j, e.position.distance_squared(pos))) .filter(|(_, d)| *d <= 81.0) .min_by(|a, b| a.1.total_cmp(&b.1)); From cb0bbe7d19e0123e11915244f906791786dd244d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:33:01 +0000 Subject: [PATCH 037/115] Sculk: skip the loaded-chunk diff while no chunk came or went sculk_sync_index collected every loaded chunk key into a set and diffed it against the known chunks every ten ticks, thousands of keys on a busy server. It now remembers the chunk map's membership revision and skips the diff while it is unchanged; a replaced chunk keeps its key and was not rescanned before either. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/game/sculk.rs | 7 ++++++- crates/horizon-client/src/game/sculk_fixture.rs | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 096562608..8667f305f 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -71,6 +71,8 @@ pub(super) struct SculkState { /// The sculk block entities in the order they were added. index: Index, pub known: HashSet<(i32, i32)>, + /// The chunk map's membership revision `known` was taken at. + pub known_revision: Option, // Keyed by mob ids the server gives out: the fast hasher is safe. steps: FxHashMap, damaged: FxHashMap, @@ -336,7 +338,10 @@ impl Game<'_> { /// the block writes recorded since the last tick. pub(super) fn sculk_sync_index(&mut self) { // Chunks that arrived or left (every half second is plenty). - if self.sculk.ticks.is_multiple_of(10) { + // Nothing to do while no chunk came or went. + let revision = self.world.chunks.membership_revision(); + if self.sculk.ticks.is_multiple_of(10) && self.sculk.known_revision != Some(revision) { + self.sculk.known_revision = Some(revision); let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect(); let arrived: Vec<(i32, i32)> = loaded.difference(&self.sculk.known).copied().collect(); for key in arrived { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 890e571b8..df376a7e3 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -433,6 +433,7 @@ impl Game<'_> { }); self.level_events.clear(); self.sculk.known = self.world.chunks.keys().copied().collect(); + self.sculk.known_revision = Some(self.world.chunks.membership_revision()); self.sculk_sync_index(); let mut names: HashMap = HashMap::new(); let mut sources: Vec = Vec::new(); From 49a224df9fb0a3762643c942c5ac9c9a67737e0c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:15:11 +0200 Subject: [PATCH 038/115] Axolotl: free water paths, flat walk targets and the attack sound Three differences from vanilla's Axolotl kept the brain from matching: - The constructor's setPathfindingMalus(WATER, 0) was missing, so every swim target in water failed DefaultRandomPos's malus check and idle axolotls never picked a walk target. - Axolotl.getWalkTargetValue returns 0 everywhere; Horizon used Animal's light-based value, which picked the brightest candidate instead of the first. - Axolotl.playAttackSound (entity.axolotl.attack at pitch 1) never played. The mob AI harness gets #64's two scenarios, in a pool sunk into the ground so no water flows out of it: hunting a cod, and playing dead after repeated hits. Both now match vanilla on every tick (393/393 mob-ticks, was 26). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/mobs/ai.rs | 10 ++++++++-- crates/horizon-client/src/mobs/aquatic.rs | 3 +++ tools/test_mob_ai_parity.py | 7 +++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 34276ddda..ae4aa91a6 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -1240,10 +1240,10 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 { 0.0 }; } - // AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike. + // AbstractNautilus, Axolotl and Creaking.getWalkTargetValue: everywhere alike. if matches!( m.species(), - Species::Nautilus | Species::ZombieNautilus | Species::Creaking + Species::Nautilus | Species::ZombieNautilus | Species::Axolotl | Species::Creaking ) { return 0.0; } @@ -1406,6 +1406,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) { if super::creaking::is_creaking(m) { m.voice("entity.creaking.attack", cx.events); } + // Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0). + if m.species() == Species::Axolotl { + let at = [m.position.x, m.position.y, m.position.z]; + cx.events + .push(MobEvent::Sound("entity.axolotl.attack", at, 1.0, 1.0)); + } let _ = Fluid::None; } /// Mob.ate (sheep regrow wool, babies grow). diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index 702e3740d..6afacb53a 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -46,6 +46,9 @@ pub fn register(m: &mut Mob) { }; m.ai.look.kind = super::control::LookKind::SmoothSwimming(20.0); m.ai.nav.kind = NavKind::Amphibious; + // `Axolotl()`: water costs nothing, so swim targets in water pass + // DefaultRandomPos's malus check. + m.set_malus(super::path::PathType::Water, 0.0); super::animal_brain::init(m, i64::from(m.id)); } S::Tadpole => { diff --git a/tools/test_mob_ai_parity.py b/tools/test_mob_ai_parity.py index 6eda7583e..01ed4680f 100644 --- a/tools/test_mob_ai_parity.py +++ b/tools/test_mob_ai_parity.py @@ -268,6 +268,13 @@ def scenarios(): ('witch', 176), ('vindicator', 177), ('zombie', 178)]: add(f'{species}_deep_water', 160, ['fill -4 -64 -4 4 -61 4 minecraft:water', f'mob minecraft:{species} 0.5 -62 0.5 0 {seed} persistent']) + # Axolotls (#64): idle swimming, hunting a cod, and playing dead after hits, in a pool sunk into + # the ground so no water flows out of it (the probe doesn't tick fluids). + POOL = 'fill -5 -63 -5 5 -61 5 minecraft:water' + add('axolotl_hunting', 45, [POOL, 'player 12.5 -60 0.5', 'mob minecraft:axolotl 0.5 -62 0.5 0 12 persistent', + 'mob minecraft:cod 2.5 -62 0.5 0 13 persistent noai']) + add('axolotl_play_dead', 300, [POOL, 'player 12.5 -60 0.5', 'mob minecraft:axolotl 0.5 -62 0.5 0 28 persistent'] + + [f'hurt {t} 0' for t in range(4, 160, 12)]) return s From 784e8f0648968de2221517da2c7b20f3c41554a0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:17:25 +0200 Subject: [PATCH 039/115] Mod browser (1/3): Modrinth and CurseForge sources, checksum-checked downloads The launcher's core gains `browser`: search Modrinth for what Horizon loads (resource packs, Iris/OptiFine shader packs, modpacks; never Java mod jars), say how well each result runs, pick the newest version that runs, and download a file only from Modrinth's or CurseForge's file servers, with a plain file name, kept only when its size and SHA-512 (SHA-1 on CurseForge) match. CurseForge is a pluggable source that stays off until an API key exists (HORIZON_CURSEFORGE_API_KEY at run time or build time; the launcher workflow passes the repository secret). docs/mod-browser.md. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/launcher.yml | 3 + docs/mod-browser.md | 55 +++++ docs/mods.md | 3 +- launcher/Cargo.lock | 1 + launcher/Cargo.toml | 2 + launcher/src/browser.rs | 296 ++++++++++++++++++++++++ launcher/src/browser/curseforge.rs | 237 +++++++++++++++++++ launcher/src/browser/download.rs | 144 ++++++++++++ launcher/src/browser/modrinth.rs | 214 +++++++++++++++++ launcher/src/browser/tests.rs | 355 +++++++++++++++++++++++++++++ launcher/src/lib.rs | 1 + 11 files changed, 1310 insertions(+), 1 deletion(-) create mode 100644 docs/mod-browser.md create mode 100644 launcher/src/browser.rs create mode 100644 launcher/src/browser/curseforge.rs create mode 100644 launcher/src/browser/download.rs create mode 100644 launcher/src/browser/modrinth.rs create mode 100644 launcher/src/browser/tests.rs diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index a05aa8810..79ea852fb 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -116,6 +116,9 @@ jobs: # Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository # variable, not a secret. Unset, the launcher says sign-in is not configured. HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }} + # The mod browser's CurseForge source (docs/mod-browser.md#curseforge): a repository secret. Unset, the + # launcher searches Modrinth only. + HORIZON_CURSEFORGE_API_KEY: ${{ secrets.HORIZON_CURSEFORGE_API_KEY }} # The release's version and tag, built in (launcher/src/backend.rs VERSION and own_tag: the tag says which # line it is on, docs/versioning.md); a launcher branch's build keeps Cargo.toml's. HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }} diff --git a/docs/mod-browser.md b/docs/mod-browser.md new file mode 100644 index 000000000..888a64bb8 --- /dev/null +++ b/docs/mod-browser.md @@ -0,0 +1,55 @@ +# The launcher's mod browser + +Search Modrinth (and CurseForge, once the launcher has a key) for packs Horizon loads, see how well each one runs, +and install it with its checksum checked. This is item 16 of the roadmap and issue #577. The code is in +`launcher/src/browser.rs` and `launcher/src/browser/`. + +## What it offers + +Only what Horizon actually loads is offered. Java mod jars (Fabric, NeoForge, Forge) don't run in Horizon +([mods.md](mods.md), [research/java-mod-compat.md](research/java-mod-compat.md)), so they are never searched. +Horizon `.hmod` mods aren't on Modrinth or CurseForge yet (Modrinth has no `horizon` loader). + +| Kind | Goes to | How well it runs | +|---|---|---| +| Resource packs | `resourcepacks/` beside `options.txt` | **Works** when made for 26.3 ([resource-packs.md](resource-packs.md) lists what Horizon reads). Older packs are **Partly**: they load with vanilla's compatibility warning | +| Shader packs (Iris, OptiFine) | `shaderpacks/` | **Partly**: translated to WGSL, the full-screen passes draw and the world and shadow passes don't yet ([shader-packs.md](shader-packs.md)). Packs for other loaders (Canvas, core-shader packs) **don't run** and can't be installed | +| Modpacks (`.mrpack`, CurseForge zip) | the Modpacks page's import | **Partly**: Horizon runs the mods it can port, from the player's own downloads ([modpacks.md](modpacks.md)) | + +By default a search shows only what runs: resource packs made for 26.3, shader packs for Iris or OptiFine, and every +modpack. **Show everything** lists the rest of the kind too, each marked with how well it runs; what doesn't run is +never offered for install. + +## Checks on every download + +- The file must come from Modrinth's or CurseForge's file servers (`cdn.modrinth.com`, `edge.forgecdn.net`, + `mediafilez.forgecdn.net`), over HTTPS. +- Its name must be one plain file name (no folders, `..`, hidden names or reserved characters). +- It is written as `..part`, hashed as it arrives, and renamed into place only when its size and checksum match + what the source lists: SHA-512 on Modrinth, SHA-1 on CurseForge (the strongest hash CurseForge publishes). Anything + else removes the part file and installs nothing. +- A file whose source lists no checksum is refused. + +## Sources + +**Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as +Modrinth asks. + +### CurseForge + +CurseForge's API (`api.curseforge.com/v1`) needs an API key from its developer console. Ludovic approved CurseForge +for the browser on 2026-10-21; the key is his (agents never sign up for him). Until a key exists the CurseForge source +is off and the browser searches Modrinth only. + +To turn it on: + +1. Ludovic gets a key at (sign in, API keys). CurseForge's terms for a launcher + that ships the key apply: the key is built into the binary, so anyone with the binary can read it. +2. He stores it in the 1Password **Agents** vault as an item `CurseForge API`, field `credential`. +3. It goes into the repository secret `HORIZON_CURSEFORGE_API_KEY` + (`~/fleet/op read "op://Agents/CurseForge API/credential" | gh secret set HORIZON_CURSEFORGE_API_KEY`). + The launcher workflow passes it to the build, which builds it in (`option_env!`). + +At run time `HORIZON_CURSEFORGE_API_KEY` in the environment overrides the built-in key; empty means none. A file +whose author allows downloads from CurseForge's own site only (no `downloadUrl` in the API) is shown but can't be +installed. diff --git a/docs/mods.md b/docs/mods.md index 346ce0783..9a643198e 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -17,7 +17,8 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | | Authoring tool | `crates/cargo-horizon-mod` | `cargo horizon-mod new / build / run` | | In the game | `crates/horizon-client/src/game/mods.rs`, Options > Mods | client mods | -| Launcher mod browser, signing, server mods, registries | this page, [Roadmap](#roadmap) | planned | +| Launcher mod browser (Modrinth, CurseForge with a key) | [mod-browser.md](mod-browser.md) | resource packs, shader packs, modpacks | +| `.hmod` index, signing, server mods, registries | this page, [Roadmap](#roadmap) | planned | ## Design goals diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index b48a90543..0e866fe19 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2685,6 +2685,7 @@ dependencies = [ "serde", "serde_json", "sha1", + "sha2 0.10.9", "tar", "ureq", "winresource", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index d6225cb96..1097d5675 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -14,6 +14,8 @@ serde = { version = "1", features = ["derive"] } serde_json = "1" # Checks the client jar and the version file found in other launchers' folders (sources.rs). sha1 = "0.10" +# The mod browser checks Modrinth's SHA-512 before a pack reaches the game folder (browser/download.rs). +sha2 = "0.10" pulldown-cmark = { version = "0.12", default-features = false } flate2 = "1" tar = { version = "0.4", default-features = false } diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs new file mode 100644 index 000000000..7010024f4 --- /dev/null +++ b/launcher/src/browser.rs @@ -0,0 +1,296 @@ +//! The mod browser's sources: search Modrinth (and CurseForge, once a key exists) for what +//! Horizon loads, say how well each result runs, and download a file only after its checksum +//! matches (docs/mod-browser.md). +//! +//! Only what Horizon actually loads is offered: resource packs (`resourcepacks/`), Java shader +//! packs (`shaderpacks/`, Iris and OptiFine) and modpacks (imported and ported on the Modpacks +//! page). Java mod jars don't run in Horizon (docs/mods.md), so they are never searched. +pub mod curseforge; +pub mod download; +pub mod modrinth; + +/// The Minecraft version Horizon plays. A version port updates it with the other `"26.3"` sites +/// (docs/version-ports.md). +pub const GAME: &str = "26.3"; + +/// What a project is, as far as Horizon is concerned. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Kind { + ResourcePack, + ShaderPack, + Modpack, +} + +impl Kind { + pub const ALL: [Kind; 3] = [Kind::ResourcePack, Kind::ShaderPack, Kind::Modpack]; + + pub fn label(self) -> &'static str { + match self { + Kind::ResourcePack => "Resource packs", + Kind::ShaderPack => "Shader packs", + Kind::Modpack => "Modpacks", + } + } + + /// The folder beside `options.txt` the file goes in; a modpack is imported instead. + pub fn folder(self) -> Option<&'static str> { + match self { + Kind::ResourcePack => Some("resourcepacks"), + Kind::ShaderPack => Some("shaderpacks"), + Kind::Modpack => None, + } + } +} + +/// Where a project comes from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum SourceId { + Modrinth, + CurseForge, +} + +impl SourceId { + pub fn label(self) -> &'static str { + match self { + SourceId::Modrinth => "Modrinth", + SourceId::CurseForge => "CurseForge", + } + } +} + +/// How well a project runs in Horizon. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Support { + /// Made for the version Horizon plays, and Horizon reads everything it uses. + Works, + /// It loads, with the limit said. + Partial(String), + /// It can't run in Horizon: never offered for install. + No(String), +} + +impl Support { + pub fn installable(&self) -> bool { + !matches!(self, Support::No(_)) + } + + pub fn label(&self) -> &'static str { + match self { + Support::Works => "Works", + Support::Partial(_) => "Partly", + Support::No(_) => "Doesn't run", + } + } + + pub fn reason(&self) -> Option<&str> { + match self { + Support::Works => None, + Support::Partial(r) | Support::No(r) => Some(r), + } + } +} + +/// A search result or a looked-up project. +#[derive(Clone, Debug, PartialEq)] +pub struct Project { + pub source: SourceId, + pub id: String, + pub slug: String, + pub title: String, + pub summary: String, + pub author: String, + pub downloads: u64, + /// The project's page on its source, for the player to read before installing. + pub page: String, + pub icon: Option, + pub license: String, + pub kind: Kind, + /// The Minecraft versions its files list, and the loaders (`iris`, `optifine`, `minecraft`...). + pub game_versions: Vec, + pub loaders: Vec, +} + +impl Project { + pub fn support(&self) -> Support { + support(self.kind, &self.game_versions, &self.loaders) + } +} + +/// One downloadable file of a version, with the checksums its source publishes. +#[derive(Clone, Debug, PartialEq)] +pub struct FileRef { + pub url: String, + pub name: String, + pub size: u64, + pub sha512: Option, + pub sha1: Option, + pub primary: bool, +} + +impl FileRef { + /// The strongest checksum the source gives: what the download is checked against. + pub fn checksum(&self) -> Option<(&'static str, &str)> { + match (&self.sha512, &self.sha1) { + (Some(h), _) => Some(("SHA-512", h)), + (None, Some(h)) => Some(("SHA-1", h)), + (None, None) => None, + } + } +} + +/// A version of a project: its files and what it needs. +#[derive(Clone, Debug, PartialEq)] +pub struct Version { + pub id: String, + pub number: String, + pub published: String, + pub game_versions: Vec, + pub loaders: Vec, + pub files: Vec, + /// Required dependencies, as project ids on the same source. + pub required: Vec, + /// Why this version can't be downloaded from here (CurseForge authors can forbid it). + pub blocked: Option, +} + +impl Version { + /// The file to install: the primary one, else the first. + pub fn file(&self) -> Option<&FileRef> { + self.files + .iter() + .find(|f| f.primary) + .or_else(|| self.files.first()) + } +} + +/// A search. +#[derive(Clone, Debug, PartialEq)] +pub struct Query { + pub text: String, + pub kind: Kind, + /// Off: only what runs (made for [`GAME`], Iris or OptiFine shaders). On: everything of the + /// kind, each result marked with how well it runs. + pub everything: bool, + pub offset: usize, + pub limit: usize, +} + +impl Query { + pub fn new(text: &str, kind: Kind) -> Self { + Self { + text: text.trim().to_owned(), + kind, + everything: false, + offset: 0, + limit: 20, + } + } +} + +/// A place projects come from. +pub trait Source: Send + Sync { + fn id(&self) -> SourceId; + fn search(&self, query: &Query) -> Result, String>; + fn project(&self, id: &str) -> Result; + /// Versions, newest first. + fn versions(&self, project: &Project) -> Result, String>; +} + +/// The sources this launcher can use: Modrinth always, CurseForge when it has an API key. +pub fn sources() -> Vec> { + let mut all: Vec> = vec![Box::new(modrinth::Modrinth)]; + if let Some(cf) = curseforge::CurseForge::from_env() { + all.push(Box::new(cf)); + } + all +} + +/// The loaders a Java shader pack may name that Horizon translates. +const SHADER_LOADERS: [&str; 2] = ["iris", "optifine"]; + +/// How well a project of `kind` made for `game_versions` and `loaders` runs in Horizon. +pub fn support(kind: Kind, game_versions: &[String], loaders: &[String]) -> Support { + match kind { + Kind::ResourcePack => { + if game_versions.iter().any(|v| v == GAME) { + Support::Works + } else if let Some(newest) = newest_release(game_versions) { + Support::Partial(format!( + "Made for {newest}: it loads with vanilla's compatibility warning, and \ + what changed since may look wrong." + )) + } else { + Support::Partial("Lists no Minecraft version.".into()) + } + } + Kind::ShaderPack => { + if loaders.iter().any(|l| SHADER_LOADERS.contains(&l.as_str())) { + Support::Partial( + "Java shader packs are translated: their full-screen passes draw, the world \ + and shadow passes don't yet (BSL and Complementary tested)." + .into(), + ) + } else { + let named = loaders.first().map(String::as_str).unwrap_or("unknown"); + Support::No(format!( + "A shader pack for {named}: Horizon runs Iris and OptiFine packs only." + )) + } + } + Kind::Modpack => Support::Partial( + "Imported on the Modpacks page: Horizon runs the mods it can port, from your own \ + downloads." + .into(), + ), + } +} + +/// The newest plain release (`1.21.4`, `26.2`) in a list of Minecraft versions. +fn newest_release(versions: &[String]) -> Option<&str> { + versions + .iter() + .filter(|v| { + v.split('.') + .all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) + }) + .max_by_key(|v| { + v.split('.') + .map(|p| p.parse::().unwrap_or(0)) + .collect::>() + }) + .map(String::as_str) +} + +/// The version to install: the newest one that runs, or with `everything` the newest at all. +/// `versions` is newest first, as [`Source::versions`] gives them. +pub fn pick(kind: Kind, versions: &[Version], everything: bool) -> Option<&Version> { + let mut usable = versions + .iter() + .filter(|v| v.blocked.is_none() && v.file().is_some()); + let runs = |v: &&Version| match support(kind, &v.game_versions, &v.loaders) { + Support::Works => true, + // A modpack's version is for its own Minecraft; any shader pack Horizon translates. + Support::Partial(_) => kind != Kind::ResourcePack, + Support::No(_) => false, + }; + if let Some(v) = usable.clone().find(runs) { + return Some(v); + } + usable.find(|v| everything && support(kind, &v.game_versions, &v.loaders).installable()) +} + +/// A file name from a source, kept only when it is one plain name: no folders, no `..`, no +/// hidden file, nothing a file system would read as something else. +pub fn safe_name(name: &str) -> Option<&str> { + let ok = !name.is_empty() + && name.len() <= 200 + && !name.starts_with('.') + && !name.ends_with(['.', ' ']) + && name.chars().all(|c| { + !c.is_control() && !matches!(c, '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|') + }); + ok.then_some(name) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/browser/curseforge.rs b/launcher/src/browser/curseforge.rs new file mode 100644 index 000000000..347cf0d40 --- /dev/null +++ b/launcher/src/browser/curseforge.rs @@ -0,0 +1,237 @@ +//! CurseForge's API (api.curseforge.com/v1). It needs a key from CurseForge's developer console, +//! so this source stays off until one is given (docs/mod-browser.md#curseforge): +//! `HORIZON_CURSEFORGE_API_KEY` in the environment, else the same variable when the launcher was +//! built (the release workflow passes the repository secret). Files carry SHA-1 and MD5; the +//! download is checked against the SHA-1. +use super::{modrinth::encode, FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; +use serde_json::Value; + +const API: &str = "https://api.curseforge.com/v1"; +/// Minecraft's game id on CurseForge. +const MINECRAFT: u64 = 432; +/// `HashAlgo` in CurseForge's schema. +const SHA1: u64 = 1; +/// `FileRelationType::RequiredDependency`. +const REQUIRED: u64 = 3; + +pub struct CurseForge { + key: String, +} + +/// CurseForge's class id for a kind. +fn class(kind: Kind) -> u64 { + match kind { + Kind::ResourcePack => 12, + Kind::ShaderPack => 6552, + Kind::Modpack => 4471, + } +} + +fn kind_of(class_id: u64) -> Option { + Kind::ALL.into_iter().find(|k| class(*k) == class_id) +} + +/// The key: the environment's, else the one built in. Empty counts as none. +pub(super) fn key(runtime: Option, built: Option<&str>) -> Option { + runtime + .or_else(|| built.map(str::to_owned)) + .map(|k| k.trim().to_owned()) + .filter(|k| !k.is_empty()) +} + +impl CurseForge { + /// The source, when a key exists; else None and CurseForge isn't offered. + pub fn from_env() -> Option { + key( + std::env::var("HORIZON_CURSEFORGE_API_KEY").ok(), + option_env!("HORIZON_CURSEFORGE_API_KEY"), + ) + .map(|key| Self { key }) + } + + fn get(&self, url: &str) -> Result { + let response = super::download::agent() + .get(url) + .set("x-api-key", &self.key) + .set("Accept", "application/json") + .call() + .map_err(|e| match e { + ureq::Error::Status(403, _) => "CurseForge refused the launcher's API key.".into(), + ureq::Error::Status(code, _) => format!("CurseForge answered {code}."), + ureq::Error::Transport(t) => format!("No connection to CurseForge: {t}"), + })?; + response + .into_json() + .map_err(|e| format!("CurseForge's answer wasn't readable: {e}")) + } +} + +pub(super) fn search_url(query: &Query) -> String { + let mut url = format!( + "{API}/mods/search?gameId={MINECRAFT}&classId={}&sortField=2&sortOrder=desc&index={}&pageSize={}", + class(query.kind), + query.offset, + query.limit.clamp(1, 50), + ); + if !query.everything && query.kind == Kind::ResourcePack { + url.push_str(&format!("&gameVersion={GAME}")); + } + if !query.text.is_empty() { + url.push_str("&searchFilter="); + url.push_str(&encode(&query.text)); + } + url +} + +/// CurseForge mixes Minecraft versions and loader names (`Iris`, `OptiFine`, `NeoForge`) in one +/// list: digits first is a version, the rest are loaders, in lowercase as Modrinth names them. +fn split_versions(list: &Value) -> (Vec, Vec) { + let mut versions = Vec::new(); + let mut loaders = Vec::new(); + for v in list + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if v.starts_with(|c: char| c.is_ascii_digit()) { + versions.push(v.to_owned()); + } else { + loaders.push(v.to_ascii_lowercase()); + } + } + versions.sort(); + versions.dedup(); + loaders.sort(); + loaders.dedup(); + (versions, loaders) +} + +pub(super) fn parse_mod(m: &Value) -> Option { + let kind = kind_of(m["classId"].as_u64()?)?; + let latest = Value::Array( + m["latestFilesIndexes"] + .as_array() + .into_iter() + .flatten() + .filter_map(|i| i["gameVersion"].as_str()) + .map(|v| Value::String(v.to_owned())) + .collect(), + ); + let (game_versions, mut loaders) = split_versions(&latest); + // A shader pack's files name its loader; the index often doesn't. + if kind == Kind::ShaderPack && loaders.is_empty() { + let (_, own) = split_versions(&Value::Array( + m["latestFiles"] + .as_array() + .into_iter() + .flatten() + .flat_map(|f| f["gameVersions"].as_array().cloned().unwrap_or_default()) + .collect(), + )); + loaders = own; + } + Some(Project { + source: SourceId::CurseForge, + id: m["id"].as_u64()?.to_string(), + slug: m["slug"].as_str().unwrap_or_default().to_owned(), + title: m["name"].as_str().unwrap_or_default().to_owned(), + summary: m["summary"].as_str().unwrap_or_default().to_owned(), + author: m["authors"][0]["name"] + .as_str() + .unwrap_or_default() + .to_owned(), + downloads: m["downloadCount"].as_f64().unwrap_or(0.) as u64, + page: m["links"]["websiteUrl"] + .as_str() + .unwrap_or_default() + .to_owned(), + icon: m["logo"]["thumbnailUrl"].as_str().map(str::to_owned), + // CurseForge's API doesn't say; the project page does. + license: String::new(), + kind, + game_versions, + loaders, + }) +} + +pub(super) fn parse_file(f: &Value) -> Option { + let (game_versions, loaders) = split_versions(&f["gameVersions"]); + let name = f["fileName"].as_str()?.to_owned(); + let sha1 = f["hashes"] + .as_array() + .into_iter() + .flatten() + .find(|h| h["algo"].as_u64() == Some(SHA1)) + .and_then(|h| h["value"].as_str()) + .map(str::to_ascii_lowercase); + let url = f["downloadUrl"].as_str().filter(|u| !u.is_empty()); + let files = url + .map(|url| { + vec![FileRef { + url: url.to_owned(), + name: name.clone(), + size: f["fileLength"].as_u64().unwrap_or(0), + sha512: None, + sha1, + primary: true, + }] + }) + .unwrap_or_default(); + Some(Version { + id: f["id"].as_u64()?.to_string(), + number: f["displayName"].as_str().unwrap_or(&name).to_owned(), + published: f["fileDate"].as_str().unwrap_or_default().to_owned(), + game_versions, + loaders, + files, + required: f["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["relationType"].as_u64() == Some(REQUIRED)) + .filter_map(|d| d["modId"].as_u64().map(|id| id.to_string())) + .collect(), + blocked: url + .is_none() + .then(|| "Its author allows downloads from CurseForge's own site only.".to_owned()), + }) +} + +impl Source for CurseForge { + fn id(&self) -> SourceId { + SourceId::CurseForge + } + + fn search(&self, query: &Query) -> Result, String> { + let found = self.get(&search_url(query))?; + Ok(found["data"] + .as_array() + .into_iter() + .flatten() + .filter_map(parse_mod) + .collect()) + } + + fn project(&self, id: &str) -> Result { + let m = self.get(&format!("{API}/mods/{}", encode(id)))?; + parse_mod(&m["data"]) + .ok_or_else(|| format!("CurseForge: {id} is not a pack Horizon loads.")) + } + + fn versions(&self, project: &Project) -> Result, String> { + let found = self.get(&format!( + "{API}/mods/{}/files?pageSize=50", + encode(&project.id) + ))?; + let mut all: Vec = found["data"] + .as_array() + .into_iter() + .flatten() + .filter(|f| f["isAvailable"].as_bool() != Some(false)) + .filter_map(parse_file) + .collect(); + all.sort_by(|a, b| b.published.cmp(&a.published)); + Ok(all) + } +} diff --git a/launcher/src/browser/download.rs b/launcher/src/browser/download.rs new file mode 100644 index 000000000..66199fd07 --- /dev/null +++ b/launcher/src/browser/download.rs @@ -0,0 +1,144 @@ +//! Downloads that reach the game folder only when their checksum matches the source's. +use super::{safe_name, FileRef}; +use sha1::Sha1; +use sha2::{Digest, Sha512}; +use std::fs; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; + +/// Hosts a file may come from: Modrinth's and CurseForge's file servers. +const HOSTS: [&str; 3] = [ + "https://cdn.modrinth.com/", + "https://edge.forgecdn.net/", + "https://mediafilez.forgecdn.net/", +]; +/// Bigger than any pack these sources serve (Modrinth caps uploads at 500 MiB). +const MAX: u64 = 1 << 30; + +/// The HTTP agent the sources share. Modrinth asks for a user agent that names the project. +pub(super) fn agent() -> ureq::Agent { + ureq::AgentBuilder::new() + .user_agent(&format!( + "ludovic111/horizon horizon-launcher/{} (github.com/ludovic111/horizon)", + crate::backend::VERSION + )) + .timeout_connect(std::time::Duration::from_secs(15)) + .timeout_read(std::time::Duration::from_secs(60)) + .build() +} + +/// Why a file can't be downloaded at all, before any byte is read. +pub fn refuse(file: &FileRef) -> Option { + if !HOSTS.iter().any(|h| file.url.starts_with(h)) { + return Some(format!( + "{} isn't on Modrinth's or CurseForge's file servers.", + file.url + )); + } + if safe_name(&file.name).is_none() { + return Some(format!("{:?} isn't a plain file name.", file.name)); + } + if file.checksum().is_none() { + return Some("Its source gives no checksum, so it can't be checked.".into()); + } + if file.size > MAX { + return Some("It is larger than any pack should be.".into()); + } + None +} + +/// Hashes as they are written: the strongest one the file lists. +enum Hasher { + Sha512(Sha512), + Sha1(Sha1), +} + +impl Hasher { + fn for_file(file: &FileRef) -> Self { + if file.sha512.is_some() { + Hasher::Sha512(Sha512::new()) + } else { + Hasher::Sha1(Sha1::new()) + } + } + fn update(&mut self, bytes: &[u8]) { + match self { + Hasher::Sha512(h) => h.update(bytes), + Hasher::Sha1(h) => h.update(bytes), + } + } + fn hex(self) -> String { + let bytes: Vec = match self { + Hasher::Sha512(h) => h.finalize().to_vec(), + Hasher::Sha1(h) => h.finalize().to_vec(), + }; + bytes.iter().map(|b| format!("{b:02x}")).collect() + } +} + +/// Copies `reader` into `/`, hashing on the way, and keeps it only when the +/// size and checksum match: until then it is `..part`, removed on any failure. +/// `progress` gets the fraction done. +pub fn save( + file: &FileRef, + mut reader: impl Read, + folder: &Path, + progress: &dyn Fn(f32), +) -> Result { + if let Some(why) = refuse(file) { + return Err(why); + } + let (algo, want) = file.checksum().expect("refuse checks for one"); + fs::create_dir_all(folder).map_err(|e| format!("{}: {e}", folder.display()))?; + let target = folder.join(&file.name); + let part = folder.join(format!(".{}.part", file.name)); + let result = (|| { + let mut out = fs::File::create(&part).map_err(|e| format!("{}: {e}", part.display()))?; + let mut hasher = Hasher::for_file(file); + let (mut done, mut buf) = (0u64, vec![0u8; 1 << 16]); + loop { + let n = reader + .read(&mut buf) + .map_err(|e| format!("Download interrupted: {e}"))?; + if n == 0 { + break; + } + done += n as u64; + if done > MAX || (file.size > 0 && done > file.size) { + return Err("The download is larger than its source says.".to_string()); + } + hasher.update(&buf[..n]); + out.write_all(&buf[..n]).map_err(|e| e.to_string())?; + progress(done as f32 / file.size.max(1) as f32); + } + if file.size > 0 && done != file.size { + return Err(format!("Got {done} bytes of {}.", file.size)); + } + let got = hasher.hex(); + if !got.eq_ignore_ascii_case(want) { + return Err(format!( + "The {algo} checksum doesn't match: the file isn't the one its source lists. \ + Nothing was installed." + )); + } + out.sync_all().map_err(|e| e.to_string())?; + drop(out); + fs::rename(&part, &target).map_err(|e| format!("{}: {e}", target.display())) + })(); + if result.is_err() { + let _ = fs::remove_file(&part); + } + result.map(|()| target) +} + +/// Downloads `file` into `folder`, checked as [`save`] does. +pub fn fetch(file: &FileRef, folder: &Path, progress: &dyn Fn(f32)) -> Result { + if let Some(why) = refuse(file) { + return Err(why); + } + let response = agent().get(&file.url).call().map_err(|e| match e { + ureq::Error::Status(code, _) => format!("{} answered {code}.", file.url), + ureq::Error::Transport(t) => format!("No connection: {t}"), + })?; + save(file, response.into_reader(), folder, progress) +} diff --git a/launcher/src/browser/modrinth.rs b/launcher/src/browser/modrinth.rs new file mode 100644 index 000000000..e7e39628a --- /dev/null +++ b/launcher/src/browser/modrinth.rs @@ -0,0 +1,214 @@ +//! Modrinth's public API (api.modrinth.com/v2): no key, files with SHA-512 and SHA-1. +use super::{FileRef, Kind, Project, Query, Source, SourceId, Version, GAME}; +use serde_json::Value; + +const API: &str = "https://api.modrinth.com/v2"; +const SITE: &str = "https://modrinth.com"; + +pub struct Modrinth; + +/// Modrinth's project type for a kind. +fn project_type(kind: Kind) -> &'static str { + match kind { + Kind::ResourcePack => "resourcepack", + Kind::ShaderPack => "shader", + Kind::Modpack => "modpack", + } +} + +fn kind_of(project_type: &str) -> Option { + Kind::ALL + .into_iter() + .find(|k| self::project_type(*k) == project_type) +} + +/// The search's facets (AND of ORs): the kind, and unless `everything` what runs. +pub(super) fn facets(query: &Query) -> String { + let mut all = vec![vec![format!("project_type:{}", project_type(query.kind))]]; + if !query.everything { + match query.kind { + Kind::ResourcePack => all.push(vec![format!("versions:{GAME}")]), + Kind::ShaderPack => { + all.push(vec!["categories:iris".into(), "categories:optifine".into()]) + } + Kind::Modpack => {} + } + } + serde_json::to_string(&all).unwrap_or_default() +} + +pub(super) fn search_url(query: &Query) -> String { + let mut url = format!( + "{API}/search?facets={}&index={}&offset={}&limit={}", + encode(&facets(query)), + if query.text.is_empty() { + "downloads" + } else { + "relevance" + }, + query.offset, + query.limit.clamp(1, 100), + ); + if !query.text.is_empty() { + url.push_str("&query="); + url.push_str(&encode(&query.text)); + } + url +} + +fn strings(v: &Value) -> Vec { + v.as_array() + .into_iter() + .flatten() + .filter_map(|s| s.as_str().map(str::to_owned)) + .collect() +} + +fn text(v: &Value) -> String { + v.as_str().unwrap_or_default().to_owned() +} + +/// A search hit. Its `categories` hold the loaders too; `versions` its Minecraft versions. +pub(super) fn parse_hit(hit: &Value) -> Option { + let kind = kind_of(hit["project_type"].as_str()?)?; + let slug = text(&hit["slug"]); + Some(Project { + source: SourceId::Modrinth, + id: hit["project_id"].as_str()?.to_owned(), + page: format!("{SITE}/{}/{slug}", project_type(kind)), + slug, + title: text(&hit["title"]), + summary: text(&hit["description"]), + author: text(&hit["author"]), + downloads: hit["downloads"].as_u64().unwrap_or(0), + icon: hit["icon_url"] + .as_str() + .filter(|u| !u.is_empty()) + .map(str::to_owned), + license: text(&hit["license"]), + kind, + game_versions: strings(&hit["versions"]), + loaders: strings(&hit["categories"]), + }) +} + +/// `GET /project/{id}`: the fields differ from a search hit's. +pub(super) fn parse_project(p: &Value) -> Option { + let kind = kind_of(p["project_type"].as_str()?)?; + let slug = text(&p["slug"]); + Some(Project { + source: SourceId::Modrinth, + id: p["id"].as_str()?.to_owned(), + page: format!("{SITE}/{}/{slug}", project_type(kind)), + slug, + title: text(&p["title"]), + summary: text(&p["description"]), + author: String::new(), + downloads: p["downloads"].as_u64().unwrap_or(0), + icon: p["icon_url"] + .as_str() + .filter(|u| !u.is_empty()) + .map(str::to_owned), + license: text(&p["license"]["id"]), + kind, + game_versions: strings(&p["game_versions"]), + loaders: strings(&p["loaders"]), + }) +} + +pub(super) fn parse_version(v: &Value) -> Option { + let files = v["files"] + .as_array()? + .iter() + .filter_map(|f| { + Some(FileRef { + url: f["url"].as_str()?.to_owned(), + name: f["filename"].as_str()?.to_owned(), + size: f["size"].as_u64().unwrap_or(0), + sha512: f["hashes"]["sha512"].as_str().map(str::to_ascii_lowercase), + sha1: f["hashes"]["sha1"].as_str().map(str::to_ascii_lowercase), + primary: f["primary"].as_bool().unwrap_or(false), + }) + }) + .collect(); + let required = v["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["dependency_type"] == "required") + .filter_map(|d| d["project_id"].as_str().map(str::to_owned)) + .collect(); + Some(Version { + id: v["id"].as_str()?.to_owned(), + number: text(&v["version_number"]), + published: text(&v["date_published"]), + game_versions: strings(&v["game_versions"]), + loaders: strings(&v["loaders"]), + files, + required, + blocked: None, + }) +} + +impl Source for Modrinth { + fn id(&self) -> SourceId { + SourceId::Modrinth + } + + fn search(&self, query: &Query) -> Result, String> { + let found = get(&search_url(query))?; + Ok(found["hits"] + .as_array() + .into_iter() + .flatten() + .filter_map(parse_hit) + .collect()) + } + + fn project(&self, id: &str) -> Result { + let p = get(&format!("{API}/project/{}", encode(id)))?; + parse_project(&p).ok_or_else(|| format!("Modrinth: {id} is not a pack Horizon loads.")) + } + + fn versions(&self, project: &Project) -> Result, String> { + let found = get(&format!("{API}/project/{}/version", encode(&project.id)))?; + let mut all: Vec = found + .as_array() + .into_iter() + .flatten() + .filter(|v| v["status"].as_str().is_none_or(|s| s == "listed")) + .filter_map(parse_version) + .collect(); + // Modrinth lists newest first already; ISO dates sort as text. + all.sort_by(|a, b| b.published.cmp(&a.published)); + Ok(all) + } +} + +fn get(url: &str) -> Result { + let response = super::download::agent() + .get(url) + .call() + .map_err(|e| match e { + ureq::Error::Status(429, _) => { + "Modrinth asks to slow down: try again in a minute.".into() + } + ureq::Error::Status(code, _) => format!("Modrinth answered {code}."), + ureq::Error::Transport(t) => format!("No connection to Modrinth: {t}"), + })?; + response + .into_json() + .map_err(|e| format!("Modrinth's answer wasn't readable: {e}")) +} + +/// Percent-encoding for a query value or a path segment. +pub(super) fn encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} diff --git a/launcher/src/browser/tests.rs b/launcher/src/browser/tests.rs new file mode 100644 index 000000000..ced342d13 --- /dev/null +++ b/launcher/src/browser/tests.rs @@ -0,0 +1,355 @@ +use super::*; +use serde_json::json; +use sha2::Digest; + +fn v(list: &[&str]) -> Vec { + list.iter().map(|s| s.to_string()).collect() +} + +fn version(id: &str, games: &[&str], loaders: &[&str]) -> Version { + Version { + id: id.into(), + number: id.into(), + published: String::new(), + game_versions: v(games), + loaders: v(loaders), + files: vec![FileRef { + url: format!("https://cdn.modrinth.com/data/x/versions/{id}/{id}.zip"), + name: format!("{id}.zip"), + size: 3, + sha512: Some("ab".into()), + sha1: None, + primary: true, + }], + required: Vec::new(), + blocked: None, + } +} + +#[test] +fn support_by_kind() { + assert_eq!( + support( + Kind::ResourcePack, + &v(&["1.21.4", GAME]), + &v(&["minecraft"]) + ), + Support::Works + ); + let old = support( + Kind::ResourcePack, + &v(&["1.20.1", "1.21.10", "1.21.9", "26.4-snapshot-1"]), + &[], + ); + assert_eq!(old.label(), "Partly"); + assert!( + old.reason().unwrap().starts_with("Made for 1.21.10:"), + "{old:?}" + ); + assert!(support(Kind::ShaderPack, &[], &v(&["iris"])).installable()); + assert!(support(Kind::ShaderPack, &[], &v(&["optifine"])).installable()); + let canvas = support(Kind::ShaderPack, &[], &v(&["canvas"])); + assert!(!canvas.installable()); + assert!(canvas.reason().unwrap().contains("canvas")); + assert!(!support(Kind::ShaderPack, &[], &[]).installable()); + assert!(support(Kind::Modpack, &v(&["1.21.1"]), &v(&["neoforge"])).installable()); +} + +#[test] +fn picks_the_newest_version_that_runs() { + let versions = [ + version("snapshot", &["26.4-snapshot-5"], &["minecraft"]), + version("now", &["26.2", GAME], &["minecraft"]), + version("old", &["1.21.1"], &["minecraft"]), + ]; + assert_eq!( + pick(Kind::ResourcePack, &versions, false).unwrap().id, + "now" + ); + let old = [version("old", &["1.21.1"], &["minecraft"])]; + assert!(pick(Kind::ResourcePack, &old, false).is_none()); + assert_eq!(pick(Kind::ResourcePack, &old, true).unwrap().id, "old"); + + let shaders = [ + version("canvas", &[GAME], &["canvas"]), + version("iris", &["1.21.1"], &["iris"]), + ]; + assert_eq!(pick(Kind::ShaderPack, &shaders, false).unwrap().id, "iris"); + let only_canvas = [version("canvas", &[GAME], &["canvas"])]; + assert!(pick(Kind::ShaderPack, &only_canvas, true).is_none()); + + let mut blocked = version("blocked", &[GAME], &["minecraft"]); + blocked.blocked = Some("no".into()); + let mut empty = version("empty", &[GAME], &["minecraft"]); + empty.files.clear(); + assert!(pick(Kind::ResourcePack, &[blocked, empty], true).is_none()); +} + +#[test] +fn file_names_must_be_plain() { + for good in [ + "Faithful 32x.zip", + "FreshAnimations_v1.11.1_26.1+.zip", + "BSL_v10.zip", + ] { + assert_eq!(safe_name(good), Some(good)); + } + for bad in [ + "", + "../x.zip", + "a/b.zip", + "a\\b.zip", + ".hidden.zip", + "c:x.zip", + "x.zip.", + "x\n.zip", + ] { + assert_eq!(safe_name(bad), None, "{bad:?}"); + } +} + +#[test] +fn modrinth_search_asks_for_what_runs() { + let q = Query::new(" faithful ", Kind::ResourcePack); + assert_eq!(q.text, "faithful"); + assert_eq!( + modrinth::facets(&q), + r#"[["project_type:resourcepack"],["versions:26.3"]]"# + ); + let url = modrinth::search_url(&q); + assert!(url.starts_with("https://api.modrinth.com/v2/search?facets=%5B%5B%22project_type")); + assert!( + url.contains("&index=relevance&") && url.ends_with("&query=faithful"), + "{url}" + ); + let shaders = Query::new("", Kind::ShaderPack); + assert_eq!( + modrinth::facets(&shaders), + r#"[["project_type:shader"],["categories:iris","categories:optifine"]]"# + ); + assert!(modrinth::search_url(&shaders).contains("&index=downloads&")); + let everything = Query { + everything: true, + ..Query::new("", Kind::ResourcePack) + }; + assert_eq!( + modrinth::facets(&everything), + r#"[["project_type:resourcepack"]]"# + ); + assert_eq!( + modrinth::facets(&Query::new("", Kind::Modpack)), + r#"[["project_type:modpack"]]"# + ); +} + +#[test] +fn modrinth_answers() { + let hit = json!({ + "project_id": "50dA9Sha", "project_type": "resourcepack", "slug": "fresh-animations", + "title": "Fresh Animations", "description": "Animated entities.", "author": "FreshLX", + "downloads": 51404735, "icon_url": "https://cdn.modrinth.com/data/50dA9Sha/icon.webp", + "license": "LicenseRef-See-Terms", "versions": ["1.21.11", "26.3"], + "categories": ["16x", "minecraft"] + }); + let p = modrinth::parse_hit(&hit).unwrap(); + assert_eq!(p.id, "50dA9Sha"); + assert_eq!(p.kind, Kind::ResourcePack); + assert_eq!(p.page, "https://modrinth.com/resourcepack/fresh-animations"); + assert_eq!(p.support(), Support::Works); + assert_eq!(p.downloads, 51404735); + // A Java mod is never a result. + let jar = json!({"project_id": "AANobbMI", "project_type": "mod", "slug": "sodium"}); + assert!(modrinth::parse_hit(&jar).is_none()); + + let project = json!({ + "id": "HVnmMxH1", "project_type": "shader", "slug": "complementary-reimagined", + "title": "Complementary Shaders - Reimagined", "description": "d", + "license": {"id": "LicenseRef-Complementary", "name": ""}, + "game_versions": ["1.21.1"], "loaders": ["iris", "optifine"] + }); + let p = modrinth::parse_project(&project).unwrap(); + assert_eq!(p.kind, Kind::ShaderPack); + assert_eq!(p.license, "LicenseRef-Complementary"); + assert_eq!( + p.page, + "https://modrinth.com/shader/complementary-reimagined" + ); + assert!(p.support().installable()); + + let version = json!({ + "id": "tvGVYMD4", "version_number": "1.11.1", "date_published": "2026-10-20T02:23:13Z", + "game_versions": ["26.2", "26.3"], "loaders": ["minecraft"], + "dependencies": [ + {"project_id": "need", "dependency_type": "required"}, + {"project_id": "maybe", "dependency_type": "optional"}, + {"version_id": "x", "project_id": null, "dependency_type": "required"} + ], + "files": [ + {"hashes": {"sha512": "AB12", "sha1": "cd34"}, "url": "https://cdn.modrinth.com/data/a/b.zip", + "filename": "b.zip", "primary": false, "size": 10}, + {"hashes": {"sha512": "ef56", "sha1": "0789"}, "url": "https://cdn.modrinth.com/data/a/c.zip", + "filename": "c.zip", "primary": true, "size": 20} + ] + }); + let ver = modrinth::parse_version(&version).unwrap(); + assert_eq!(ver.required, ["need"]); + assert_eq!(ver.files[0].sha512.as_deref(), Some("ab12")); + let file = ver.file().unwrap(); + assert_eq!(file.name, "c.zip"); + assert_eq!(file.checksum(), Some(("SHA-512", "ef56"))); +} + +#[test] +fn curseforge_stays_off_without_a_key() { + assert_eq!(curseforge::key(None, None), None); + assert_eq!(curseforge::key(Some(" ".into()), None), None); + assert_eq!(curseforge::key(None, Some("")), None); + assert_eq!( + curseforge::key(None, Some("built")).as_deref(), + Some("built") + ); + assert_eq!( + curseforge::key(Some("env ".into()), Some("built")).as_deref(), + Some("env") + ); +} + +#[test] +fn curseforge_answers() { + let q = Query::new("bsl", Kind::ShaderPack); + let url = curseforge::search_url(&q); + assert!(url.contains("gameId=432&classId=6552&"), "{url}"); + assert!( + !url.contains("gameVersion=") && url.ends_with("&searchFilter=bsl"), + "{url}" + ); + assert!( + curseforge::search_url(&Query::new("", Kind::ResourcePack)).contains("&gameVersion=26.3") + ); + + let m = json!({ + "id": 228756, "classId": 6552, "slug": "bsl-shaders", "name": "BSL Shaders", + "summary": "s", "authors": [{"name": "CaptTatsu"}], "downloadCount": 1.5e7, + "links": {"websiteUrl": "https://www.curseforge.com/minecraft/shaders/bsl-shaders"}, + "logo": {"thumbnailUrl": "https://media.forgecdn.net/avatars/thumbnails/x.png"}, + "latestFilesIndexes": [{"gameVersion": "1.21.1"}], + "latestFiles": [{"gameVersions": ["1.21.1", "Iris", "OptiFine"]}] + }); + let p = curseforge::parse_mod(&m).unwrap(); + assert_eq!( + (p.source, p.id.as_str(), p.kind), + (SourceId::CurseForge, "228756", Kind::ShaderPack) + ); + assert_eq!(p.loaders, ["iris", "optifine"]); + assert_eq!(p.author, "CaptTatsu"); + assert!(p.support().installable()); + assert!(curseforge::parse_mod(&json!({"id": 1, "classId": 6})).is_none()); + + let file = json!({ + "id": 5000, "displayName": "BSL v10", "fileName": "BSL_v10.zip", "fileLength": 300, + "fileDate": "2026-01-01T00:00:00Z", "downloadUrl": "https://edge.forgecdn.net/files/5/0/BSL_v10.zip", + "gameVersions": ["1.21.1", "Iris"], + "hashes": [{"value": "D41D8CD9", "algo": 2}, {"value": "DA39A3EE", "algo": 1}], + "dependencies": [{"modId": 7, "relationType": 3}, {"modId": 8, "relationType": 2}] + }); + let ver = curseforge::parse_file(&file).unwrap(); + assert_eq!(ver.required, ["7"]); + assert_eq!(ver.loaders, ["iris"]); + assert_eq!(ver.file().unwrap().checksum(), Some(("SHA-1", "da39a3ee"))); + assert!(ver.blocked.is_none()); + let mut closed = file.clone(); + closed["downloadUrl"] = serde_json::Value::Null; + let ver = curseforge::parse_file(&closed).unwrap(); + assert!(ver.files.is_empty() && ver.blocked.is_some()); +} + +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-browser-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + dir +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn file_for(body: &[u8], sha512: bool) -> FileRef { + FileRef { + url: "https://cdn.modrinth.com/data/a/versions/b/pack.zip".into(), + name: "pack.zip".into(), + size: body.len() as u64, + sha512: sha512.then(|| hex(&sha2::Sha512::digest(body))), + sha1: (!sha512).then(|| hex(&sha1::Sha1::digest(body))), + primary: true, + } +} + +#[test] +fn a_download_is_kept_only_when_its_checksum_matches() { + let dir = scratch("save"); + let body = b"a resource pack"; + for strong in [true, false] { + let file = file_for(body, strong); + let path = download::save(&file, &body[..], &dir, &|_| {}).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), body); + std::fs::remove_file(path).unwrap(); + } + // Another file than the one listed: refused, and nothing is left behind. + let file = file_for(body, true); + let other = b"a resource paCk"; + let e = download::save(&file, &other[..], &dir, &|_| {}).unwrap_err(); + assert!(e.contains("SHA-512 checksum doesn't match"), "{e}"); + let short = download::save(&file, &body[..4], &dir, &|_| {}).unwrap_err(); + assert!(short.starts_with("Got 4 bytes"), "{short}"); + let long = download::save(&file, &b"a resource pack and more"[..], &dir, &|_| {}).unwrap_err(); + assert!(long.contains("larger"), "{long}"); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 0); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn downloads_refused_before_any_byte() { + let body = b"x"; + let mut file = file_for(body, true); + file.url = "https://example.com/pack.zip".into(); + assert!(download::refuse(&file).unwrap().contains("file servers")); + let mut file = file_for(body, true); + file.url = "http://cdn.modrinth.com/data/a/pack.zip".into(); + assert!(download::refuse(&file).is_some()); + let mut file = file_for(body, true); + file.name = "../../options.txt".into(); + assert!(download::refuse(&file).unwrap().contains("plain file name")); + let mut file = file_for(body, true); + file.sha512 = None; + assert!(download::refuse(&file).unwrap().contains("no checksum")); + let mut file = file_for(body, false); + file.url = "https://edge.forgecdn.net/files/1/2/pack.zip".into(); + assert_eq!(download::refuse(&file), None); +} + +/// Against the real Modrinth: `cargo test --lib browser::tests::live -- --ignored`. +#[test] +#[ignore = "needs the network"] +fn live_modrinth_search_pick_and_download() { + let source = modrinth::Modrinth; + for kind in Kind::ALL { + let found = source.search(&Query::new("", kind)).unwrap(); + assert!(!found.is_empty(), "{kind:?}"); + assert!(found + .iter() + .all(|p| p.kind == kind && p.support().installable())); + } + let packs = source + .search(&Query::new("fresh animations", Kind::ResourcePack)) + .unwrap(); + let p = packs.iter().find(|p| p.slug == "fresh-animations").unwrap(); + assert_eq!(p.support(), Support::Works); + let versions = source.versions(p).unwrap(); + let chosen = pick(p.kind, &versions, false).unwrap(); + assert!(chosen.game_versions.iter().any(|g| g == GAME)); + let dir = scratch("live"); + let path = download::fetch(chosen.file().unwrap(), &dir, &|_| {}).unwrap(); + assert!(path.is_file()); + std::fs::remove_dir_all(&dir).unwrap(); + assert_eq!(source.project(&p.id).unwrap().slug, p.slug); +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 99445abf3..98228b5fc 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -1,6 +1,7 @@ //! The launcher's core, shared by the GUI, the CLI and the MCP server. pub mod account; pub mod backend; +pub mod browser; pub mod desktop; pub mod heads; pub mod modpacks; From 9346ac04ad4120b8ae7dfa926d508ca27eea0da3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:22:39 +0200 Subject: [PATCH 040/115] Mod browser (2/3): install, update and remove, with `horizon-launcher mods` browser::installed installs a pack and its required dependencies into resourcepacks/ or shaderpacks/, every file checked before any download (a dependency that is a Java mod stops it) and checksum-verified on the way in; mod-browser.json records source, version, file and checksum. Update swaps the file, remove deletes only what the browser installed (a player's own file of the same name is never overwritten). A modpack is downloaded, checked, and imported through the Modpacks page's pipeline. The CLI gains `mods list|search|install|update|remove`. Co-Authored-By: Claude Opus 5.5 --- docs/mod-browser.md | 25 +++ launcher/README.md | 5 + launcher/src/browser.rs | 23 ++- launcher/src/browser/installed.rs | 260 ++++++++++++++++++++++++ launcher/src/browser/installed/tests.rs | 252 +++++++++++++++++++++++ launcher/src/cli.rs | 211 +++++++++++++++++++ 6 files changed, 774 insertions(+), 2 deletions(-) create mode 100644 launcher/src/browser/installed.rs create mode 100644 launcher/src/browser/installed/tests.rs diff --git a/docs/mod-browser.md b/docs/mod-browser.md index 888a64bb8..b7a9176c5 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -30,6 +30,31 @@ never offered for install. else removes the part file and installs nothing. - A file whose source lists no checksum is refused. +## Installing, updating, removing + +`mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file +and the checksum it was checked against. The browser replaces or removes only the files it lists; a file of the +same name the player put there is never overwritten. + +- **Install** picks the newest version that runs, then its required dependencies, checked before any download: a + dependency that isn't a pack Horizon loads (a Java mod) stops the install. Dependencies go in first. A resource + pack still has to be turned on in the game's Resource Packs screen, and a shader pack in Video Settings > Shader + Packs, as in vanilla and Iris. +- **Update** installs the newer version and removes the old file. +- **Remove** deletes the file and its entry. Packs installed as dependencies stay. +- **A modpack** is downloaded (checked the same way) into `ports/downloads/` and imported on the Modpacks page, + which says what of it Horizon runs and ports it. + +From a terminal (or an agent): + +```sh +horizon-launcher mods search faithful # --kind resource|shader|modpack, --everything, --source +horizon-launcher mods install faithful-32x # id or slug; a modpack is imported +horizon-launcher mods list # --json +horizon-launcher mods update [faithful-32x] [--check] +horizon-launcher mods remove faithful-32x +``` + ## Sources **Modrinth.** The public API (`api.modrinth.com/v2`) needs no key. The launcher names itself in its user agent, as diff --git a/launcher/README.md b/launcher/README.md index d6168dbb4..e95d72649 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -139,6 +139,11 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over horizon-launcher modpack play [--version ] play it as its own profile horizon-launcher modpack remove + horizon-launcher mods [list] what the mod browser installed (docs/mod-browser.md) + horizon-launcher mods search [--kind resource|shader|modpack] [--everything] [--source modrinth|curseforge] + horizon-launcher mods install checksum checked, with what it needs; a modpack is imported + horizon-launcher mods update [] [--check] + horizon-launcher mods remove horizon-launcher servers [list] the servers hosted from the launcher, and whether they run horizon-launcher servers create [--name N] [--seed S | --copy-world DIR] [--mode M] [--difficulty D] [--max-players N] [--open] [--check-accounts] [--player NAME]... --accept-eula diff --git a/launcher/src/browser.rs b/launcher/src/browser.rs index 7010024f4..49ec1e696 100644 --- a/launcher/src/browser.rs +++ b/launcher/src/browser.rs @@ -7,14 +7,18 @@ //! page). Java mod jars don't run in Horizon (docs/mods.md), so they are never searched. pub mod curseforge; pub mod download; +pub mod installed; pub mod modrinth; +use serde::{Deserialize, Serialize}; + /// The Minecraft version Horizon plays. A version port updates it with the other `"26.3"` sites /// (docs/version-ports.md). pub const GAME: &str = "26.3"; /// What a project is, as far as Horizon is concerned. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum Kind { ResourcePack, ShaderPack, @@ -43,7 +47,8 @@ impl Kind { } /// Where a project comes from. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] pub enum SourceId { Modrinth, CurseForge, @@ -194,6 +199,15 @@ pub trait Source: Send + Sync { fn project(&self, id: &str) -> Result; /// Versions, newest first. fn versions(&self, project: &Project) -> Result, String>; + /// Downloads one of its files into `folder`, checked ([`download::fetch`]). + fn fetch( + &self, + file: &FileRef, + folder: &std::path::Path, + progress: &dyn Fn(f32), + ) -> Result { + download::fetch(file, folder, progress) + } } /// The sources this launcher can use: Modrinth always, CurseForge when it has an API key. @@ -205,6 +219,11 @@ pub fn sources() -> Vec> { all } +/// The source of that id, when this launcher can use it. +pub fn source(id: SourceId) -> Option> { + sources().into_iter().find(|s| s.id() == id) +} + /// The loaders a Java shader pack may name that Horizon translates. const SHADER_LOADERS: [&str; 2] = ["iris", "optifine"]; diff --git a/launcher/src/browser/installed.rs b/launcher/src/browser/installed.rs new file mode 100644 index 000000000..d1aac1af5 --- /dev/null +++ b/launcher/src/browser/installed.rs @@ -0,0 +1,260 @@ +//! What the browser installed into the game folder, and installing, updating and removing it. +//! +//! `mod-browser.json` beside `options.txt` lists each file the browser put in `resourcepacks/` +//! or `shaderpacks/`: where it came from, its version and its checksum. Files the player put +//! there themselves are never touched: the browser only replaces or removes what it lists. +use super::{pick, safe_name, Kind, Project, Source, SourceId, Support, Version}; +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; + +const MANIFEST: &str = "mod-browser.json"; +/// How deep required dependencies are followed. +const MAX_DEPTH: usize = 4; + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub source: SourceId, + pub project: String, + pub slug: String, + pub title: String, + pub kind: Kind, + pub version: String, + pub number: String, + /// Relative to the game folder: `resourcepacks/`. + pub file: String, + /// The checksum the download was checked against: `SHA-512:`. + pub checksum: String, + pub page: String, + /// Installed because another pack needs it. + #[serde(default)] + pub dependency: bool, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Installed { + pub entries: Vec, +} + +impl Installed { + pub fn load(home: &Path) -> Self { + fs::read_to_string(home.join(MANIFEST)) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + + pub fn save(&self, home: &Path) -> Result<(), String> { + let path = home.join(MANIFEST); + let part = home.join(format!(".{MANIFEST}.part")); + let text = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?; + fs::create_dir_all(home).map_err(|e| format!("{}: {e}", home.display()))?; + fs::write(&part, text).map_err(|e| format!("{}: {e}", part.display()))?; + fs::rename(&part, &path).map_err(|e| format!("{}: {e}", path.display())) + } + + pub fn find(&self, source: SourceId, project: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.source == source && e.project == project) + } + + /// By project id or slug, as the CLI takes them. + pub fn lookup(&self, name: &str) -> Option<&Entry> { + self.entries + .iter() + .find(|e| e.project == name || e.slug == name) + } +} + +/// One file to install: the project, the version chosen and why it was pulled in. +#[derive(Clone, Debug)] +pub struct Step { + pub project: Project, + pub version: Version, + pub dependency: bool, +} + +/// What installing `project` takes, dependencies first, checked before any byte is downloaded: +/// every file runs in Horizon and has a version to install. +pub fn plan(source: &dyn Source, project: &Project, everything: bool) -> Result, String> { + if project.kind.folder().is_none() { + return Err(format!( + "{} is a modpack: it is imported on the Modpacks page.", + project.title + )); + } + let mut steps = Vec::new(); + add(source, project.clone(), everything, false, 0, &mut steps)?; + Ok(steps) +} + +fn add( + source: &dyn Source, + project: Project, + everything: bool, + dependency: bool, + depth: usize, + steps: &mut Vec, +) -> Result<(), String> { + if steps.iter().any(|s| s.project.id == project.id) { + return Ok(()); + } + if depth > MAX_DEPTH { + return Err(format!("{}'s dependencies go too deep.", project.title)); + } + if let Support::No(why) = project.support() { + return Err(format!("{} doesn't run in Horizon: {why}", project.title)); + } + let versions = source.versions(&project)?; + let Some(version) = pick(project.kind, &versions, everything).cloned() else { + return Err(match versions.iter().find_map(|v| v.blocked.clone()) { + Some(why) => format!("{} can't be installed from here: {why}", project.title), + None => format!("{} has no version Horizon runs.", project.title), + }); + }; + for id in &version.required { + let needed = source.project(id).map_err(|_| { + format!( + "{} needs {id} on {}, which isn't a pack Horizon loads (a Java mod?).", + project.title, + source.id().label() + ) + })?; + if needed.kind.folder().is_none() { + return Err(format!( + "{} needs the modpack {}.", + project.title, needed.title + )); + } + add(source, needed, everything, true, depth + 1, steps)?; + } + steps.push(Step { + project, + version, + dependency, + }); + Ok(()) +} + +/// Installs `project` (and what it needs) into the game folder `home`. A project already +/// installed is updated to the version chosen. `progress` gets a line per file and the fraction. +pub fn install( + source: &dyn Source, + project: &Project, + everything: bool, + home: &Path, + progress: &dyn Fn(&str, f32), +) -> Result, String> { + let steps = plan(source, project, everything)?; + let mut installed = Installed::load(home); + let mut done = Vec::new(); + for step in steps { + let p = &step.project; + let old = installed.find(p.source, &p.id).cloned(); + if old.as_ref().is_some_and(|o| o.version == step.version.id) { + done.push(old.expect("checked")); + continue; + } + let file = step + .version + .file() + .expect("pick keeps versions with a file"); + let folder_name = p.kind.folder().expect("plan keeps folder kinds"); + let name = safe_name(&file.name) + .ok_or_else(|| format!("{:?} isn't a plain file name.", file.name))?; + let relative = format!("{folder_name}/{name}"); + let owner = installed.entries.iter().find(|e| e.file == relative); + let ours = owner.is_some_and(|e| e.source == p.source && e.project == p.id); + if home.join(&relative).exists() && !ours { + return Err(match owner { + Some(e) => format!( + "{relative} belongs to {}, installed from the browser.", + e.title + ), + None => format!( + "{relative} is already there and wasn't installed by the browser: move it \ + away first, or keep it." + ), + }); + } + let line = format!("{} {}", p.title, step.version.number); + let path = source.fetch(file, &home.join(folder_name), &|f| progress(&line, f))?; + let (algo, hash) = file.checksum().expect("fetch checks for one"); + if let Some(old) = &old { + if old.file != relative { + let _ = fs::remove_file(home.join(&old.file)); + } + } + let entry = Entry { + source: p.source, + project: p.id.clone(), + slug: p.slug.clone(), + title: p.title.clone(), + kind: p.kind, + version: step.version.id.clone(), + number: step.version.number.clone(), + file: relative, + checksum: format!("{algo}:{hash}"), + page: p.page.clone(), + // Asked for by the player once: it stays theirs. + dependency: step.dependency && old.as_ref().is_none_or(|o| o.dependency), + }; + debug_assert!(path.ends_with(name)); + installed + .entries + .retain(|e| !(e.source == p.source && e.project == p.id)); + installed.entries.push(entry.clone()); + installed.save(home)?; + done.push(entry); + } + Ok(done) +} + +/// Removes what the browser installed for `name` (a project id or slug): its file and its entry. +pub fn remove(home: &Path, name: &str) -> Result { + let mut installed = Installed::load(home); + let entry = installed + .lookup(name) + .cloned() + .ok_or_else(|| format!("{name} wasn't installed by the browser."))?; + match fs::remove_file(home.join(&entry.file)) { + Ok(()) => {} + Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} + Err(e) => return Err(format!("{}: {e}", entry.file)), + } + installed + .entries + .retain(|e| !(e.source == entry.source && e.project == entry.project)); + installed.save(home)?; + Ok(entry) +} + +/// The newer version `entry` can be updated to, if any. +pub fn update_for(source: &dyn Source, entry: &Entry) -> Result, String> { + let project = source.project(&entry.project)?; + let versions = source.versions(&project)?; + Ok(pick(project.kind, &versions, true) + .filter(|v| v.id != entry.version) + .cloned()) +} + +/// Downloads a modpack's file, checked, into `folder` (kept there: the import reads it). +pub fn fetch_modpack( + source: &dyn Source, + project: &Project, + folder: &Path, + progress: &dyn Fn(f32), +) -> Result { + if project.kind != Kind::Modpack { + return Err(format!("{} isn't a modpack.", project.title)); + } + let versions = source.versions(project)?; + let version = pick(Kind::Modpack, &versions, true) + .ok_or_else(|| format!("{} has no file to download.", project.title))?; + let file = version.file().expect("pick keeps versions with a file"); + source.fetch(file, folder, progress) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/browser/installed/tests.rs b/launcher/src/browser/installed/tests.rs new file mode 100644 index 000000000..33dc525ab --- /dev/null +++ b/launcher/src/browser/installed/tests.rs @@ -0,0 +1,252 @@ +use super::*; +use crate::browser::{download, FileRef, Query, GAME}; +use sha2::Digest; +use std::collections::HashMap; +use std::sync::Mutex; + +/// A source in memory: projects, their versions, and the bytes each file URL serves. +#[derive(Default)] +struct Fake { + projects: HashMap, + versions: Mutex>>, + bytes: Mutex>>, +} + +impl Source for Fake { + fn id(&self) -> SourceId { + SourceId::Modrinth + } + fn search(&self, _: &Query) -> Result, String> { + Ok(self.projects.values().cloned().collect()) + } + fn project(&self, id: &str) -> Result { + self.projects + .get(id) + .cloned() + .ok_or_else(|| "not a pack".into()) + } + fn versions(&self, p: &Project) -> Result, String> { + Ok(self + .versions + .lock() + .unwrap() + .get(&p.id) + .cloned() + .unwrap_or_default()) + } + fn fetch( + &self, + file: &FileRef, + folder: &Path, + progress: &dyn Fn(f32), + ) -> Result { + let body = self + .bytes + .lock() + .unwrap() + .get(&file.url) + .cloned() + .unwrap_or_default(); + download::save(file, &body[..], folder, progress) + } +} + +fn project(id: &str, kind: Kind) -> Project { + Project { + source: SourceId::Modrinth, + id: id.into(), + slug: format!("{id}-slug"), + title: format!("Pack {id}"), + summary: String::new(), + author: String::new(), + downloads: 0, + page: format!("https://modrinth.com/resourcepack/{id}-slug"), + icon: None, + license: "MIT".into(), + kind, + game_versions: vec![GAME.into()], + loaders: vec![if kind == Kind::ShaderPack { + "iris" + } else { + "minecraft" + } + .into()], + } +} + +impl Fake { + fn add(&mut self, p: Project) { + self.projects.insert(p.id.clone(), p); + } + /// A new newest version of `id`, its file serving `body`; `tamper` serves other bytes. + fn release(&self, id: &str, number: &str, needs: &[&str], body: &[u8], tamper: bool) { + let url = format!("https://cdn.modrinth.com/data/{id}/versions/{number}/{id}-{number}.zip"); + let file = FileRef { + url: url.clone(), + name: format!("{id}-{number}.zip"), + size: body.len() as u64, + sha512: Some( + sha2::Sha512::digest(body) + .iter() + .map(|b| format!("{b:02x}")) + .collect(), + ), + sha1: None, + primary: true, + }; + let version = Version { + id: format!("{id}@{number}"), + number: number.into(), + published: number.into(), + game_versions: vec![GAME.into()], + loaders: self.projects[id].loaders.clone(), + files: vec![file], + required: needs.iter().map(|s| s.to_string()).collect(), + blocked: None, + }; + let mut served = body.to_vec(); + if tamper { + served[0] ^= 1; + } + self.bytes.lock().unwrap().insert(url, served); + let mut versions = self.versions.lock().unwrap(); + versions.entry(id.into()).or_default().insert(0, version); + } +} + +fn home(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-installed-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +const NONE: &dyn Fn(&str, f32) = &|_, _| {}; + +#[test] +fn installs_with_dependencies_then_updates_and_removes() { + let home = home("cycle"); + let mut fake = Fake::default(); + fake.add(project("base", Kind::ResourcePack)); + fake.add(project("addon", Kind::ResourcePack)); + fake.release("base", "1", &[], b"base pack", false); + fake.release("addon", "1", &["base"], b"addon pack", false); + let addon = fake.project("addon").unwrap(); + + let done = install(&fake, &addon, false, &home, NONE).unwrap(); + let files: Vec<&str> = done.iter().map(|e| e.file.as_str()).collect(); + assert_eq!( + files, + ["resourcepacks/base-1.zip", "resourcepacks/addon-1.zip"] + ); + assert!(done[0].dependency && !done[1].dependency); + assert!(done[1].checksum.starts_with("SHA-512:")); + assert_eq!( + fs::read(home.join("resourcepacks/addon-1.zip")).unwrap(), + b"addon pack" + ); + assert_eq!(Installed::load(&home).entries.len(), 2); + + // Installing again with nothing new downloads nothing. + fs::remove_file(home.join("resourcepacks/base-1.zip")).unwrap(); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/base-1.zip").exists()); + + // An update replaces the old file. + fake.release("addon", "2", &["base"], b"addon pack v2", false); + let entry = Installed::load(&home).lookup("addon").cloned().unwrap(); + assert_eq!(update_for(&fake, &entry).unwrap().unwrap().number, "2"); + install(&fake, &addon, false, &home, NONE).unwrap(); + assert!(!home.join("resourcepacks/addon-1.zip").exists()); + assert_eq!( + fs::read(home.join("resourcepacks/addon-2.zip")).unwrap(), + b"addon pack v2" + ); + let entry = Installed::load(&home) + .lookup("addon-slug") + .cloned() + .unwrap(); + assert_eq!(entry.number, "2"); + assert!(update_for(&fake, &entry).unwrap().is_none()); + + let removed = remove(&home, "addon").unwrap(); + assert_eq!(removed.project, "addon"); + assert!(!home.join("resourcepacks/addon-2.zip").exists()); + assert!(remove(&home, "addon").is_err()); + assert_eq!(Installed::load(&home).entries.len(), 1); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn nothing_is_installed_when_a_check_fails() { + let home = home("refuse"); + let mut fake = Fake::default(); + fake.add(project("good", Kind::ResourcePack)); + fake.add(project("bad", Kind::ResourcePack)); + fake.add(project("needs-mod", Kind::ResourcePack)); + fake.release("good", "1", &[], b"good", false); + fake.release("bad", "1", &[], b"tampered", true); + fake.release("needs-mod", "1", &["sodium"], b"x", false); + + let e = install(&fake, &fake.project("bad").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("checksum doesn't match"), "{e}"); + let e = install( + &fake, + &fake.project("needs-mod").unwrap(), + false, + &home, + NONE, + ) + .unwrap_err(); + assert!(e.contains("needs sodium"), "{e}"); + assert!( + !home.join("resourcepacks").exists() + || fs::read_dir(home.join("resourcepacks")).unwrap().count() == 0 + ); + assert!(Installed::load(&home).entries.is_empty()); + + // The player's own file of the same name is never replaced. + fs::create_dir_all(home.join("resourcepacks")).unwrap(); + fs::write(home.join("resourcepacks/good-1.zip"), b"mine").unwrap(); + let e = install(&fake, &fake.project("good").unwrap(), false, &home, NONE).unwrap_err(); + assert!(e.contains("wasn't installed by the browser"), "{e}"); + assert_eq!( + fs::read(home.join("resourcepacks/good-1.zip")).unwrap(), + b"mine" + ); + assert!(remove(&home, "good").is_err()); + assert!(home.join("resourcepacks/good-1.zip").exists()); + + // What doesn't run is refused before anything is asked for. + let mut canvas = project("canvas", Kind::ShaderPack); + canvas.loaders = vec!["canvas".into()]; + fake.add(canvas.clone()); + assert!(install(&fake, &canvas, true, &home, NONE) + .unwrap_err() + .contains("doesn't run")); + let pack = project("pack", Kind::Modpack); + assert!(plan(&fake, &pack, false) + .unwrap_err() + .contains("Modpacks page")); + fs::remove_dir_all(&home).unwrap(); +} + +#[test] +fn shader_packs_go_to_their_folder_and_modpacks_download_checked() { + let home = home("kinds"); + let mut fake = Fake::default(); + fake.add(project("bsl", Kind::ShaderPack)); + fake.release("bsl", "10", &[], b"shaders", false); + install(&fake, &fake.project("bsl").unwrap(), false, &home, NONE).unwrap(); + assert!(home.join("shaderpacks/bsl-10.zip").is_file()); + + fake.add(project("atm", Kind::Modpack)); + fake.release("atm", "1", &[], b"mrpack", false); + let downloads = home.join("downloads"); + let path = fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).unwrap(); + assert_eq!(fs::read(path).unwrap(), b"mrpack"); + fake.release("atm", "2", &[], b"mrpack 2", true); + assert!(fetch_modpack(&fake, &fake.project("atm").unwrap(), &downloads, &|_| {}).is_err()); + assert!(!downloads.join("atm-2.zip").exists()); + fs::remove_dir_all(&home).unwrap(); +} diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index a43529db0..6dcb4b975 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -155,6 +155,68 @@ enum ModpackCmd { Remove { pack: String }, } +#[derive(Subcommand)] +enum ModsCmd { + /// What the browser installed (the default) + List, + /// Search for packs Horizon loads + Search { + text: Vec, + #[arg(long, value_enum, default_value_t = KindArg::Resource)] + kind: KindArg, + /// Also what was made for other versions or runs only partly, each marked + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Install a pack and what it needs, by its id or slug (checksums checked); a modpack is + /// imported on the Modpacks page + Install { + project: String, + /// Allow a version made for another Minecraft version + #[arg(long)] + everything: bool, + #[arg(long, value_enum, default_value_t = SourceArg::Modrinth)] + source: SourceArg, + }, + /// Update what the browser installed (or one pack) + Update { + project: Option, + /// Only say what is newer + #[arg(long)] + check: bool, + }, + /// Remove a pack the browser installed + Remove { project: String }, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum KindArg { + Resource, + Shader, + Modpack, +} + +#[derive(Clone, Copy, clap::ValueEnum)] +enum SourceArg { + Modrinth, + Curseforge, +} + +impl SourceArg { + fn get(self) -> Result, String> { + use horizon_launcher::browser::{self, SourceId}; + let id = match self { + SourceArg::Modrinth => SourceId::Modrinth, + SourceArg::Curseforge => SourceId::CurseForge, + }; + browser::source(id).ok_or_else(|| { + "CurseForge needs an API key: HORIZON_CURSEFORGE_API_KEY (docs/mod-browser.md).".into() + }) + } +} + #[derive(Subcommand)] enum Cmd { /// List Horizon releases, or the installed versions @@ -257,6 +319,12 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// The mod browser: resource packs, shader packs and modpacks from Modrinth (and CurseForge + /// with a key), each file checked against its checksum (docs/mod-browser.md) + Mods { + #[command(subcommand)] + action: Option, + }, /// Servers hosted with horizon-server (the Servers page): list them, create one, or run any /// horizon-server command on one Servers { @@ -523,6 +591,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, + Cmd::Mods { action } => mods(action.unwrap_or(ModsCmd::List), as_json)?, Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } @@ -821,6 +890,148 @@ fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn mods(action: ModsCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::browser::{installed, Kind, Query}; + use horizon_launcher::modpacks; + let home = backend::game_home(); + let entry_json = |e: &installed::Entry| serde_json::to_value(e).unwrap_or_default(); + let line = |label: &str, f: f32| progress(label.to_string())(f); + match action { + ModsCmd::List => { + let list = installed::Installed::load(&home).entries; + if as_json { + json(list.iter().map(entry_json).collect()); + } else if list.is_empty() { + println!( + "Nothing installed from the browser yet: horizon-launcher mods search " + ); + } + for e in list.iter().filter(|_| !as_json) { + println!( + "{} {} ({}, {})\n {} {}", + e.title, + e.number, + e.source.label(), + e.slug, + e.file, + e.checksum + ); + } + } + ModsCmd::Search { + text, + kind, + everything, + source, + } => { + let kind = match kind { + KindArg::Resource => Kind::ResourcePack, + KindArg::Shader => Kind::ShaderPack, + KindArg::Modpack => Kind::Modpack, + }; + let query = Query { + everything, + ..Query::new(&text.join(" "), kind) + }; + let found = source.get()?.search(&query)?; + if as_json { + json(found.iter().map(|p| { + let support = p.support(); + serde_json::json!({ + "id": p.id, "slug": p.slug, "title": p.title, "summary": p.summary, + "author": p.author, "downloads": p.downloads, "page": p.page, + "license": p.license, "support": support.label(), "reason": support.reason(), + }) + }).collect()); + } else { + for p in &found { + let support = p.support(); + println!( + "{} ({}) {} · {} downloads\n {}", + p.title, + p.slug, + support.label(), + p.downloads, + p.summary + ); + if let Some(why) = support.reason() { + println!(" {why}"); + } + } + } + } + ModsCmd::Install { + project, + everything, + source, + } => { + let source = source.get()?; + let p = source.project(&project)?; + if p.kind == Kind::Modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = + installed::fetch_modpack(&*source, &p, &folder, &progress(p.title.clone()))?; + let log = &|line: String| eprintln!("{line}"); + let pack = modpacks::import(&file, log)?; + println!( + "Imported {} ({}): horizon-launcher modpack port {}", + pack.title(), + pack.summary(), + pack.slug + ); + return Ok(()); + } + let done = installed::install(&*source, &p, everything, &home, &line)?; + if as_json { + json(done.iter().map(entry_json).collect()); + } + for e in done.iter().filter(|_| !as_json) { + println!("{} {}: {} ({})", e.title, e.number, e.file, e.checksum); + } + } + ModsCmd::Update { project, check } => { + let list = installed::Installed::load(&home).entries; + let chosen: Vec<_> = list + .iter() + .filter(|e| { + project + .as_deref() + .is_none_or(|n| e.project == n || e.slug == n) + }) + .collect(); + if chosen.is_empty() { + return Err(match project { + Some(n) => format!("{n} wasn't installed by the browser."), + None => "Nothing installed from the browser yet.".into(), + }); + } + for e in chosen { + let Some(source) = horizon_launcher::browser::source(e.source) else { + println!("{}: {} isn't available here.", e.title, e.source.label()); + continue; + }; + match installed::update_for(&*source, e)? { + None => println!("{} {}: up to date.", e.title, e.number), + Some(v) if check => { + println!("{} {}: {} is available.", e.title, e.number, v.number) + } + Some(_) => { + let p = source.project(&e.project)?; + for done in installed::install(&*source, &p, true, &home, &line)? { + println!("{} {}: {}", done.title, done.number, done.file); + } + } + } + } + } + ModsCmd::Remove { project } => { + let e = installed::remove(&home, &project)?; + println!("Removed {} ({}).", e.title, e.file); + } + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::modpacks::{self, Imported}; use horizon_port_pack::report::Status; From cf96b7c0970562273625824a1e581a6b57c6ab1d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:27:33 +0200 Subject: [PATCH 041/115] Mod browser (3/3): the launcher's Mods page A Mods page between Versions and Modpacks: resource packs, shader packs and modpacks as tabs, a search field, Show everything, and Modrinth / CurseForge once CurseForge has a key. Results are index rows with summary, author, downloads, source, licence and how well each runs (with the reason), Page and Install (Import for a modpack, which then shows on the Modpacks page). Installed packs list their version, source, file and the checksum they were checked against, with Update and Remove. Searches, installs and update checks run on threads; stale search answers are dropped. Fixes #577 Co-Authored-By: Claude Opus 5.5 --- docs/mod-browser.md | 9 + launcher/README.md | 6 + launcher/src/main.rs | 11 +- launcher/src/mods_page.rs | 675 +++++++++++++++++++++++++++++++++++ launcher/src/servers_page.rs | 4 +- 5 files changed, 702 insertions(+), 3 deletions(-) create mode 100644 launcher/src/mods_page.rs diff --git a/docs/mod-browser.md b/docs/mod-browser.md index b7a9176c5..115877075 100644 --- a/docs/mod-browser.md +++ b/docs/mod-browser.md @@ -30,6 +30,15 @@ never offered for install. else removes the part file and installs nothing. - A file whose source lists no checksum is refused. +## The Mods page + +The launcher's **Mods** page has the three kinds as tabs, a search field (Enter searches), **Show everything** and, +once CurseForge is set up, a Modrinth / CurseForge switch. Each result is an index row: its summary, author, +downloads, source and licence, how well it runs (and why), **Page** (the project's page on its source) and +**Install** (**Import** for a modpack). Installed packs are listed above the results with their version, source, +file and the checksum they were checked against, with **Update to …** when a newer version runs and **Remove** +(asked twice). + ## Installing, updating, removing `mod-browser.json` beside `options.txt` lists every file the browser installed: its source, project, version, file diff --git a/launcher/README.md b/launcher/README.md index e95d72649..74054ea55 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -24,6 +24,12 @@ The opening, then Play ([clip](docs/opening.webm)): preparation reuses checksum-verified game jars and libraries from the current or another installed Horizon version, so the original Minecraft install is only required when no valid imported copy exists. +- **Mods**: search Modrinth (and CurseForge once the launcher has its API key) for resource + packs, Iris/OptiFine shader packs and modpacks, each marked Works, Partly or Doesn't run in + Horizon; Java mod jars are never offered. Install puts a pack and what it needs in + `resourcepacks/` or `shaderpacks/` only after its SHA-512 (SHA-1 on CurseForge) matches, and a + modpack goes to the Modpacks page; installed packs show their source and checksum, with Update + and Remove ([docs/mod-browser.md](../docs/mod-browser.md)). - **Modpacks**: import a Java modpack (a Modrinth `.mrpack`, a CurseForge zip, or a Prism, MultiMC or CurseForge instance folder) and see its coverage report: per mod, ported, partial, not yet or not needed, with the reason ([docs/modpacks.md](../docs/modpacks.md)). **Port** diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 3b2d0f32b..41bce0489 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -8,6 +8,7 @@ mod internet; mod markdown; mod mcp; mod modpacks_page; +mod mods_page; mod perf; mod scrollbar; mod servers_page; @@ -35,6 +36,7 @@ use theme::Theme; enum Page { Play, Versions, + Mods, Modpacks, Servers, Notes, @@ -42,9 +44,10 @@ enum Page { } impl Page { - const ALL: [(Page, &'static str); 6] = [ + const ALL: [(Page, &'static str); 7] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), + (Page::Mods, "Mods"), (Page::Modpacks, "Modpacks"), (Page::Servers, "Servers"), (Page::Notes, "Patch notes"), @@ -181,6 +184,8 @@ struct Launcher { pack_error: Option, /// The game starting now plays this pack's profile (its work folder). starting_pack: Option, + /// The Mods page: the browser's search, installs and updates (`mods_page.rs`). + mods: mods_page::Mods, } impl Launcher { @@ -291,6 +296,7 @@ impl Launcher { pack_log: VecDeque::new(), pack_error: None, starting_pack: None, + mods: mods_page::Mods::new(cx), }; if this.bench.is_some() { this.perf.keep_local_log(false); @@ -595,6 +601,7 @@ impl Launcher { } } changed |= self.servers_tick(); + changed |= self.mods_tick(); if let Some(sign_in) = &self.sign_in { let state = sign_in.state(); let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); @@ -2687,10 +2694,12 @@ impl Render for Launcher { self.perf.frame(); self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); + self.mods.note_focus(window); self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), + Page::Mods => self.mods_page(cx), Page::Modpacks => self.modpacks_page(cx), Page::Servers => self.servers_page(cx), Page::Notes => self.notes_page(cx), diff --git a/launcher/src/mods_page.rs b/launcher/src/mods_page.rs new file mode 100644 index 000000000..25a825c93 --- /dev/null +++ b/launcher/src/mods_page.rs @@ -0,0 +1,675 @@ +//! The Mods page: search Modrinth (and CurseForge with a key) for resource packs, shader packs +//! and modpacks Horizon loads, see where each comes from and how well it runs, install it with +//! its checksum checked, and update or remove what was installed (`horizon_launcher::browser`). +use super::servers_page::{type_key, Key}; +use super::*; +use horizon_launcher::browser::{ + self, curseforge::CurseForge, installed, Kind as PackKind, Project, Query, SourceId, Support, +}; +use horizon_launcher::modpacks; +use std::collections::HashMap; + +const KINDS: [(PackKind, &str); 3] = [ + (PackKind::ResourcePack, "Resource packs"), + (PackKind::ShaderPack, "Shader packs"), + (PackKind::Modpack, "Modpacks"), +]; +const SOURCES: [(SourceId, &str); 2] = [ + (SourceId::Modrinth, "Modrinth"), + (SourceId::CurseForge, "CurseForge"), +]; +const PAGE: usize = 20; + +pub(super) enum Event { + /// A search's answer, for the search it was (stale answers are dropped) at that offset. + Found(u64, usize, Result, String>), + Progress(String, f32), + Done(Result, bool), + Updates(HashMap<(SourceId, String), String>), +} + +pub(super) struct Mods { + kind: PackKind, + source: SourceId, + curseforge: bool, + text: String, + focus: FocusHandle, + pub(super) focused: bool, + everything: bool, + /// Which search is the current one; answers for older ones are dropped. + search: u64, + searching: bool, + searched: bool, + results: Vec, + more: bool, + error: Option, + installed: Vec, + loaded: bool, + /// The project being installed, and the line and fraction of its download. + busy: Option<(String, String, f32)>, + message: Option>, + updates: HashMap<(SourceId, String), String>, + confirm_remove: Option, + tx: Sender, + rx: Receiver, +} + +impl Mods { + pub(super) fn new(cx: &mut App) -> Self { + let (tx, rx) = channel(); + Self { + kind: PackKind::ResourcePack, + source: SourceId::Modrinth, + curseforge: CurseForge::from_env().is_some(), + text: String::new(), + focus: cx.focus_handle().tab_index(0).tab_stop(true), + focused: false, + everything: false, + search: 0, + searching: false, + searched: false, + results: Vec::new(), + more: false, + error: None, + installed: Vec::new(), + loaded: false, + busy: None, + message: None, + updates: HashMap::new(), + confirm_remove: None, + tx, + rx, + } + } + + pub(super) fn note_focus(&mut self, window: &Window) { + self.focused = self.focus.is_focused(window); + } + + fn entry(&self, p: &Project) -> Option<&installed::Entry> { + self.installed + .iter() + .find(|e| e.source == p.source && e.project == p.id) + } +} + +/// `51404735` → `51.4M`. +fn count(n: u64) -> String { + match n { + 0..1_000 => n.to_string(), + 1_000..1_000_000 => format!("{:.1}k", n as f64 / 1e3), + _ => format!("{:.1}M", n as f64 / 1e6), + } +} + +/// A checksum as the page shows it: the algorithm and the first and last hex digits. +fn short_sum(checksum: &str) -> String { + let (algo, hex) = checksum.split_once(':').unwrap_or(("", checksum)); + if hex.len() <= 20 { + return checksum.to_string(); + } + format!("{algo} {}…{}", &hex[..12], &hex[hex.len() - 8..]) +} + +impl Launcher { + /// Called with the launcher's other work: what the background sent. + pub(super) fn mods_tick(&mut self) -> bool { + let mut changed = false; + while let Ok(event) = self.mods.rx.try_recv() { + changed = true; + let m = &mut self.mods; + match event { + Event::Found(search, offset, result) if search == m.search => { + m.searching = false; + m.searched = true; + match result { + Ok(found) => { + m.more = found.len() == PAGE; + m.results.truncate(offset); + m.results.extend(found); + m.error = None; + } + Err(e) => m.error = Some(e), + } + } + Event::Found(..) => {} + Event::Progress(line, f) => { + if let Some(busy) = &mut m.busy { + busy.1 = line; + busy.2 = f; + } + } + Event::Done(result, modpack) => { + m.busy = None; + m.message = Some(result); + m.installed = installed::Installed::load(&backend::game_home()).entries; + if modpack { + // The Modpacks page reads its list again. + self.packs_loaded = None; + } + } + Event::Updates(found) => m.updates = found, + } + } + changed + } + + fn mods_search(&mut self, offset: usize) { + let m = &mut self.mods; + m.search += 1; + m.searching = true; + if offset == 0 { + m.results.clear(); + m.more = false; + } + let query = Query { + everything: m.everything, + offset, + limit: PAGE, + ..Query::new(&m.text, m.kind) + }; + let (tx, search, source) = (m.tx.clone(), m.search, m.source); + std::thread::spawn(move || { + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|s| s.search(&query)); + let _ = tx.send(Event::Found(search, offset, result)); + }); + } + + /// Looks for newer versions of what the browser installed. + fn mods_check_updates(&mut self) { + let entries = self.mods.installed.clone(); + if entries.is_empty() { + return; + } + let tx = self.mods.tx.clone(); + std::thread::spawn(move || { + let mut found = HashMap::new(); + for e in entries { + let Some(source) = browser::source(e.source) else { + continue; + }; + if let Ok(Some(v)) = installed::update_for(&*source, &e) { + found.insert((e.source, e.project.clone()), v.number); + } + } + let _ = tx.send(Event::Updates(found)); + }); + } + + /// Installs (or updates) a project on a thread: a pack into its folder, a modpack into + /// Modpacks. `known` is the project when the page has it; else it is asked for first. + fn mods_install(&mut self, source: SourceId, id: String, known: Option) { + if self.mods.busy.is_some() { + return; + } + self.mods.message = None; + self.mods.busy = Some((id.clone(), format!("Asking {}…", source.label()), 0.)); + self.mods.updates.remove(&(source, id.clone())); + let (tx, everything) = (self.mods.tx.clone(), self.mods.everything); + std::thread::spawn(move || { + let last = std::cell::Cell::new(-1); + let progress = |line: &str, f: f32| { + let pct = (f * 100.) as i32; + if last.replace(pct) != pct { + let _ = tx.send(Event::Progress(line.to_string(), f)); + } + }; + let mut modpack = false; + let result = browser::source(source) + .ok_or_else(|| format!("{} isn't set up.", source.label())) + .and_then(|source| { + let p = match known { + Some(p) => p, + None => source.project(&id)?, + }; + modpack = p.kind == PackKind::Modpack; + if modpack { + let folder = modpacks::ports_dir().join("downloads"); + let file = installed::fetch_modpack(&*source, &p, &folder, &|f| { + progress(&p.title, f) + })?; + let log = |line: String| progress(&line, 1.); + let pack = modpacks::import(&file, &log)?; + return Ok(format!( + "{} is imported: open it on the Modpacks page to port it.", + pack.title() + )); + } + let home = backend::game_home(); + let done = installed::install(&*source, &p, everything, &home, &progress)?; + let names: Vec = done + .iter() + .map(|e| format!("{} {}", e.title, e.number)) + .collect(); + let turn_on = match p.kind { + PackKind::ShaderPack => "Video Settings > Shader Packs", + _ => "Options > Resource Packs", + }; + Ok(format!( + "Installed {}, checksums checked. Turn it on in the game: {turn_on}.", + names.join(", ") + )) + }); + let _ = tx.send(Event::Done(result, modpack)); + }); + } + + fn mods_field(&mut self, cx: &mut Context) -> Stateful
{ + let t = self.theme; + let m = &self.mods; + let focused = m.focused; + let shown: String = { + let chars: Vec = m.text.chars().collect(); + chars[chars.len().saturating_sub(40)..].iter().collect() + }; + div() + .id("mods-search") + .track_focus(&m.focus) + .flex() + .items_center() + .w(px(320.)) + .h(px(theme::FIELD)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(theme::RADIUS)) + .border_1() + .border_color(if focused { t.accent } else { t.rule }) + .bg(t.surface) + .text_size(px(theme::UI.px)) + .cursor_text() + .child(if m.text.is_empty() && !focused { + div().text_color(t.muted).child("Search, then Enter") + } else { + div().text_color(t.ink).child(shown) + }) + .when(focused, |d| { + d.child(div().flex_none().w(px(1.)).h(px(16.)).bg(t.ink)) + }) + .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { + window.focus(&this.mods.focus); + cx.notify(); + })) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + let command = k.modifiers.control || k.modifiers.platform; + match type_key( + &mut this.mods.text, + false, + &k.key, + k.key_char.as_deref(), + command, + ) { + Key::Enter => this.mods_search(0), + Key::Escape => window.blur(), + Key::Paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + let line = text.lines().next().unwrap_or_default().trim().to_string(); + this.mods.text.push_str(&line); + } + } + Key::Edited => {} + Key::Pass => return, + } + if let Some((at, _)) = this.mods.text.char_indices().nth(100) { + this.mods.text.truncate(at); + } + cx.stop_propagation(); + cx.notify(); + })) + } + + pub(super) fn mods_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if !self.mods.loaded { + self.mods.loaded = true; + self.mods.installed = installed::Installed::load(&backend::game_home()).entries; + self.mods_check_updates(); + self.mods_search(0); + } + let header = page_header( + "Mods", + "Resource packs, shader packs and modpacks that Horizon loads. Each file is checked \ + against its source's checksum before it reaches your game folder.", + &t, + ); + let this = cx.entity().downgrade(); + let kinds = segments("mods-kind", &KINDS, self.mods.kind, &t, { + let this = this.clone(); + move |kind, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.kind != kind { + this.mods.kind = kind; + this.mods_search(0); + } + cx.notify(); + }); + } + }); + let everything = self.mods.everything; + let toggle = div() + .id("mods-everything") + .flex() + .items_center() + .gap(px(8.)) + .cursor_pointer() + .child(switch("mods-everything-switch", everything, &t)) + .child( + text(theme::LABEL) + .text_color(t.ink_soft) + .child("Show everything"), + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.mods.everything = !this.mods.everything; + this.mods_search(0); + cx.notify(); + })); + let source_note = if self.mods.curseforge { + segments("mods-source", &SOURCES, self.mods.source, &t, { + let this = this.clone(); + move |source, _, cx| { + let _ = this.update(cx, |this, cx| { + if this.mods.source != source { + this.mods.source = source; + this.mods_search(0); + } + cx.notify(); + }); + } + }) + .into_any_element() + } else { + text(theme::CAPTION) + .text_color(t.muted) + .child("From Modrinth. CurseForge comes once the launcher has its API key.") + .into_any_element() + }; + let controls = div() + .flex() + .flex_col() + .gap(px(12.)) + .child( + div() + .flex() + .flex_wrap() + .items_center() + .gap(px(12.)) + .child(kinds) + .child(self.mods_field(cx)) + .child(toggle), + ) + .child(source_note); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(controls); + if let Some((_, line, f)) = &self.mods.busy { + page = page.child( + plate(&t) + .flex() + .flex_col() + .gap(px(8.)) + .p(px(16.)) + .child(caps("Installing").text_color(t.accent)) + .child( + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink_soft) + .truncate() + .child(format!("{line} {:.0}%", f * 100.)), + ), + ); + } + match &self.mods.message { + Some(Ok(done)) => { + page = page.child( + plate(&t) + .p(px(16.)) + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(done.clone()), + ) + } + Some(Err(e)) => page = page.child(notice(e.clone(), &t)), + None => {} + } + if let Some(list) = self.mods_installed_list(cx) { + page = page.child(list); + } + page.child(self.mods_results(cx)) + } + + fn mods_installed_list(&self, cx: &mut Context) -> Option
{ + let t = self.theme; + let kind = self.mods.kind; + let entries: Vec<&installed::Entry> = self + .mods + .installed + .iter() + .filter(|e| e.kind == kind) + .collect(); + if entries.is_empty() { + return None; + } + let busy = self.mods.busy.is_some(); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, e) in entries.into_iter().enumerate() { + let key = (e.source, e.project.clone()); + let mut right = div().flex().items_center().gap(px(8.)); + if let Some(number) = self.mods.updates.get(&key) { + let mut update = button( + SharedString::from(format!("mods-update-{}", e.project)), + format!("Update to {number}"), + Kind::Secondary, + &t, + ); + if busy { + update = disabled(update); + } else { + let (source, id) = key.clone(); + update = update.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(source, id.clone(), None); + cx.notify(); + })); + } + right = right.child(update); + } + let confirming = self.mods.confirm_remove.as_deref() == Some(e.project.as_str()); + let id = e.project.clone(); + let remove = button( + SharedString::from(format!("mods-remove-{}", e.project)), + if confirming { + "Remove for good" + } else { + "Remove" + }, + if confirming { + Kind::Secondary + } else { + Kind::Ghost + }, + &t, + ) + .when(confirming, |b| b.text_color(t.danger)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.mods.confirm_remove.as_ref() == Some(&id) { + let home = backend::game_home(); + this.mods.message = Some( + installed::remove(&home, &id).map(|e| format!("Removed {}.", e.title)), + ); + this.mods.installed = installed::Installed::load(&home).entries; + this.mods.confirm_remove = None; + } else { + this.mods.confirm_remove = Some(id.clone()); + } + cx.notify(); + })); + right = right.child(remove); + let detail = div() + .flex() + .flex_col() + .child(format!( + "{} · from {}{} · {}", + e.number, + e.source.label(), + if e.dependency { + ", needed by another pack" + } else { + "" + }, + e.file + )) + .child( + div() + .font_family(theme::MONO) + .child(format!("checked: {}", short_sum(&e.checksum))), + ); + list = list.child(index_row( + i + 1, + e.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + Some( + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(caps("Installed").text_color(t.muted)) + .child(list), + ) + } + + fn mods_results(&self, cx: &mut Context) -> Div { + let t = self.theme; + let m = &self.mods; + if let Some(e) = &m.error { + return div().child(notice(e.clone(), &t)); + } + if m.results.is_empty() { + let line = if m.searching || !m.searched { + "Searching…" + } else if m.everything { + "Nothing found." + } else { + "Nothing found that runs in Horizon. Show everything lists the rest." + }; + return centered(line, &t); + } + let busy = m.busy.as_ref().map(|b| b.0.as_str()); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in m.results.iter().enumerate() { + let support = p.support(); + let color = match support { + Support::Works => t.success, + Support::Partial(_) => t.accent, + Support::No(_) => t.muted, + }; + let mut right = div() + .flex() + .items_center() + .gap(px(8.)) + .child(caps(support.label()).flex_none().text_color(color)); + let page_url = p.page.clone(); + if !page_url.is_empty() { + right = right.child( + button( + SharedString::from(format!("mods-page-{}", p.id)), + "Page", + Kind::Ghost, + &t, + ) + .on_click(move |_, _, cx| cx.open_url(&page_url)), + ); + } + if busy == Some(p.id.as_str()) { + right = right.child(caps("Installing").text_color(t.accent)); + } else if m.entry(p).is_some() { + right = right.child(caps("Installed").text_color(t.muted)); + } else if support.installable() { + let label = if p.kind == PackKind::Modpack { + "Import" + } else { + "Install" + }; + let mut install = button( + SharedString::from(format!("mods-install-{}", p.id)), + label, + Kind::Secondary, + &t, + ); + if busy.is_some() { + install = disabled(install); + } else { + let p = p.clone(); + install = install.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_install(p.source, p.id.clone(), Some(p.clone())); + cx.notify(); + })); + } + right = right.child(install); + } + let mut by = Vec::new(); + if !p.author.is_empty() { + by.push(format!("by {}", p.author)); + } + by.push(format!("{} downloads", count(p.downloads))); + by.push(format!("from {}", p.source.label())); + if !p.license.is_empty() { + by.push(p.license.clone()); + } + let detail = div() + .flex() + .flex_col() + .child(div().truncate().child(p.summary.clone())) + .child(by.join(" · ")) + .children( + support + .reason() + .map(|r| div().text_color(t.ink_soft).child(r.to_string())), + ); + list = list.child(index_row( + i + 1, + p.title.clone(), + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + let mut out = div().flex().flex_col().child(list); + if m.more { + let mut more = button("mods-more", "More", Kind::Ghost, &t); + if m.searching { + more = disabled(more); + } else { + let offset = m.results.len(); + more = more.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mods_search(offset); + cx.notify(); + })); + } + out = out.child(div().flex().pt(px(16.)).child(more)); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counts_and_checksums_read_short() { + assert_eq!(count(999), "999"); + assert_eq!(count(1_500), "1.5k"); + assert_eq!(count(51_404_735), "51.4M"); + let sum = format!("SHA-512:{}", "ab".repeat(64)); + assert_eq!(short_sum(&sum), "SHA-512 abababababab…abababab"); + assert_eq!(short_sum("SHA-1:abcd"), "SHA-1:abcd"); + } +} diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs index 625b6ffab..b1338f1aa 100644 --- a/launcher/src/servers_page.rs +++ b/launcher/src/servers_page.rs @@ -291,7 +291,7 @@ fn bytes(n: u64) -> String { /// A backup's date and kind from its name (`2026-10-19_11-28-57-manual.zip`, UTC), for people. /// What a key did in a one-line field. #[derive(Debug, PartialEq)] -enum Key { +pub(super) enum Key { Enter, Escape, /// Command/Ctrl-V: the caller pastes the clipboard's first line. @@ -303,7 +303,7 @@ enum Key { /// Types `key` into `text`. A `selected` suggestion is replaced by what's typed or pasted, and /// cleared by Backspace. -fn type_key( +pub(super) fn type_key( text: &mut String, selected: bool, key: &str, From 21998a7e6ac1ca57b937a849d51ef67b0a87141f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 02:45:32 +0200 Subject: [PATCH 042/115] Shader packs: read pack sources as Iris's JCPP does; legalise what naga refuses Preprocessor (GLSL and shaders.properties), as JCPP does: - a #define replaces an earlier macro (Bloop, Steadfast: DefineRedefined); - in #if, a float counts as its integer part (Steadfast's shaders.properties float token), and a macro always defined empty counts as 0 (Iris's MC_GL_VENDOR_OTHER, Bloop's TAA_USE_YCOCG); - an #if may run to the end of the input (Bloop's taa.fsh); - #error "..." lexes in skipped blocks (Photon); - shaders.properties keeps its empty lines and hides backslashes from the preprocessor (IRIS_PASSTHROUGHBACKSLASH), so a continued value no longer swallows the next directive or line (Photon, Bliss, Steadfast's custom uniforms; Complementary's isCold uniform is now complete). Legaliser: % through overloads (naga won't take ivec2 % int: Noble), sqrt of a negative constant left to the GPU (Bloop's NaN), constants naga can't fold (?:, mix: Bliss) become globals set in main, and 16/8-bit types (u16vec2 & co., Noble on NVIDIA) become their 32-bit ones. horizon-client: real_packs_load runs the game's own load over the packs in HORIZON_TEST_SHADERPACKS (the compatibility table's source). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/java_pack.rs | 39 +++ crates/horizon-shaderpack/src/preprocess.rs | 180 ++++++++++++- crates/horizon-shaderpack/src/properties.rs | 68 ++++- crates/horizon-shaderpack/src/translate.rs | 252 ++++++++++++++++++- crates/horizon-shaderpack/tests/pack.rs | 63 +++++ crates/horizon-shaderpack/tests/translate.rs | 41 +++ 6 files changed, 629 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index fb170d152..a5bc2904e 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -179,4 +179,43 @@ mod tests { ); assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple"); } + + /// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the + /// game loads them, with their default options: the compatibility table + /// of docs/shader-packs.md. Skipped when the variable isn't set. + #[test] + fn real_packs_load() { + let Some(dir) = std::env::var_os("HORIZON_TEST_SHADERPACKS") else { + return; + }; + let mut entries: Vec<_> = std::fs::read_dir(dir) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| is_java_pack(p)) + .collect(); + entries.sort(); + let mut failures = Vec::new(); + for path in entries { + let name = path.file_name().unwrap().to_string_lossy().into_owned(); + match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") { + Ok(pack) => { + let folders: Vec = pack + .folders + .iter() + .map(|f| { + let n = f.passes.len() + usize::from(f.final_pass.is_some()); + format!("{} {n} passes", f.folder) + }) + .collect(); + println!("{name}: loads ({})", folders.join(", ")); + } + Err(e) => { + println!("{name}: {e}"); + failures.push(name); + } + } + } + assert!(failures.is_empty(), "{failures:?}"); + } } diff --git a/crates/horizon-shaderpack/src/preprocess.rs b/crates/horizon-shaderpack/src/preprocess.rs index 18c890496..8a0c4e694 100644 --- a/crates/horizon-shaderpack/src/preprocess.rs +++ b/crates/horizon-shaderpack/src/preprocess.rs @@ -6,8 +6,9 @@ use crate::include::Inlined; use pp_rs::{ pp::Preprocessor, - token::{Punct, TokenValue}, + token::{PreprocessorError, Punct, TokenValue}, }; +use std::collections::HashMap; /// The version of Minecraft packs are told they run on (`MC_VERSION`, /// Iris's `formatVersionString("26.3")`). @@ -286,14 +287,176 @@ fn mark_comments(text: &str) -> (String, Vec) { (out, comments) } +/// Whether trimmed `line` is an `#if` or `#elif` directive. +pub(crate) fn is_condition(line: &str) -> bool { + line.strip_prefix('#') + .map(str::trim_start) + .and_then(|d| d.strip_prefix("elif").or_else(|| d.strip_prefix("if"))) + .is_some_and(|r| !r.starts_with(|c: char| c.is_ascii_alphanumeric() || c == '_')) +} + +/// Whether `word` is a float literal. +pub(crate) fn is_float(word: &str) -> bool { + word.starts_with(|c: char| c.is_ascii_digit() || c == '.') + && !word.starts_with("0x") + && !word.starts_with("0X") + && word.contains(['.', 'e', 'E']) +} + +/// What JCPP's `#if` makes of a number (`Preprocessor.expr` takes +/// `NumericValue.longValue`): a float counts as its integer part, so +/// `0.75` is 0 and `1.5e1` is 10. `None` for a non-number. +pub(crate) fn jcpp_integer(number: &str) -> Option { + let number = number.trim_end_matches(['f', 'F', 'l', 'L', 'u', 'U']); + let (mantissa, exponent) = match number.find(['e', 'E']) { + Some(i) => (&number[..i], number[i + 1..].parse::().ok()?), + None => (number, 0), + }; + let integer = mantissa.split('.').next()?; + let value = if integer.is_empty() { + 0 + } else { + integer.parse::().ok()? + }; + Some((value as f64 * 10f64.powi(exponent)) as i64) +} + +/// `line` with each word (identifier or number, with an exponent's sign: +/// `1e-3`) replaced by what `f` returns for it, if anything. The directive's +/// name and the names after `defined` are kept. +pub(crate) fn rewrite_condition(line: &str, f: impl Fn(&str) -> Option) -> String { + let mut out = String::with_capacity(line.len()); + let (mut rest, mut first, mut after_defined) = (line, true, false); + while let Some(c) = rest.chars().next() { + if !(c.is_ascii_alphanumeric() || c == '_' || c == '.') { + if !c.is_whitespace() && c != '(' && c != '#' { + after_defined = false; + } + out.push(c); + rest = &rest[c.len_utf8()..]; + continue; + } + let bytes = rest.as_bytes(); + let mut len = 0; + while let Some(&b) = bytes.get(len) { + let sign = (b == b'+' || b == b'-') + && bytes[0].is_ascii_digit() + && matches!(bytes[len - 1], b'e' | b'E'); + if !(b.is_ascii_alphanumeric() || b == b'_' || b == b'.' || sign) { + break; + } + len += 1; + } + let word = &rest[..len]; + let kept = first || after_defined; + match (!kept).then(|| f(word)).flatten() { + Some(replacement) => out.push_str(&replacement), + None => out.push_str(word), + } + after_defined = word == "defined"; + first = false; + rest = &rest[len..]; + } + out +} + +/// Make pp-rs read `text` as JCPP, Iris's preprocessor, does: +/// - a `#define` replaces an earlier macro (`Preprocessor.addMacro`; Bloop +/// and Steadfast redefine theirs), where pp-rs refuses a different +/// redefinition: an `#undef` line goes before every `#define`; +/// - in `#if`/`#elif`, a float counts as its integer part, and so does a +/// macro always defined as the same float (an option: `#define LEVEL 0.5`); +/// a macro always defined empty (Iris's `MC_GL_VENDOR_OTHER`, Bloop's +/// `#define TAA_USE_YCOCG`) counts as 0: JCPP reports the missing operand +/// and goes on with 0. pp-rs stops on both; +/// - `#error "..."` (Photon's guard in programs it disables) lexes: pp-rs +/// has no string tokens and fails on the quote, even in a skipped block. +/// +/// Returns the text and the added lines' 1-based numbers in it. +fn jcpp_compatible(text: &str, env: &Environment) -> (String, Vec) { + // A `#define` line's name and body. + let define = |l: &str| { + let rest = l + .trim_start() + .strip_prefix('#')? + .trim_start() + .strip_prefix("define") + .filter(|rest| rest.starts_with([' ', '\t']))? + .trim_start(); + let end = rest + .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()); + let (name, body) = rest.split_at(end); + let body = body.split("//").next().unwrap_or("").trim(); + (!name.is_empty()).then(|| (name.to_owned(), body.to_owned())) + }; + // Each macro's body, if every definition has the same one. + let mut bodies: HashMap> = HashMap::new(); + let definitions = env + .defines + .iter() + .cloned() + .chain(text.lines().filter_map(define)); + for (name, body) in definitions { + bodies + .entry(name) + .and_modify(|b| { + if b.as_ref() != Some(&body) { + *b = None; + } + }) + .or_insert(Some(body)); + } + let number = |word: &str| -> Option { + let word = match bodies.get(word) { + Some(Some(body)) if body.is_empty() => return Some("0".into()), + Some(Some(body)) => body.as_str(), + Some(None) => return None, + None => word, + }; + is_float(word) + .then(|| jcpp_integer(word)) + .flatten() + .map(|n| n.to_string()) + }; + let mut out = String::with_capacity(text.len() + text.len() / 16); + let mut added = Vec::new(); + let (mut line, mut continued) = (1, false); + for l in text.split_inclusive('\n') { + if !continued && let Some((name, _)) = define(l) { + out.push_str(&format!("#undef {name}\n")); + added.push(line); + line += 1; + } + let directive = l.trim_start().strip_prefix('#').map(str::trim_start); + if !continued + && directive.is_some_and(|d| d.starts_with("error") || d.starts_with("warning")) + { + out.push_str(&l.replace(['"', '\''], "")); + } else if !continued && is_condition(l.trim_start()) { + out.push_str(&rewrite_condition(l, number)); + } else { + out.push_str(l); + } + continued = l.trim_end().ends_with('\\'); + line += 1; + } + (out, added) +} + /// Expand `source` with `env`'s macros. Errors name the file and line. pub fn preprocess(source: &Inlined, env: &Environment) -> Result { let (marked, comments) = mark_comments(&source.text); - let text = &marked; + let (text, added) = jcpp_compatible(&marked, env); + let text = &text; let line_starts: Vec = std::iter::once(0) .chain(text.match_indices('\n').map(|(i, _)| i + 1)) .collect(); - let line_of = |offset: u32| line_starts.partition_point(|&s| s <= offset as usize) as u32; + // Lines of the source: the added `#undef` lines don't count. + let line_of = |offset: u32| { + let line = line_starts.partition_point(|&s| s <= offset as usize) as u32; + line - added.partition_point(|&a| a < line) as u32 + }; let mut pp = Preprocessor::new(text); for (name, value) in &env.defines { pp.add_define(name, value) @@ -307,8 +470,15 @@ pub fn preprocess(source: &Inlined, env: &Environment) -> Result break, + item => { + item.map_err(|(e, at)| format!("{}: {e:?}", source.locate(line_of(at.start))))? + } + }; let at = line_of(token.location.start); let piece = match token.value { TokenValue::Version(v) => { diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 8c3f29c8f..3c6ee251c 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -6,7 +6,7 @@ //! so `#if` blocks pick the directives that apply. use crate::options::{OptionSet, OptionValues}; -use crate::preprocess::Environment; +use crate::preprocess::{Environment, is_condition, is_float, jcpp_integer, rewrite_condition}; use pp_rs::{pp::Preprocessor, token::TokenValue}; use std::collections::BTreeMap; @@ -120,9 +120,32 @@ const DIRECTIVES: &[&str] = &[ "#warning", "#pragma", "#line", "#include", ]; +/// An `#if`/`#elif` line with its floats as JCPP reads them (Steadfast tests +/// `#if ATMOSPHERE_FOG_STRENGTH_NOON == 0.75` with the option at 0.5, which +/// Iris reads as `0 == 0`): float literals and the options set to a float +/// become their integer part. +fn jcpp_condition(line: &str, options: &OptionSet, values: &OptionValues) -> String { + rewrite_condition(line, |word| { + let value = match options.strings.get(word) { + Some(o) => values.strings.get(word).unwrap_or(&o.default).as_str(), + None => word, + }; + is_float(value) + .then(|| jcpp_integer(value)) + .flatten() + .map(|n| n.to_string()) + }) +} + +/// What backslashes are while the macros expand, as in Iris: the +/// preprocessor must not join a `\`-continued value with the directive on +/// the next line (Photon ends an `#if`'d value with `) \` before `#else`). +const BACKSLASH: &str = "IRIS_PASSTHROUGHBACKSLASH"; + /// `PropertiesPreprocessor.preprocessSource`: comment lines dropped, other -/// `#`s removed, then the macros expanded. Tokens keep their source spelling -/// and spacing (`0.50` stays `0.50`, `` stays one word). +/// `#`s removed, then the macros expanded with the backslashes hidden. +/// Tokens keep their source spelling and spacing (`0.50` stays `0.50`, +/// `` stays one word). pub fn preprocess( text: &str, env: &Environment, @@ -132,7 +155,6 @@ pub fn preprocess( let filtered: String = text .lines() .map(str::trim) - .filter(|l| !l.is_empty()) .map(|l| match l.starts_with('#') { // JCPP lets a #define replace a macro (Complementary sets // COLORED_LIGHTING 0 on macOS); pp-rs refuses, so undefine first. @@ -142,11 +164,12 @@ pub fn preprocess( None => l.to_owned(), } } + true if is_condition(l) => jcpp_condition(l, options, values), true if DIRECTIVES.iter().any(|d| l.starts_with(d)) => l.to_owned(), true => String::new(), false => l.replace('#', ""), }) - .map(|l| l + "\n") + .map(|l| l.replace('\\', BACKSLASH) + "\n") .collect(); let mut pp = Preprocessor::new(&filtered); let mut define = |name: &str, value: &str| { @@ -202,7 +225,7 @@ pub fn preprocess( }); } out.push('\n'); - Ok(out) + Ok(out.replace(BACKSLASH, "\\")) } /// One element of an option screen (`OptionMenuElement`). @@ -698,6 +721,39 @@ mod tests { ); } + #[test] + fn floats_in_conditions_count_as_their_integer_part() { + assert_eq!( + [".5", "0.75", "1.0", "2.5f", "1.5e1", "7", "0x10"].map(jcpp_integer), + [Some(0), Some(0), Some(1), Some(2), Some(10), Some(7), None] + ); + // Steadfast's fog strength: the option is 0.5, so Iris takes the + // 0.75 branch (0 == 0). + let set = options(&["#define FOG 0.5 // [0.0 0.5 0.75 1.0]"]); + let text = "\ +#if FOG == 1.0 +a = 1 +#elif FOG == 0.75 +a = 0.75 +#else +a = 0.5 +#endif +#if(FOG<1e1) +b = 1 +#endif +"; + let env = Environment { + defines: Vec::new(), + }; + let values = OptionValues::default(); + let out = preprocess(text, &env, &set, &values).unwrap(); + assert_eq!(out, "a = 0.75\nb = 1\n"); + assert_eq!( + jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values), + "#elif 0 == 0 && X > 2" + ); + } + #[test] fn boolean_expressions() { let set = options(&["#define A", "//#define B", "#define C"]); diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index f9a61169e..708ab5771 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -18,7 +18,11 @@ //! swizzled shadow lookup is widened first (naga has no scalar swizzle); //! - global initialisers run at the start of `main` (drivers accept //! non-constant ones), unsized global arrays are sized from them; -//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none). +//! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none); +//! - what naga refuses and drivers accept: `%` goes through overloads (naga +//! won't take `ivec2 % int`), `sqrt` of a negative constant isn't folded, +//! constants naga can't fold (`?:`, `mix`) become globals set in `main`, +//! and 16/8-bit types are their 32-bit ones. //! //! The programs of one pass share a [`Link`], so their locations, bindings and //! uniform block agree. @@ -234,6 +238,81 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; } vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; } "; +/// `%` as overloads: naga's GLSL front end splats a scalar operand for +/// `+ - / & ^ |` but not for `%`, and rejects `ivec2(uv) % 256` (Noble). +fn modulo_helpers() -> String { + let mut out = String::new(); + for (s, v) in [("int", "ivec"), ("uint", "uvec")] { + out.push_str(&format!("{s} iris_mod({s} a, {s} b) {{ return a % b; }}\n")); + for n in 2..=4 { + let v = format!("{v}{n}"); + out.push_str(&format!("{v} iris_mod({v} a, {v} b) {{ return a % b; }}\n")); + out.push_str(&format!( + "{v} iris_mod({v} a, {s} b) {{ return a % {v}(b); }}\n" + )); + out.push_str(&format!( + "{v} iris_mod({s} a, {v} b) {{ return {v}(a) % b; }}\n" + )); + } + } + out +} + +/// 16- and 8-bit types (`GL_NV_gpu_shader5`, `GL_EXT_shader_explicit_arithmetic_types`) +/// and their built-ins, as the 32-bit ones WGSL has: Noble declares +/// `u16vec2` & co. when Iris reports an NVIDIA GPU, and falls back to these +/// same aliases elsewhere. +const SMALL_TYPES: &[(&str, &str)] = &[ + ("float16_t", "float"), + ("f16vec2", "vec2"), + ("f16vec3", "vec3"), + ("f16vec4", "vec4"), + ("int16_t", "int"), + ("i16vec2", "ivec2"), + ("i16vec3", "ivec3"), + ("i16vec4", "ivec4"), + ("uint16_t", "uint"), + ("u16vec2", "uvec2"), + ("u16vec3", "uvec3"), + ("u16vec4", "uvec4"), + ("int8_t", "int"), + ("i8vec2", "ivec2"), + ("i8vec3", "ivec3"), + ("i8vec4", "ivec4"), + ("uint8_t", "uint"), + ("u8vec2", "uvec2"), + ("u8vec3", "uvec3"), + ("u8vec4", "uvec4"), + ("packFloat2x16", "packHalf2x16"), + ("unpackFloat2x16", "unpackHalf2x16"), +]; + +/// `source` with [`SMALL_TYPES`] replaced, word by word. +fn widen_small_types(source: &str) -> std::borrow::Cow<'_, str> { + if !SMALL_TYPES.iter().any(|(t, _)| source.contains(t)) { + return source.into(); + } + let mut out = String::with_capacity(source.len()); + let mut rest = source; + while let Some(c) = rest.chars().next() { + let len = if c.is_ascii_alphanumeric() || c == '_' { + rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .unwrap_or(rest.len()) + } else { + c.len_utf8() + }; + let word = &rest[..len]; + out.push_str( + SMALL_TYPES + .iter() + .find(|(t, _)| *t == word) + .map_or(word, |(_, w)| w), + ); + rest = &rest[len..]; + } + out.into() +} + /// Translate one preprocessed program. `locate` turns a line of `source` /// into `file:line` for errors. pub fn translate( @@ -248,7 +327,8 @@ pub fn translate( Stage::Compute => naga::ShaderStage::Compute, _ => return Err(format!("{stage:?} programs are not supported")), }; - let mut unit = ast::TranslationUnit::parse(source).map_err(|e| { + let source = widen_small_types(source); + let mut unit = ast::TranslationUnit::parse(&source).map_err(|e| { let line = e.line() + 1; format!("{}: {}", locate(line), e.inner()) })?; @@ -281,6 +361,111 @@ pub fn translate( }) } +/// The GLSL built-ins naga's constant evaluator folds (`MathFunction`s it +/// implements), besides type constructors. +const FOLDABLE: &[&str] = &[ + "abs", + "acos", + "acosh", + "asin", + "asinh", + "atan", + "atanh", + "ceil", + "clamp", + "cos", + "cosh", + "cross", + "degrees", + "distance", + "dot", + "exp", + "exp2", + "floor", + "fma", + "fract", + "inversesqrt", + "length", + "log", + "log2", + "max", + "min", + "normalize", + "pow", + "radians", + "round", + "sign", + "sin", + "sinh", + "sqrt", + "step", + "tan", + "tanh", + "trunc", +]; + +/// Whether a constant's initialisers need what naga can't fold and drivers +/// do: a `?:`, another built-in (Bliss's `mix`), or a constant that had to +/// become a global (`runtime`). +fn needs_runtime(list: &ast::InitDeclaratorList, runtime: &HashSet) -> bool { + let constructor = |name: &str| { + let n = name.trim_start_matches(['i', 'u', 'b', 'd']); + matches!(name, "float" | "int" | "uint" | "bool" | "double") + || n.starts_with("vec") + || n.starts_with("mat") + }; + let expr = |e: &ast::Expr| { + fn walk(e: &ast::Expr, f: &dyn Fn(&ast::Expr) -> bool) -> bool { + use ast::ExprData as E; + f(e) || match &e.content { + E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) | E::Dot(a, _) => walk(a, f), + E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) | E::Bracket(a, b) => { + walk(a, f) || walk(b, f) + } + E::Ternary(a, b, c) => walk(a, f) || walk(b, f) || walk(c, f), + E::FunCall(_, args) => args.iter().any(|a| walk(a, f)), + _ => false, + } + } + walk(e, &|e| match &e.content { + ast::ExprData::Ternary(..) => true, + ast::ExprData::Variable(v) => runtime.contains(v.as_str()), + ast::ExprData::FunCall(f, _) => { + callee(f).is_some_and(|c| !constructor(&c) && !FOLDABLE.contains(&c.as_str())) + } + _ => false, + }) + }; + fn init(i: &ast::Initializer, expr: &dyn Fn(&ast::Expr) -> bool) -> bool { + match &i.content { + ast::InitializerData::Simple(e) => expr(e), + ast::InitializerData::List(items) => items.iter().any(|i| init(i, expr)), + } + } + let tail = list.tail.iter().filter_map(|t| t.initializer.as_ref()); + list.head + .initializer + .iter() + .chain(tail) + .any(|i| init(i, &expr)) +} + +/// A negative number: `-1.0`, `-1`. +fn negative_constant(e: &ast::Expr) -> bool { + use ast::ExprData as E; + match &e.content { + E::Unary(op, a) if op.content == ast::UnaryOpData::Minus => { + matches!( + a.content, + E::FloatConst(v) if v > 0.0 + ) || matches!(a.content, E::IntConst(v) if v > 0) + || matches!(a.content, E::DoubleConst(v) if v > 0.0) + } + E::FloatConst(v) => *v < 0.0, + _ => false, + } +} + fn first_lines(s: &str) -> String { s.lines().take(8).collect::>().join("\n") } @@ -316,6 +501,14 @@ struct Legaliser<'a> { /// Identifiers used, for the implicit declarations. used: HashSet, errors: Vec, + /// Inside a constant initialiser: no helper calls there. + constant: bool, + /// The program uses `%` ([`modulo_helpers`]) or `iris_sqrt`: their + /// helpers go in. + modulo: bool, + nan: bool, + /// Constants turned into globals ([`needs_runtime`]). + runtime_constants: HashSet, } fn var(name: &str) -> ast::Expr { @@ -507,6 +700,10 @@ impl<'a> Legaliser<'a> { declared: HashSet::new(), used: HashSet::new(), errors: Vec::new(), + constant: false, + modulo: false, + nan: false, + runtime_constants: HashSet::new(), } } @@ -736,9 +933,25 @@ impl<'a> Legaliser<'a> { } return Ok(false); } - if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) { + // A constant naga can't fold becomes a global set at the start of `main`. + if has(ast::StorageQualifierData::Const) && needs_runtime(list, &self.runtime_constants) { + self.runtime_constants + .extend(names.iter().map(|(n, _)| n.clone())); + let q = &mut list.head.ty.qualifier; + if let Some(q) = q { + q.qualifiers.retain(|q| { + !matches!(&q.content, ast::TypeQualifierSpecData::Storage(s) + if s.content == ast::StorageQualifierData::Const) + }); + } + if q.as_ref().is_some_and(|q| q.qualifiers.is_empty()) { + *q = None; + } + } else if has(ast::StorageQualifierData::Const) || has(ast::StorageQualifierData::Shared) { self.sized(list); + self.constant = true; self.global_initialisers(list, false); + self.constant = false; return Ok(true); } self.sized(list); @@ -930,6 +1143,8 @@ impl<'a> Legaliser<'a> { return; }; self.sized(list); + self.constant = + storage(&list.head.ty.qualifier).contains(&ast::StorageQualifierData::Const); if let Some(i) = &mut list.head.initializer { self.initializer(i); } @@ -944,6 +1159,7 @@ impl<'a> Legaliser<'a> { let n = t.ident.ident.as_str().to_owned(); self.declare(&n); } + self.constant = false; } fn initializer(&mut self, i: &mut ast::Initializer) { @@ -1148,6 +1364,24 @@ impl<'a> Legaliser<'a> { | E::FloatConst(_) | E::DoubleConst(_) => {} E::Unary(_, a) | E::PostInc(a) | E::PostDec(a) => self.expr(a), + E::Binary(op, a, b) if op.content == ast::BinaryOpData::Mod && !self.constant => { + self.expr(a); + self.expr(b); + self.modulo = true; + let (a, b) = ( + std::mem::replace(&mut **a, var("_")), + std::mem::replace(&mut **b, var("_")), + ); + *e = call("iris_mod", vec![a, b]); + } + E::Assignment(a, op, b) if op.content == ast::AssignmentOpData::Mod => { + self.expr(a); + self.expr(b); + self.modulo = true; + let rhs = std::mem::replace(&mut **b, var("_")); + **b = call("iris_mod", vec![(**a).clone(), rhs]); + *op = ast::AssignmentOpData::Equal.into_node(); + } E::Binary(_, a, b) | E::Assignment(a, _, b) | E::Comma(a, b) => { self.expr(a); self.expr(b); @@ -1268,6 +1502,12 @@ impl<'a> Legaliser<'a> { if self.functions.contains(&name) { return; } + // `sqrt(-1.0)`, Bloop's NaN: naga folds it and fails, drivers give NaN. + if name == "sqrt" && !self.constant && args.len() == 1 && negative_constant(&args[0]) { + *f = ast::FunIdentifierData::Expr(Box::new(var("iris_sqrt"))).into_node(); + self.nan = true; + return; + } if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { *f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node(); } else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) { @@ -1307,6 +1547,12 @@ impl<'a> Legaliser<'a> { } let mut out = String::from("#version 450 core\n"); out.push_str(HELPERS); + if self.modulo { + out.push_str(&modulo_helpers()); + } + if self.nan { + out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); + } if !self.link.uniforms.is_empty() { out.push_str("layout(std140, set = 0, binding = 0) uniform IrisUniforms {\n"); for (_, decl) in &self.link.uniforms { diff --git a/crates/horizon-shaderpack/tests/pack.rs b/crates/horizon-shaderpack/tests/pack.rs index 7aa45e8fa..c957d7fb4 100644 --- a/crates/horizon-shaderpack/tests/pack.rs +++ b/crates/horizon-shaderpack/tests/pack.rs @@ -121,6 +121,69 @@ fn preprocesses_with_defaults_and_with_values() { ); } +/// JCPP lets a `#define` replace a macro (Bloop's `TILT_ANGLE`); the added +/// `#undef`s don't move the lines errors name. +#[test] +fn a_define_replaces_an_earlier_one() { + use horizon_shaderpack::{include::Inlined, preprocess::preprocess}; + let text = "#define TILT 5.0\nfloat a = TILT;\n # define TILT 1.5 // radians\nfloat b = TILT;\n#define F(x) x\n#define F(x) (x * 2)\nfloat c = F(1);\n#if\n"; + let source = Inlined { + text: text.into(), + origin: (1..=8).map(|l| ("lib/specular.glsl".into(), l)).collect(), + }; + let error = preprocess(&source, &env()).unwrap_err(); + assert!(error.starts_with("lib/specular.glsl:8:"), "{error}"); + let source = Inlined { + text: text.replace("#if\n", ""), + ..source + }; + let out = preprocess(&source, &env()).unwrap().text; + let lines: Vec<&str> = out.lines().collect(); + assert_eq!(lines[1], "float a = 5.0 ;"); + assert_eq!(lines[3], "float b = 1.5 ;"); + assert_eq!(lines[6], "float c = ( 1 * 2 ) ;"); +} + +/// Conditions as JCPP reads them: an empty macro counts as 0 (Bloop's +/// `#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER` with Iris's empty vendor +/// macro, its `#define TAA_USE_YCOCG`), a float as its integer part; a +/// quoted `#error` lexes, and an `#if` may run to the end. +#[test] +fn conditions_read_as_jcpp_does() { + use horizon_shaderpack::{include::Inlined, preprocess::preprocess}; + let mut env = env(); + env.define("MC_GL_VENDOR_OTHER", ""); + let text = "#define TAA_USE_YCOCG +#define LEVEL 0.5 +#if MC_GL_VENDOR_INTEL || MC_GL_VENDOR_OTHER +float gather = 0.0; +#else +float gather = 1.0; +#endif +#if TAA_USE_YCOCG +float ycocg = 1.0; +#endif +#if defined TAA_USE_YCOCG && defined(MC_GL_VENDOR_OTHER) && LEVEL == 0 +float both = 1.0; +#endif +#ifndef TAA_USE_YCOCG +#error \"This program should be disabled\" +#endif +#ifdef TAA_USE_YCOCG +float open = 1.0; +"; + let source = Inlined { + text: text.into(), + origin: Vec::new(), + }; + let out = preprocess(&source, &env).unwrap().text; + let words: Vec<&str> = out.split_whitespace().collect(); + assert_eq!( + words.join(" "), + "float gather = 1.0 ; float both = 1.0 ; float open = 1.0 ;" + ); +} + #[test] fn reports_missing_includes_and_cycles() { let pack = JavaPack::open(&mini()).unwrap(); diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index da8dc7e32..bb4a544c2 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -290,6 +290,47 @@ fn reports_errors_with_their_place() { assert_eq!(err, "uniform a is declared as both `float a` and `int a`"); } +/// What naga refuses and drivers accept: `vec % scalar` (Noble), `sqrt` of +/// a negative constant (Bloop's NaN), constants naga can't fold (Bliss's +/// `?:`, `mix`), and 16-bit types (Noble on NVIDIA). +#[test] +fn legalises_what_naga_refuses() { + let mut link = Link::default(); + let fs = run( + Stage::Fragment, + "uniform vec2 uv; +const int RES = 256 % 100; +const vec3 TARGET = length(vec3(1.0)) < 0.001 ? vec3(0.0) : normalize(vec3(1.0)); +const vec3 TINT = mix(TARGET, vec3(1.0), 0.5); +const vec3 HALF = TINT * 0.5; +u16vec2 pack(uint v) { return u16vec2(v & 65535u, v >> 16u); } +float nan() { return sqrt(-1.0); } +void main() { + ivec2 texel = ivec2(uv) % RES; + texel %= 7; + uint packed = packFloat2x16(f16vec2(HALF.xy)); + gl_FragColor = vec4(vec2(texel), float(pack(packed).x), nan()); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "const int RES = 256 % 100;", + "vec3 TARGET;", + "vec3 TINT;", + "vec3 HALF;", + "ivec2 texel = iris_mod(ivec2(uv), RES);", + "texel = iris_mod(texel, 7);", + "uvec2 pack(uint v)", + "return iris_sqrt(-1.);", + "uint packed = packHalf2x16(vec2(HALF.xy));", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + reparse(&fs.wgsl).unwrap(); +} + /// The written WGSL, read back and validated: what wgpu is given. fn reparse(wgsl: &str) -> Result<(), String> { let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?; From e570561db9115d055d70317b0386801280737aa1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:21:44 +0200 Subject: [PATCH 043/115] Shader packs: write narrow fragment outputs through a vec4 GL fills the channels a fragment shader leaves out; wgpu refuses a pipeline whose output has fewer channels than its target. Steadfast's final pass writes `out vec3` and failed to build in the game. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-shaderpack/src/translate.rs | 40 +++++++++++++- crates/horizon-shaderpack/tests/translate.rs | 56 ++++++++++++++++++++ 2 files changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 708ab5771..8a32795af 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -238,6 +238,31 @@ vec3 iris_modf(vec3 x, out vec3 i) { i = trunc(x); return x - i; } vec4 iris_modf(vec4 x, out vec4 i) { i = trunc(x); return x - i; } "; +/// A fragment output narrower than four channels (`out vec3 color`, +/// Steadfast's `final`): the four-channel type it is written through and the +/// epilogue line that fills it, with alpha 1 and the rest 0. `None` when the +/// output already has four channels. +fn widen_output(ty: &str, name: &str) -> Option<(String, String)> { + let (wide, one, zero) = match ty { + "float" | "vec2" | "vec3" => ("vec4", "1.0", "0.0"), + "int" | "ivec2" | "ivec3" => ("ivec4", "1", "0"), + "uint" | "uvec2" | "uvec3" => ("uvec4", "1u", "0u"), + _ => return None, + }; + let channels = match ty.chars().last() { + Some('2') => 2, + Some('3') => 3, + _ => 1, + }; + let mut parts = vec![name.to_owned()]; + parts.extend((channels..3).map(|_| zero.to_owned())); + parts.push(one.to_owned()); + Some(( + wide.to_owned(), + format!("iris_out_{name} = {wide}({});", parts.join(", ")), + )) +} + /// `%` as overloads: naga's GLSL front end splats a scalar operand for /// `+ - / & ^ |` but not for `%`, and rejects `ivec2(uv) % 256` (Noble). fn modulo_helpers() -> String { @@ -924,8 +949,19 @@ impl<'a> Legaliser<'a> { let at = explicit .map(|l: u32| l + i as u32) .unwrap_or_else(|| self.next_output()); - self.header - .push(format!("layout(location = {at}) out {full} {name}{array};")); + if let (Some(widened), "") = (widen_output(&full, name), array.as_str()) { + // GL fills the missing channels of a narrow output; + // wgpu wants every channel of the target written. + let (wide, fill) = widened; + self.header.push(format!("{full} {name};")); + self.header.push(format!( + "layout(location = {at}) out {wide} iris_out_{name};" + )); + self.epilogue.push(fill); + } else { + self.header + .push(format!("layout(location = {at}) out {full} {name}{array};")); + } self.interface.outputs.insert(at, name.clone()); } else { self.varying(dir, &interp, &full, name, array); diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index bb4a544c2..3c71d8546 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -331,6 +331,62 @@ void main() { reparse(&fs.wgsl).unwrap(); } +/// A fragment output narrower than its four-channel target (Steadfast's +/// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: +/// GL fills the missing channels, wgpu refuses the pipeline. +#[test] +fn narrow_fragment_outputs_fill_four_channels() { + let mut link = Link::default(); + let fs = run( + Stage::Fragment, + "uniform vec3 tint; +layout(location = 0) out vec3 color; +layout(location = 1) out float depth; +out vec4 extra; +void main() { + color = tint; + depth = 0.5; + extra = vec4(tint, 0.25); +} +", + &mut link, + ) + .unwrap(); + for wanted in [ + "layout(location = 0) out vec4 iris_out_color;", + "iris_out_color = vec4(color, 1.0);", + "layout(location = 1) out vec4 iris_out_depth;", + "iris_out_depth = vec4(depth, 0.0, 0.0, 1.0);", + "layout(location = 2) out vec4 extra;", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + assert_eq!( + fs.interface.outputs.values().collect::>(), + ["color", "depth", "extra"] + ); + let module = naga::front::wgsl::parse_str(&fs.wgsl).unwrap(); + let entry = &module.entry_points[0]; + let result = entry.function.result.as_ref().unwrap(); + let naga::TypeInner::Struct { members, .. } = &module.types[result.ty].inner else { + panic!("{}", fs.wgsl); + }; + for m in members { + assert!( + matches!( + module.types[m.ty].inner, + naga::TypeInner::Vector { + size: naga::VectorSize::Quad, + .. + } + ), + "{}", + fs.wgsl + ); + } + reparse(&fs.wgsl).unwrap(); +} + /// The written WGSL, read back and validated: what wgpu is given. fn reparse(wgsl: &str) -> Result<(), String> { let module = naga::front::wgsl::parse_str(wgsl).map_err(|e| e.emit_to_string(wgsl))?; From 6ea7a51ff35983c2082cfa4e002136a461261845 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:05:29 +0200 Subject: [PATCH 044/115] Shader Packs page: the folder's path, Open Folder, a switch per pack The Shader Pack setting cycled through what shaderpacks/ held, so with the folder empty (or the packs in the launcher's version folder, as brabus_ had them) it silently stayed Off. The row now opens a Shader Packs page: a sidebar section in the Horizon menus, Video Settings > Shader Packs... in the Classic ones. It shows the game home's shaderpacks/ path and an Open Folder button (made if missing), says when there is no pack, and lists one switch per pack. A pack that fails to load says why on its row. The list is read again every second while the page shows. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/options.rs | 5 + .../horizon-client/src/game/shader_packs.rs | 8 +- .../horizon-client/src/game/startup_menu.rs | 5 + crates/horizon-client/src/graphics_ui.rs | 47 ++-- crates/horizon-client/src/options_horizon.rs | 167 ++++++++++++- crates/horizon-client/src/options_ui.rs | 219 +++++++++++++++++- crates/horizon-client/src/shader_pack.rs | 32 ++- docs/shader-packs.md | 20 +- 8 files changed, 462 insertions(+), 41 deletions(-) diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index 12efde5be..61036d18c 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -230,6 +230,11 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::OpenShaderPackFolder => { + let dir = horizon_client::shader_pack::folder(); + let _ = std::fs::create_dir_all(&dir); + super::packs::open_folder(&dir); + } } } Ok(()) diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index 6b9ee33dc..052f64d26 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -37,11 +37,8 @@ impl ShaderPacks { } } -/// `shaderpacks/` beside `options.txt`. pub(super) fn dir() -> PathBuf { - std::env::current_dir() - .unwrap_or_default() - .join(shader_pack::DIR) + shader_pack::folder() } impl Game<'_> { @@ -77,6 +74,7 @@ impl Game<'_> { return self.shader_pack_error(&id, &e.to_string()); } self.shader_packs.pack = pack; + self.ui.options.shader_pack_error = None; } /// Give the loaded pack to the renderer (also after it is rebuilt). pub(super) fn apply_shader_pack(&mut self) -> horizon_client::Result<()> { @@ -105,6 +103,8 @@ impl Game<'_> { } fn shader_pack_error(&mut self, id: &str, error: &str) { log::warn!("Horizon: shader pack {id}: {error}"); + // The Shader Packs page says why on the pack's row. + self.ui.options.shader_pack_error = Some((id.to_owned(), error.to_owned())); self.system_message(Text::literal(format!("Shader pack {id}: {error}"))); } } diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index c5b19763c..ffbbe7193 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -373,6 +373,11 @@ impl Loading { let _ = std::fs::create_dir_all(&dir); packs::open_folder(&dir); } + Event::OpenShaderPackFolder => { + let dir = horizon_client::shader_pack::folder(); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } Event::ButtonClick => {} } } diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index eea2d03cb..9722ddc21 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -237,7 +237,7 @@ pub fn rows(level: Level) -> Vec { h( H::ShaderPack, High, - "Redraws the world with a pack from shaderpacks/. Off is vanilla.", + "Redraws the world with a pack from the shaderpacks folder. Off is vanilla.", ), Row::Header("Preferences"), v(Opt::ViewBobbing, None, "Sways the view while walking."), @@ -422,17 +422,6 @@ impl H { H::Antialiasing => g.fxaa = !g.fxaa, H::BatteryMode => g.battery = !g.battery, H::GraphicsApi => g.api = step(&GraphicsApi::ALL, g.api, back), - H::ShaderPack => { - // Off, then every pack in shaderpacks/ by folder name. - let dir = std::env::current_dir() - .unwrap_or_default() - .join(crate::shader_pack::DIR); - let mut all = vec![String::new()]; - all.extend(crate::shader_pack::list(&dir).into_iter().map(|(id, _)| id)); - let i = all.iter().position(|x| *x == g.shader_pack).unwrap_or(0); - let n = all.len(); - g.shader_pack = all[if back { (i + n - 1) % n } else { (i + 1) % n }].clone(); - } H::Pacing => { g.pacing = match g.pacing { Pacing::Efficient => Pacing::Precise, @@ -559,6 +548,8 @@ pub enum Action { Changed, OpenAdvanced, OpenSimple, + /// The Shader Pack row: the Shader Packs page (where packs are picked). + OpenShaderPacks, Done, } @@ -784,6 +775,9 @@ impl GraphicsUi { } return match wd.target { Target::Button(action) => vec![Action::ButtonClick, action], + Target::Item(Item::Horizon(H::ShaderPack)) => { + vec![Action::ButtonClick, Action::OpenShaderPacks] + } Target::Item(item) => { if item.slider(s).is_some() { self.dragging = Some(item); @@ -1003,11 +997,30 @@ mod tests { ); s.horizon.shader_pack = "horizon-sample".into(); assert_eq!(row.label(&s).plain(), "Shader Pack: horizon-sample"); - // Picking a pack keeps the preset. - Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]); - let preset = s.horizon.preset; - row.cycle(&mut s, false, [854, 480]); - assert_eq!(s.horizon.preset, preset); + // The row opens the Shader Packs page, where packs are picked. + let mut ui = GraphicsUi::default(); + let find = |ui: &mut GraphicsUi| { + let (widgets, ..) = ui.layout(Level::Advanced, 854.0, 480.0); + widgets + .into_iter() + .find(|w| matches!(w.target, Target::Item(i) if i == row)) + .unwrap() + }; + ui.scroll = find(&mut ui).y - GraphicsUi::bounds(480.0).0 - 4.0; + let w = find(&mut ui); + assert_eq!( + ui.click( + Level::Advanced, + &mut s, + (w.x + 1.0, w.y + 1.0), + (854.0, 480.0), + [854, 480], + false, + false + ), + [Action::ButtonClick, Action::OpenShaderPacks] + ); + assert_eq!(s.horizon.shader_pack, "horizon-sample"); } #[test] diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index 75458ae40..50a42f337 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -38,7 +38,14 @@ pub enum HRow { Mod(usize), /// Opens the directory where Horizon mods are installed. OpenModFolder, + /// `shaderpacks/`'s path and a button opening it. + ShaderPackFolder, + /// Shader pack `i` of `OptionsUi::shader_packs` and its switch. + ShaderPack(usize), } + +/// The sidebar section listing the shader packs. +pub const SHADER_PACKS: &str = "Shader Packs"; /// A sidebar section: name, description, rows. pub struct Section { pub name: &'static str, @@ -172,6 +179,12 @@ pub const SECTIONS: &[Section] = &[ .to_vec() }, }, + Section { + name: SHADER_PACKS, + blurb: "Packs that redraw the world. Off is the vanilla look.", + // The packs follow, from the folder (`horizon_rows`). + rows: |_| vec![HRow::ShaderPackFolder], + }, Section { name: "Interface", blurb: "Menus and resource packs.", @@ -309,7 +322,15 @@ fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch { } impl OptionsUi { fn horizon_rows(&self, s: &Settings, section: usize) -> Vec { - let rows = (SECTIONS[section].rows)(s); + let mut rows = (SECTIONS[section].rows)(s); + if SECTIONS[section].name == SHADER_PACKS { + if self.shader_packs.packs.is_empty() { + rows.push(HRow::Header( + "No shader packs: put a pack's folder or .zip in this folder", + )); + } + rows.extend((0..self.shader_packs.packs.len()).map(HRow::ShaderPack)); + } let query = self.settings_search.value.to_lowercase(); if query.is_empty() || !searchable_section(section) { return rows; @@ -511,6 +532,38 @@ impl OptionsUi { ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0); ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m)); } + HRow::ShaderPackFolder => { + let label = "Open Folder"; + let bw = ui.button_width(label, false).max(96.0); + let dir = self.shader_packs.dir.display().to_string(); + ui.described_row(x, y, "Folder", "", 0.0, (0, ""), &dir, cw - bw - 24.0); + ui.button( + ROW + i as u64, + [control_x - bw, y + 12.0, bw, CONTROL], + label, + Button::Secondary, + true, + ); + } + HRow::ShaderPack(p) => { + let (id, info) = &self.shader_packs.packs[p]; + let error = match info { + Err(e) => Some(e.as_str()), + Ok(_) => self + .shader_pack_error + .as_ref() + .filter(|(failed, _)| failed == id) + .map(|(_, e)| e.as_str()), + }; + let (cost, text) = match (error, info) { + (Some(e), _) => ((3, "Failed"), e), + (None, Ok(info)) => ((0, ""), info.description.as_str()), + (None, Err(_)) => unreachable!(), + }; + ui.described_row(x, y, id, "", 0.0, cost, text, cw - 60.0); + let on = s.horizon.shader_pack == *id; + ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, on); + } HRow::OpenModFolder => { ui.row(x, y, "Mod folder", "", 0.0); let label = "Open Folder"; @@ -756,13 +809,7 @@ impl OptionsUi { return events; } match target { - Some(Target::Nav(i)) => { - if searchable_section(self.section) || searchable_section(i) { - self.settings_search.set_value(""); - } - self.section = i; - self.hscroll = 0.0; - } + Some(Target::Nav(i)) => self.select_section(i), Some(Target::Search) => { self.settings_search.focused = true; self.settings_search.move_cursor_to_end(false); @@ -798,6 +845,10 @@ impl OptionsUi { } events.push(Event::Changed); } + Some(HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..)) => { + events.push(Event::ButtonClick); + self.open_section(SHADER_PACKS); + } Some(HRow::Graphics(item, ..)) => { item.cycle(s, right, framebuffer); events.push(Event::Changed); @@ -818,6 +869,14 @@ impl OptionsUi { events.push(Event::ButtonClick); events.push(Event::OpenModFolder); } + Some(HRow::ShaderPackFolder) if !right => { + events.push(Event::ButtonClick); + events.push(Event::OpenShaderPackFolder); + } + Some(HRow::ShaderPack(p)) => { + self.toggle_shader_pack(s, *p); + events.push(Event::Changed); + } _ => {} } } @@ -825,6 +884,19 @@ impl OptionsUi { } events } + fn select_section(&mut self, i: usize) { + if searchable_section(self.section) || searchable_section(i) { + self.settings_search.set_value(""); + } + self.section = i; + self.hscroll = 0.0; + } + /// Show the sidebar section called `name`. + fn open_section(&mut self, name: &str) { + if let Some(i) = SECTIONS.iter().position(|s| s.name == name) { + self.select_section(i); + } + } pub(crate) fn scroll_horizon(&mut self, amount: f32) { self.hscroll -= amount * 40.0; } @@ -1057,6 +1129,85 @@ mod tests { assert_eq!(ui.hscroll, 0.0); } + /// The Shader Packs section: the folder's path and Open Folder, a switch + /// per pack; the Video section's Shader Pack row leads here (#941, #925). + #[test] + fn shader_packs_section_opens_the_folder_and_picks_a_pack() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let dir = + std::env::temp_dir().join(format!("horizon-shader-section-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut options = section_ui(SHADER_PACKS); + let mut settings = Settings::default(); + options.shader_packs.poll(dir.clone()); + assert!(matches!( + options.horizon_rows(&settings, options.section)[..], + [HRow::ShaderPackFolder, HRow::Header(_)] + )); + std::fs::write(dir.join("Pack.zip"), b"").unwrap(); + options.shader_packs = Default::default(); + options.shader_packs.poll(dir.clone()); + // Click the control with hit id `id`, scrolling until it shows. + let click = |options: &mut OptionsUi, settings: &mut Settings, id: u64| { + for _ in 0..40 { + let mut batch = horizon_batch(framebuffer); + let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0)); + options.horizon_layout(settings, &mut ui, 1.0); + if let Some(hit) = ui.hits.iter().find(|hit| hit.id == id) { + let r = hit.rect; + let scale = ui.density / ui.batch.scale; + let at = ((r[0] + r[2]) * 0.5 * scale, (r[1] + r[3]) * 0.5 * scale); + drop(ui); + return options.click_horizon( + settings, + &atlas, + at.0, + at.1, + framebuffer, + false, + false, + ); + } + drop(ui); + options.hscroll += 200.0; + } + panic!("no control {id}"); + }; + assert_eq!( + click(&mut options, &mut settings, ROW), + [Event::ButtonClick, Event::OpenShaderPackFolder] + ); + assert_eq!( + click(&mut options, &mut settings, ROW + 1), + [Event::Changed] + ); + assert_eq!(settings.horizon.shader_pack, "Pack.zip"); + click(&mut options, &mut settings, ROW + 1); + assert_eq!(settings.horizon.shader_pack, ""); + + let mut options = section_ui("Video"); + settings.horizon.advanced = true; + let video = SECTIONS.iter().position(|s| s.name == "Video").unwrap(); + let row = options + .horizon_rows(&settings, video) + .iter() + .position(|r| { + matches!( + r, + HRow::Graphics(Item::Horizon(graphics_ui::H::ShaderPack), ..) + ) + }) + .unwrap(); + assert_eq!( + click(&mut options, &mut settings, ROW + row as u64), + [Event::ButtonClick] + ); + assert_eq!(SECTIONS[options.section].name, SHADER_PACKS); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn mods_section_opens_folder_from_its_button() { let atlas = atlas(); diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 0ea49cb72..7d86263df 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -862,6 +862,8 @@ pub enum Page { Font, Packs, Mods, + /// The shader packs in `shaderpacks/`: pick one, open the folder. + ShaderPacks, /// Horizon's graphics settings (`graphics_ui`). Graphics, GraphicsAdvanced, @@ -888,6 +890,9 @@ enum Act { HorizonMenus, ToggleMod(usize), OpenModFolder, + /// Pick shader pack `i` of `OptionsUi::shader_packs` (again: off). + ToggleShaderPack(usize), + OpenShaderPackFolder, } enum WKind { Button { @@ -935,6 +940,8 @@ pub enum Event { Packs(Vec), OpenPackFolder, OpenModFolder, + /// Create `shaderpacks/` if needed and open it. + OpenShaderPackFolder, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -993,6 +1000,10 @@ pub struct OptionsUi { /// Scroll the selected language into the middle on the next layout. center_language: bool, pub graphics: crate::graphics_ui::GraphicsUi, + /// `shaderpacks/` and its packs, read while the Shader Packs page shows. + pub shader_packs: crate::shader_pack::Folder, + /// The pack that failed to load last and why (set by the game). + pub shader_pack_error: Option<(String, String)>, } impl Default for OptionsUi { fn default() -> Self { @@ -1025,6 +1036,8 @@ impl Default for OptionsUi { in_world: false, center_language: false, graphics: Default::default(), + shader_packs: Default::default(), + shader_pack_error: None, } } } @@ -1073,6 +1086,8 @@ enum Row { Big(Opt), Pair(Opt, Option), Header(&'static str), + /// A line of grey text (a path). + Note(String), Buttons(Widget, Option), } fn pairs(opts: &[Opt]) -> Vec { @@ -1131,6 +1146,33 @@ impl OptionsUi { self.graphics.reset(); } } + /// Pick shader pack `i` of the folder, or turn it off when it is the + /// one running. + pub(crate) fn toggle_shader_pack(&self, s: &mut Settings, i: usize) { + let Some((id, Ok(_))) = self.shader_packs.packs.get(i) else { + return; + }; + let g = &mut s.horizon; + g.shader_pack = if g.shader_pack == *id { + String::new() + } else { + id.clone() + }; + } + pub(crate) fn shader_pack_failed(&self, id: &str) -> bool { + self.shader_pack_error + .as_ref() + .is_some_and(|(e, _)| e == id) + } + /// Whether the Shader Packs page (or the Horizon menus' section) shows. + fn shader_packs_shown(&self) -> bool { + self.page() == Page::ShaderPacks + || crate::ui_theme::horizon() + && self.page() == Page::Main + && crate::options_horizon::SECTIONS + .get(self.section) + .is_some_and(|s| s.name == crate::options_horizon::SHADER_PACKS) + } /// The graphics screen level of `page`, if it is one. fn graphics_level(page: Page) -> Option { match page { @@ -1153,6 +1195,7 @@ impl OptionsUi { Page::Font => "options.font.title", Page::Packs => "resourcePack.title", Page::Mods => "Mods", + Page::ShaderPacks => "Shader Packs", Page::Graphics | Page::GraphicsAdvanced => "options.videoTitle", Page::Controller => "Controller Settings", Page::PadBinds => "Controller Binds", @@ -1262,6 +1305,16 @@ impl OptionsUi { Act::Push(Page::GraphicsAdvanced), )), )]; + rows.push(Row::Buttons( + button( + 0.0, + 0.0, + 310.0, + Text::literal("Shader Packs..."), + Act::Push(Page::ShaderPacks), + ), + None, + )); // The way back from Classic menus. Horizon-only like the row // above, here rather than on the main Options screen so that // one keeps vanilla's exact layout; vanilla's interface @@ -1450,6 +1503,32 @@ impl OptionsUi { }) .collect() } + Page::ShaderPacks => { + let folder = &self.shader_packs; + let mut rows = vec![Row::Note(folder.dir.display().to_string())]; + if folder.packs.is_empty() { + rows.push(Row::Header( + "No shader packs: put a pack's folder or .zip in this folder", + )); + } + for (i, (id, info)) in folder.packs.iter().enumerate() { + let on = s.horizon.shader_pack == *id; + let mut label = Text::literal(format!("{id}: ")).append(on_off(on)); + if info.is_err() || self.shader_pack_failed(id) { + label = label.append(" (Failed)"); + } + let widget = button(0.0, 0.0, 310.0, label, Act::ToggleShaderPack(i)); + rows.push(Row::Buttons( + if info.is_ok() { + widget + } else { + inactive(widget) + }, + None, + )); + } + rows + } _ => { let _ = s; Vec::new() @@ -1849,6 +1928,21 @@ impl OptionsUi { }); y += padding + 18.0; } + Row::Note(text) => { + out.push(Widget { + x: 0.0, + y: y + 4.0, + w, + h: 9.0, + kind: WKind::Text { + text: Text::literal(text), + color: 0xFFA0A0A0, + centered: true, + }, + list: false, + }); + y += 16.0; + } Row::Big(opt) => { out.push(option_widget(s, opt, cx - 155.0, y + 2.0, 310.0)); y += 25.0; @@ -1875,13 +1969,20 @@ impl OptionsUi { } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - if page == Page::Mods { + let folder = match page { + Page::Mods => Some(("Open Mod Folder", Act::OpenModFolder)), + Page::ShaderPacks => { + Some(("Open Shader Pack Folder", Act::OpenShaderPackFolder)) + } + _ => None, + }; + if let Some((label, act)) = folder { out.push(button( cx - 154.0, h - 27.0, 150.0, - Text::literal("Open Mod Folder"), - Act::OpenModFolder, + Text::literal(label), + act, )); out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); } else { @@ -1911,6 +2012,9 @@ impl OptionsUi { atlas: &HudAtlas, cursor: (f32, f32), ) { + if self.shader_packs_shown() { + self.shader_packs.poll(crate::shader_pack::folder()); + } let (w, h) = (batch.width, batch.height); if let Some(error) = &self.resource_error { ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world); @@ -2210,6 +2314,7 @@ impl OptionsUi { Action::ButtonClick => events.push(Event::ButtonClick), Action::Changed => events.push(Event::Changed), Action::OpenAdvanced => self.push(Page::GraphicsAdvanced), + Action::OpenShaderPacks => self.push(Page::ShaderPacks), Action::OpenSimple => { if self.stack.len() >= 2 && self.stack[self.stack.len() - 2] == Page::Graphics @@ -2377,6 +2482,11 @@ impl OptionsUi { events.push(Event::Changed); } Act::OpenModFolder => events.push(Event::OpenModFolder), + Act::ToggleShaderPack(i) => { + self.toggle_shader_pack(s, i); + events.push(Event::Changed); + } + Act::OpenShaderPackFolder => events.push(Event::OpenShaderPackFolder), Act::None => {} } } @@ -2831,6 +2941,109 @@ mod tests { assert!(ui.resource_error.is_none()); } + /// The Shader Packs page (Video Settings > Shader Packs..., or the + /// Shader Pack row of Advanced graphics): the folder's path, Open Shader + /// Pack Folder, and a switch per pack (#941, #925). + #[test] + fn classic_shader_packs_page_shows_the_folder_and_picks_a_pack() { + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + let size = (480.0, 240.0); + let dir = std::env::temp_dir().join(format!("horizon-shaderpacks-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let find = |ui: &mut OptionsUi, s: &Settings, act: &dyn Fn(&Act) -> bool| { + ui.layout(s, size.0, size.1) + .0 + .into_iter() + .find(|w| matches!(&w.kind, WKind::Button { act: a, active: true, .. } if act(a))) + }; + ui.show(Page::Video); + let open = find(&mut ui, &s, &|a| *a == Act::Push(Page::ShaderPacks)).unwrap(); + ui.click( + &mut s, + &atlas, + open.x + 1.0, + open.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert_eq!(ui.page(), Page::ShaderPacks); + + ui.shader_packs.poll(dir.clone()); + let empty = ui.layout(&s, size.0, size.1).0; + let path = dir.display().to_string(); + for line in [path.as_str(), "No shader packs"] { + assert!( + empty.iter().any( + |w| matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(line)) + ), + "{line}" + ); + } + let folder = find(&mut ui, &s, &|a| *a == Act::OpenShaderPackFolder).unwrap(); + assert_eq!( + ui.click( + &mut s, + &atlas, + folder.x + 1.0, + folder.y + 1.0, + size, + [480, 240], + false, + false + ), + vec![Event::ButtonClick, Event::OpenShaderPackFolder] + ); + + std::fs::write(dir.join("Pack.zip"), b"").unwrap(); + ui.shader_packs = Default::default(); + ui.shader_packs.poll(dir.clone()); + let pack = find(&mut ui, &s, &|a| *a == Act::ToggleShaderPack(0)).unwrap(); + let events = ui.click( + &mut s, + &atlas, + pack.x + 1.0, + pack.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert!(events.contains(&Event::Changed)); + assert_eq!(s.horizon.shader_pack, "Pack.zip"); + ui.shader_pack_error = Some(("Pack.zip".into(), "broken".into())); + let label = |ui: &mut OptionsUi, s: &Settings| match find(ui, s, &|a| { + *a == Act::ToggleShaderPack(0) + }) + .unwrap() + .kind + { + WKind::Button { label, .. } => label.plain(), + _ => unreachable!(), + }; + assert!( + label(&mut ui, &s).ends_with("(Failed)"), + "{}", + label(&mut ui, &s) + ); + ui.click( + &mut s, + &atlas, + pack.x + 1.0, + pack.y + 1.0, + size, + [480, 240], + false, + false, + ); + assert_eq!(s.horizon.shader_pack, "", "a second click turns it off"); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn classic_mods_page_toggles_mods_and_keeps_dev_and_invalid_entries_inactive() { let atlas = atlas(); diff --git a/crates/horizon-client/src/shader_pack.rs b/crates/horizon-client/src/shader_pack.rs index ec86edc77..f3cf46028 100644 --- a/crates/horizon-client/src/shader_pack.rs +++ b/crates/horizon-client/src/shader_pack.rs @@ -171,11 +171,41 @@ pub fn list(dir: &Path) -> Vec<(String, Result)> { packs } +/// `shaderpacks/` beside `options.txt` (the game's working folder: the game +/// home, not the launcher's version folder). +pub fn folder() -> PathBuf { + std::env::current_dir().unwrap_or_default().join(DIR) +} + +/// `shaderpacks/` and its packs as the Shader Packs page lists them, read +/// again at most once a second while the page is open, so a pack dropped +/// into the folder shows up. +#[derive(Debug, Default)] +pub struct Folder { + pub dir: PathBuf, + pub packs: Vec<(String, Result)>, + read: Option, +} + +impl Folder { + pub fn poll(&mut self, dir: PathBuf) { + let fresh = self + .read + .is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(1)); + if fresh && self.dir == dir { + return; + } + self.packs = list(&dir); + self.dir = dir; + self.read = Some(std::time::Instant::now()); + } +} + /// A Java pack has no manifest: its name is its file name. fn java_info(name: String) -> Info { Info { name, - description: String::new(), + description: "Iris/OptiFine pack: its full-screen passes run.".into(), authors: Vec::new(), version: String::new(), license: String::new(), diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3cd068f2d..faf3c7d3f 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -13,7 +13,7 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Part | State | | --- | --- | | Renderer layout (below) | today's code | -| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs screen | first slice planned | +| Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs page | done (the page: list, pick, open the folder) | | Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned | | Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) | | Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros) | done: every program of the three test packs preprocesses | @@ -56,15 +56,19 @@ The lightmap, fog and sky colours are computed on the CPU (`environment.rs`, `fo ### Where packs live and how one is picked - Packs go in `shaderpacks/` beside `options.txt` in the game folder (the same folder Iris uses, so one folder - holds both kinds). A pack is a folder (zips planned). A pack with a `pack.toml` at its root is a Horizon pack; a pack - with a `shaders/` folder is a Java pack. -- **Options → Video Settings → Shader Packs...** (Classic screens, laid out like Iris's: the packs on the left with - "(off)" first, Apply and Done, *Open Shader Pack Folder*, *Shader Pack Settings...*) and a **Shader Packs** row in - the Horizon menus' Video section open the same list. + holds both kinds). That is the game home the launcher starts the game in (`%APPDATA%\horizon` on Windows, + `~/Library/Application Support/horizon` on macOS, `~/.local/share/horizon` on Linux), not the launcher's version + folder. A pack with a `pack.toml` at its root is a Horizon pack; a folder with `shaders/`, or a `.zip`, is a Java + pack. +- The **Shader Packs** page lists them: a sidebar section in the Horizon menus, **Video Settings → Shader Packs...** + in the Classic ones, and the Shader Pack row of the graphics settings leads to it. It shows the folder's full path + and an *Open Folder* button (the folder is made if it is missing), then one switch per pack: turning one on picks + it, turning it off is the vanilla picture. With no pack, it says so under the path. The list is read again every + second while the page is open, so a pack dropped into the folder shows up. - The choice is kept in `horizon-graphics.txt` (`shaderPack:`, empty = off). A pack's option values are kept in `shaderpacks/.txt`, as Iris does. -- A pack that fails to load or compile leaves the vanilla picture on and shows why, in red, on its row (and in the - log). Nothing a pack does can stop the game from starting. +- A pack that fails to load or compile leaves the vanilla picture (or the last pack that worked) on and says why on + its row ("Failed", with the error), in chat and in the log. Nothing a pack does can stop the game from starting. - Benchmarks (`--benchmark`) and the parity harnesses never load a pack. ### Layout From acbfb8ceca74de42569849f036c3db11d5b8f5b1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:32:17 +0200 Subject: [PATCH 045/115] docs/shader-packs.md: the ten packs tested and what stops the rest Co-Authored-By: Claude Opus 5.5 --- docs/shader-packs.md | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3cd068f2d..ecb71b5f6 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -16,7 +16,7 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Horizon shader packs: `composite` stage, uniforms, hot reload, Shader Packs screen | first slice planned | | Horizon shader packs: `deferred`, `gbuffer`, `shadow` stages, custom textures | planned | | Java shader packs: preprocessing + GLSL parse coverage | spike done: 450 of 470 programs reach valid WGSL (below) | -| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros) | done: every program of the three test packs preprocesses | +| Java shader packs: preprocessor (`crates/horizon-shaderpack`: includes, options, Iris's macros, JCPP's `#if` and `#define` rules) | done: every program of the three test packs preprocesses; ten packs tested (Compatibility, below) | | Java shader packs: GLSL → WGSL (`horizon_shaderpack::translate`: syntax-tree legaliser, naga) | done: the 464 programs the three test packs enable by default translate (below) | | Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs | | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs | @@ -378,6 +378,43 @@ shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but ignored), custom textures, the option screen; shadow matrices are identity. +### Compatibility + +Tested on 2026-10-22 on the Mac mini (M4 Pro, Metal) with each pack's default options, the 26.3 builds from Modrinth or +the authors' pages (dev-only test inputs, kept outside the repository). "Loads" means every pass the pack enables for +the overworld, Nether and End is preprocessed, translated and validated, as the game does when the pack is picked +(`java_pack::tests::real_packs_load` with `HORIZON_TEST_SHADERPACKS`); "drawn" means it was also picked in the game +and screenshotted. Only full-screen passes run (above), so no pack has its own terrain, water, shadows or sky yet. + +| Pack | Version | Result | First thing that stops it | +| --- | --- | --- | --- | +| BSL | v10.1.8 | drawn: 26 passes | | +| Complementary Reimagined | r5.9.3 | drawn: 27 passes | | +| Complementary Unbound | r5.8 | loads: 27 passes | | +| Sildur's Vibrant Extreme | 2.02 | drawn: 18 passes, only its sky (above) | | +| Steadfast | 0.8.0 | drawn: 3 passes | | +| Bliss | 2.1.2 | fails | `world0/deferred.vsh`: an operation naga forbids in a vertex shader | +| Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | +| Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | +| Photon | v1.4 | fails | `world0/prepare.vsh`: a struct varying (`CloudsParameters`) | +| Rethinking Voxels | r0.1-beta9 | fails | `world0/prepare.fsh`: `1 << 31` overflows naga's constant folding; it also needs images | + +What the translator does for these packs, as Iris (JCPP and its GLSL transformer) does: + +- **`#if` reads floats as JCPP does**: a float in a condition, written there or through a macro, counts as its + integer part, and an empty operand as 0. The same holds in `shaders.properties`, where Steadfast's + `#elif ATMOSPHERE_FOG_STRENGTH_NOON == 0.5` stopped the pack (`UnexpectedToken(Float(0.5))`). +- **A later `#define` replaces an earlier one** instead of failing (Bloop's `DefineRedefined`), and an unterminated + `#if` runs to the end of the file. +- **`shaders.properties`** keeps its empty lines and backslashes through the preprocessor, as Iris's does, so a + continued line doesn't swallow the next one. +- **16-bit and 8-bit types** (`float16_t`, `u16vec2`, `packFloat2x16`...), which Noble uses when the GPU reports + NVIDIA (`NV_gpu_shader5`), become their 32-bit types: WGSL has none. +- **What naga refuses**: `%` with a scalar and a vector operand goes through overloads, a `const` naga can't fold + (`mix`, `?:`, `smoothstep`) becomes a global set at the start of `main`, `sqrt` of a negative constant is + evaluated at run time, and a fragment output narrower than four channels (`out vec3`, Steadfast's `final`) is + written through a `vec4` with alpha 1 as OpenGL fills it. + ### Order to implement 1. **Translator crate** (`horizon-shaderpack`): the preprocessor (includes, option `#define`s with the player's From ac25d415784c69b3ca0fcd910317329a4daa55d3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:27:28 +0200 Subject: [PATCH 046/115] Shader Packs page: show the first line of a pack's error Translator errors go on with a drawn source excerpt that the row can't show. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/shader_packs.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index 052f64d26..7d628ef44 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -103,8 +103,11 @@ impl Game<'_> { } fn shader_pack_error(&mut self, id: &str, error: &str) { log::warn!("Horizon: shader pack {id}: {error}"); - // The Shader Packs page says why on the pack's row. - self.ui.options.shader_pack_error = Some((id.to_owned(), error.to_owned())); + // The Shader Packs page says why on the pack's row: the first line, + // since translator errors go on with a drawn source excerpt. + let first = error.lines().map(str::trim).find(|l| !l.is_empty()); + self.ui.options.shader_pack_error = + Some((id.to_owned(), first.unwrap_or(error).to_owned())); self.system_message(Text::literal(format!("Shader pack {id}: {error}"))); } } From 186777110f6c7996889726d90d02a80f8f0cf9fa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 00:22:26 +0000 Subject: [PATCH 047/115] Hoppers: skip the item scan when no item reaches the hopper's column HopperBlockEntity.suckInItems scanned every item entity for each hopper that ticked without a container above. During the block-entity pass the game now keeps the set of block columns item boxes reach; a hopper whose column is not in it has nothing to suck, and the scan (same order, same item taken) runs only for the rest. Items do not move within the pass: removals leave a superset, and additions (pushed at the end with a new id) or removing the last item rebuild the set. It is dropped at the end of the pass. 500 hoppers, 200 items: 1.36 -> 0.05 ms per tick 2000 hoppers, 500 items: 13.52 -> 0.26 ms per tick 2000 hoppers, 2000 items: 60.6 -> 3.3 ms per tick Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/game.rs | 3 + .../src/game/block_entity_ticks.rs | 3 + crates/horizon-client/src/game/machines.rs | 164 ++++++++++++++++++ 3 files changed, 170 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 56d37a3af..c87875e4d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1393,6 +1393,8 @@ struct Game<'a> { arrow_model: Option, tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + /// Where item entities are, while the block entities tick (hoppers). + item_columns: Option, creative_screen: Creative, control: Option, frame_stats: horizon_client::control::FrameStats, @@ -11381,6 +11383,7 @@ impl<'a> Game<'a> { arrow_model: prepared.arrow_model, tnts: Vec::new(), hoppers: HashMap::new(), + item_columns: None, creative_screen: prepared.creative_screen, control: None, frame_stats: Default::default(), diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index bb1cadd15..094aed6ef 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -24,6 +24,7 @@ impl Game<'_> { let ticking = self.block_ticking_area(); let mut spawners = Vec::new(); let mut trial_spawners = Vec::new(); + self.item_columns = Some(Default::default()); for slot in self.world.block_entity_tickers() { let pos = slot.0; // Ticks before this one can remove it (`TickingBlockEntity.isRemoved`). @@ -56,6 +57,8 @@ impl Game<'_> { _ => {} } } + // Items move between passes: the columns hold for this one only. + self.item_columns = None; self.update_song_volumes(); self.scan_for_hearts(); // The client ticks (particles, sounds, the turning mob) are for a diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index c05c7295f..8ce1940c9 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -327,6 +327,46 @@ impl Containers<'_> { } } +/// The block columns any item entity's box reaches, so that a hopper with +/// no item over it skips the scan of every item. Kept for one block-entity +/// pass, in which items do not move: removing one leaves a superset, still +/// right, and adding one (always pushed at the end, under a new id) or +/// removing the last rebuilds the columns. +#[derive(Default)] +pub(super) struct ItemColumns { + /// The item count and last item id when last asked, if built. + seen: Option<(usize, Option)>, + cells: horizon_client::fast_hash::FxHashSet<(i32, i32)>, +} +impl ItemColumns { + /// Whether an item's box may reach into column (x, z). + fn may_reach( + &mut self, + items: &[horizon_client::entities::ItemEntity], + x: i32, + z: i32, + ) -> bool { + let (len, last) = (items.len(), items.last().map(|i| i.id)); + let stale = self + .seen + .is_none_or(|(seen_len, seen_last)| len > seen_len || last != seen_last); + self.seen = Some((len, last)); + if stale { + self.cells.clear(); + for item in items { + let b = item.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + for cx in lo.x.floor() as i32..=hi.x.floor() as i32 { + for cz in lo.z.floor() as i32..=hi.z.floor() as i32 { + self.cells.insert((cx, cz)); + } + } + } + } + self.cells.contains(&(x, z)) + } +} + fn bone_meal() -> ItemStack { ItemStack { item: "minecraft:bone_meal".into(), @@ -648,6 +688,11 @@ impl Game<'_> { f64::from(pos.2) + 1.0, ], ); + if let Some(columns) = self.item_columns.as_mut() + && !columns.may_reach(&self.dropped, pos.0, pos.2) + { + return false; + } let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -880,3 +925,122 @@ impl Game<'_> { true } } + +#[cfg(test)] +mod item_column_tests { + use super::ItemColumns; + use horizon_client::{entities::ItemEntity, items::ItemStack}; + use horizon_core::geometry::Vec3; + + fn item(id: u32, x: f64, y: f64, z: f64) -> ItemEntity { + let at = Vec3::new(x, y, z); + ItemEntity { + health: 5, + fire_ticks: 0, + id, + stack: ItemStack::new("minecraft:stone", 1), + thrower: None, + position: at, + previous: at, + velocity: Vec3::ZERO, + on_ground: true, + age: 0, + pickup_delay: 0, + bob_offset: 0.0, + ticks: 0, + } + } + /// `hopper_suck`'s test: some item box meets the hopper's SUCK_AABB. + fn scan(items: &[ItemEntity], (x, y, z): (i32, i32, i32)) -> bool { + let (min, max) = ( + Vec3::new(f64::from(x), f64::from(y) + 11.0 / 16.0, f64::from(z)), + Vec3::new(f64::from(x) + 1.0, f64::from(y) + 2.0, f64::from(z) + 1.0), + ); + items.iter().any(|i| { + let b = i.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + lo.x < max.x + && hi.x > min.x + && lo.y < max.y + && hi.y > min.y + && lo.z < max.z + && hi.z > min.z + }) + } + + /// One tick of empty hoppers looking for items: each scans every item + /// (before) or asks the columns first (after, build included). + #[test] + #[ignore] + fn hopper_suck_cost() { + for (hoppers, count) in [(500i32, 200u32), (2000, 500), (2000, 2000)] { + let mut seed = 99u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let items: Vec = (0..count) + .map(|id| item(id, next(160.0), 64.0, next(160.0))) + .collect(); + let at: Vec<(i32, i32, i32)> = (0..hoppers) + .map(|_| (next(160.0) as i32, 63, next(160.0) as i32)) + .collect(); + let t = std::time::Instant::now(); + let a: Vec = at.iter().map(|&h| scan(&items, h)).collect(); + let before = t.elapsed().as_secs_f64() * 1e3; + let t = std::time::Instant::now(); + let mut columns = ItemColumns::default(); + let b: Vec = at + .iter() + .map(|&h| columns.may_reach(&items, h.0, h.2) && scan(&items, h)) + .collect(); + let after = t.elapsed().as_secs_f64() * 1e3; + assert_eq!(a, b); + println!("{hoppers} hoppers, {count} items: {before:.3} ms -> {after:.3} ms"); + } + } + + #[test] + fn no_hopper_with_an_item_over_it_is_skipped() { + let mut seed = 0x1234_5678_9abc_def1u64; + let mut next = |range: f64| { + seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1); + (seed >> 11) as f64 / (1u64 << 53) as f64 * range + }; + let mut items: Vec = Vec::new(); + let mut columns = ItemColumns::default(); + let mut next_id = 0; + let mut skipped = 0; + for round in 0..3000 { + // Items come and go as hoppers take them and crafters drop them. + match round % 5 { + 0 | 1 => { + next_id += 1; + // On edges too: a quarter of them sit on a block line. + let snap = |v: f64, edge: bool| if edge { v.floor() + 0.125 } else { v }; + let edge = round % 4 == 0; + items.push(item( + next_id, + snap(next(24.0) - 12.0, edge), + 64.0, + snap(next(24.0) - 12.0, edge), + )); + } + 2 if !items.is_empty() => { + let i = next(items.len() as f64) as usize; + items.remove(i); + } + _ => {} + } + let hopper = (next(26.0) as i32 - 13, 63, next(26.0) as i32 - 13); + let reach = columns.may_reach(&items, hopper.0, hopper.2); + let found = scan(&items, hopper); + assert!( + reach || !found, + "round {round}: skipped a hopper with an item over it" + ); + skipped += usize::from(!reach); + } + assert!(skipped > 1000, "skipped only {skipped}"); + } +} From 9019d708d0b49df09945213fe6e33246aa8b2dc0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 23:10:14 +0000 Subject: [PATCH 048/115] Streaming: answer "near a player?" from a grid of the players' squares On a server every player is an extra area, and streaming asks of every loaded and wanted column, several times a tick (unloading, dropping protos, finishing, decoration, the generation scan), whether one of those squares reaches it: a scan of every player's square per question. The squares are now one grid of distances, made again when a player changes chunk, and in_extra reads it. Differential test against the scan over 60 random layouts, every margin. At 50 players, 6081 columns, 3 questions each: 0.45 ms -> 0.04 ms, plus 0.02 ms to make the grid. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01UxXpf7d4RgpespL2G2UsGE --- crates/horizon-client/src/streaming.rs | 235 +++++++++++++++++++++++++ 1 file changed, 235 insertions(+) diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 858d05d30..49d1a052b 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -276,6 +276,8 @@ pub struct Streaming { /// chunks finish out to `radius + 1` (Chebyshev) and generation reaches /// past that as around the player. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, + /// `extra`'s squares as a grid, made again when `extra` changes. + cover: Option, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, } @@ -391,6 +393,7 @@ impl GenerationScan { radius: input.ranges.radius, extra: input.ranges.extra, forced: input.ranges.forced, + cover: input.ranges.cover, }; self.remember(ranges, input.world); } else { @@ -562,6 +565,7 @@ impl Streaming { meshed_total: 0, remote: false, extra: Vec::new(), + cover: None, mesh: true, } } @@ -808,6 +812,7 @@ impl Streaming { if self.paused { return (uploads, Vec::new()); } + ExtraCover::refresh(&mut self.cover, &self.extra); self.relight_edits(world); let deferred = std::mem::take(&mut self.deferred); let received = std::iter::from_fn(|| self.results.try_recv().ok()); @@ -982,6 +987,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; let (protos, generating) = (&self.protos, &self.generating); self.decoration_order.retain(|x, z| { @@ -1109,6 +1115,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }; self.waiting.retain(|&(x, sy, z)| { let back = ranges.in_view(x, z); @@ -1185,6 +1192,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), }, world, generating: &self.generating, @@ -1280,6 +1288,7 @@ impl Streaming { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: ExtraCover::matching(&self.cover, &self.extra), } } fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { @@ -1365,6 +1374,99 @@ struct Ranges<'a> { radius: i32, extra: &'a [((i32, i32), i32)], forced: &'a HashSet<(i32, i32)>, + /// `extra` as a grid, when one was made for it: `in_extra` without a + /// scan of every area. + cover: Option<&'a ExtraCover>, +} +/// For every column near the extra areas, how far it lies outside the +/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every +/// loaded and wanted column whether one reaches it, several times a tick: +/// with fifty players, a scan of fifty squares per question. +struct ExtraCover { + extra: Vec<((i32, i32), i32)>, + x0: i32, + z0: i32, + width: u32, + depth: u32, + cells: Box<[i8]>, +} +impl ExtraCover { + /// The largest margin the grid answers for; beyond it (and outside the + /// grid) a column is further than that from every square. + const REACH: i32 = 4; + /// The largest grid, in columns (a mebibyte). + const CELLS: u64 = 1 << 20; + fn matching<'a>( + cover: &'a Option, + extra: &[((i32, i32), i32)], + ) -> Option<&'a ExtraCover> { + cover.as_ref().filter(|c| c.extra == extra) + } + /// Make the grid again if `extra` changed; none for one area or none + /// (a scan is as quick), or areas too far apart. + fn refresh(cover: &mut Option, extra: &[((i32, i32), i32)]) { + if cover.as_ref().is_some_and(|c| c.extra == extra) { + return; + } + *cover = Self::new(extra); + } + fn new(extra: &[((i32, i32), i32)]) -> Option { + if extra.len() < 2 || extra.iter().any(|&(_, r)| !(0..=64).contains(&r)) { + return None; + } + let k = i64::from(Self::REACH); + let (mut x0, mut z0, mut x1, mut z1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN); + for &((x, z), r) in extra { + let (x, z, r) = (i64::from(x), i64::from(z), i64::from(r) + k); + (x0, z0, x1, z1) = (x0.min(x - r), z0.min(z - r), x1.max(x + r), z1.max(z + r)); + } + let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64); + if width * depth > Self::CELLS || x0 < i64::from(i32::MIN) || x1 > i64::from(i32::MAX) { + return None; + } + let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32); + let mut cells = vec![(Self::REACH + 1) as i8; (width * depth) as usize].into_boxed_slice(); + // Inside a square counts as 0: no margin asked for is below it. Each + // row of a square is a run of one value with a slope at either end. + let lower = |run: &mut [i8], v: i8| run.iter_mut().for_each(|c| *c = (*c).min(v)); + for &((cx, cz), r) in extra { + let reach = r + Self::REACH; + for dz in -reach..=reach { + let start = (cz + dz - z0) as usize * width as usize + (cx - x0) as usize; + let row = &mut cells[start - reach as usize..=start + reach as usize]; + let flat = dz.abs().max(r); + let centre = reach as usize; + lower( + &mut row[centre - flat as usize..=centre + flat as usize], + (flat - r) as i8, + ); + for d in flat + 1..=reach { + let v = (d - r) as i8; + lower(&mut row[centre - d as usize..=centre - d as usize], v); + lower(&mut row[centre + d as usize..=centre + d as usize], v); + } + } + } + Some(Self { + extra: extra.to_vec(), + x0, + z0, + width, + depth, + cells, + }) + } + /// Whether (x, z) is within `margin` of an area's square, for a + /// `margin` up to `REACH`. + fn within(&self, x: i32, z: i32, margin: i32) -> bool { + let (dx, dz) = ( + x.wrapping_sub(self.x0) as u32, + z.wrapping_sub(self.z0) as u32, + ); + dx < self.width + && dz < self.depth + && i32::from(self.cells[(dz * self.width + dx) as usize]) <= margin + } } impl Ranges<'_> { /// `distance`, or `rings` while the level loading screen is up. @@ -1441,6 +1543,11 @@ impl Ranges<'_> { /// Within `margin` of an extra area's square (Chebyshev distance, as /// vanilla's ticket levels spread). fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool { + if let Some(cover) = self.cover + && (0..=ExtraCover::REACH).contains(&margin) + { + return cover.within(x, z, margin); + } self.extra .iter() .any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin) @@ -1554,6 +1661,7 @@ mod tests { radius: self.radius, extra: &self.extra, forced: &self.forced, + cover: None, }, world: &self.world, generating: &self.generating, @@ -1866,6 +1974,7 @@ mod tests { radius, extra: &[], forced: &forced, + cover: None, }; let square = |x: i32, z: i32, n: i32| { (-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz))) @@ -1920,6 +2029,7 @@ mod tests { radius: 12, extra: &[], forced: &forced, + cover: None, }; let at = |dx: i32, dz: i32| (2 + dx, -1 + dz); let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading); @@ -1945,6 +2055,7 @@ mod tests { radius, extra: &[((radius * 2 + 9, 3), 4)], forced: &forced, + cover: None, }; let span = radius * 3 + 20; for x in -span..=span { @@ -1984,6 +2095,7 @@ mod tests { radius: 2, extra: &extra, forced: &forced, + cover: None, }; let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); for x in 40 - view - 8..=40 + view + 8 { @@ -2021,3 +2133,126 @@ mod tests { } } } + +#[cfg(test)] +mod cover_tests { + use super::*; + + fn areas(seed: &mut u64, n: usize, spread: i32) -> Vec<((i32, i32), i32)> { + let mut next = |m: i32| { + *seed ^= *seed << 13; + *seed ^= *seed >> 7; + *seed ^= *seed << 17; + (*seed % (2 * m as u64 + 1)) as i32 - m + }; + (0..n) + .map(|_| ((next(spread), next(spread)), 2 + next(14).abs())) + .collect() + } + + /// Every question streaming asks gets the same answer with the grid. + #[test] + fn the_grid_answers_as_the_scan() { + let mut seed = 0x9E37_79B9_7F4A_7C15u64; + let forced: HashSet<(i32, i32)> = [(40, -40)].into(); + for case in 0..60 { + let extra = areas(&mut seed, 2 + case % 20, [4, 30, 120][case % 3]); + let cover = ExtraCover::new(&extra).expect("a grid"); + let ranges = |cover| Ranges { + center: (3, -2), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + let (scan, grid) = (ranges(None), ranges(Some(&cover))); + let span = [4, 30, 120][case % 3] + 40; + for z in -span..=span { + for x in -span..=span { + for m in 0..=ExtraCover::REACH + 2 { + assert_eq!( + scan.in_extra(x, z, m), + grid.in_extra(x, z, m), + "case {case} ({x}, {z}) {m}" + ); + } + for d in [false, true] { + assert_eq!(scan.unloaded(x, z, d), grid.unloaded(x, z, d)); + assert_eq!(scan.requested(x, z, d), grid.requested(x, z, d)); + assert_eq!(scan.chunk_kept(x, z, d), grid.chunk_kept(x, z, d)); + } + } + } + } + } + + #[test] + fn a_stale_or_impossible_grid_is_not_used() { + let mut cover = None; + ExtraCover::refresh(&mut cover, &[((0, 0), 11), ((5, 5), 11)]); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 5), 11)]).is_some()); + assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 6), 11)]).is_none()); + // Too far apart for a mebibyte of grid, and one area alone: scans. + assert!(ExtraCover::new(&[((0, 0), 11), ((100_000, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((0, 0), 11)]).is_none()); + assert!(ExtraCover::new(&[((i32::MAX - 1, 0), 11), ((i32::MAX - 3, 0), 11)]).is_none()); + } + + /// cargo test --release -p horizon-client --lib cover_tests::cover_cost -- --ignored --nocapture + #[test] + #[ignore] + fn cover_cost() { + let forced = HashSet::new(); + for players in [10usize, 25, 50] { + // The benchmark's bots: most near spawn, a fifth flying outwards. + let extra: Vec<_> = (0..players) + .map(|i| { + let a = i as f64 * 2.399; + let d = if i % 5 == 0 { 30.0 } else { 3.0 }; + (((a.cos() * d) as i32, (a.sin() * d) as i32), 11) + }) + .collect(); + let cover = ExtraCover::new(&extra).unwrap(); + let ranges = |cover| Ranges { + center: (0, 0), + radius: 10, + extra: &extra, + forced: &forced, + cover, + }; + // The columns streaming asks about: everything kept, and the + // generation scan's ring past it. + let columns: Vec<(i32, i32)> = (-60..=60) + .flat_map(|z| (-60..=60).map(move |x| (x, z))) + .filter(|&(x, z)| { + ranges(None).requested(x, z, true) || !ranges(None).unloaded(x, z, true) + }) + .collect(); + let rounds = 100; + let time = |r: &Ranges| { + let t = std::time::Instant::now(); + let mut n = 0usize; + for _ in 0..rounds { + for &(x, z) in &columns { + n += usize::from(r.unloaded(x, z, true)); + n += usize::from(r.requested(x, z, true)); + n += usize::from(r.in_range(x, z, 1)); + } + } + std::hint::black_box(n); + t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds) + }; + let t = std::time::Instant::now(); + for _ in 0..rounds { + std::hint::black_box(ExtraCover::new(std::hint::black_box(&extra))); + } + let build = t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds); + println!( + "{players} players, {} columns, 3 questions each: scan {:.3} ms, grid {:.3} ms (+ {build:.3} ms to build)", + columns.len(), + time(&ranges(None)), + time(&ranges(Some(&cover))), + ); + } + } +} From cb4ecfbbe90d48f5a1036db9c35ea10244ea85db Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:15:36 +0200 Subject: [PATCH 049/115] A small fireball's fire is placed like vanilla's, and goes out SmallFireball.onHitBlock places fire with Level.setBlockAndUpdate and BaseFireBlock.getState (soul fire on soul soil and soul sand), and a mob's fireball only when mobGriefing is on. Horizon wrote a plain fire state straight into the chunk: no block updates and no scheduled fire tick, so the fire never aged and never went out, even on stone or nether bricks where vanilla's goes out within about half a minute (FireBlock.tick). Every blaze fireball that missed left a fire that stayed for good: fortress floors round a spawner filled with fire that kept everyone near it burning. The fire is now the level's fire state for the spot, set with updates (the fire's tick is scheduled on place), and only with mobGriefing when a mob shot it. lan_e2e `fireball`: a dispenser shoots a fire charge onto stone; both players see the fire and it goes out by itself (failed before: still burning after 1200 ticks; now out after about 480). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 5b7235c24bedf878a15f86322d386337b9ed8e95) --- crates/horizon-client/src/game/creatures.rs | 20 +++++++---- tools/lan_e2e.py | 37 +++++++++++++++++++-- 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 218d9e85c..ac846d2c4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2098,15 +2098,21 @@ impl Game<'_> { } }, Hit::Block { pos, face, .. } => { + // SmallFireball.onHitBlock: a mob's only with mobGriefing; + // BaseFireBlock.getState placed with updates (the fire + // ticks, ages and goes out where it can't stay). let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; - if self - .res - .facts() - .is_air(self.world.block(fire[0], fire[1], fire[2])) - && let Some(state) = - self.pack.assets.registry.default_state("minecraft:fire") + let mob = matches!(p.owner, Some(Who::Mob(_))); + if (!mob || self.ui.rules.bool("mob_griefing")) + && self + .res + .facts() + .is_air(self.world.block(fire[0], fire[1], fire[2])) { - self.world.set(fire[0], fire[1], fire[2], state)?; + let at = BlockPos::new(fire[0], fire[1], fire[2]); + let state = + self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at)); + self.level_set(fire, state)?; } } Hit::None => {} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..089149978 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -64,6 +64,8 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire + goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) - plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once the guest steps off (#848). - swings: each side sees the other's arm swing while it mines a block, and the guest sees its own @@ -111,7 +113,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1697,6 +1699,37 @@ def check_light(host, guest, out): return results +def check_fireball(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + fx, fz = x + 4, z + # A stone floor, a dispenser facing down three blocks over it, a fire charge in it, powered. + host('command', command=f'fill {fx - 2} {y - 1} {fz - 2} {fx + 2} {y - 1} {fz + 2} minecraft:stone') + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + host('command', command=f'setblock {fx} {y + 3} {fz} minecraft:dispenser[facing=down]') + host('command', command=f'item replace block {fx} {y + 3} {fz} container.0 with minecraft:fire_charge') + seen, gone = {}, None + try: + host('command', command=f'setblock {fx} {y + 4} {fz} minecraft:redstone_block') + host.wait(10) + seen = {'host': host.raw('block', fx, y, fz).get('block'), + 'guest': guest.raw('block', fx, y, fz).get('block')} + # FireBlock.tick every 30-39 ticks ages it by one a third of the time; past age 3 it goes. + for waited in range(40, 1240, 40): + host.wait(40) + if host.raw('block', fx, y, fz).get('block') == 'minecraft:air': + gone = waited + break + guest.wait(5) + seen['guest_after'] = guest.raw('block', fx, y, fz).get('block') + finally: + host('command', command=f'fill {fx - 2} {y} {fz - 2} {fx + 2} {y + 4} {fz + 2} minecraft:air') + assert seen.get('host') == 'minecraft:fire' and seen.get('guest') == 'minecraft:fire', \ + f'no fire where the fire charge landed: {seen}' + assert gone is not None, f'the fire on stone never went out (1200 ticks): {seen}' + assert seen['guest_after'] == 'minecraft:air', f'the guest still sees the fire: {seen}' + return {'out_after_ticks': gone, **seen} + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1712,7 +1745,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'fireball': check_fireball} def run(ctl, out, resources, checks): From ba72a097fa1370d36a63187f3b7a2f5952e01005 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 10:40:58 +0200 Subject: [PATCH 050/115] A player's blow turns a ghast's fireball back Player.attack on a #minecraft:redirectable_projectile (a ghast's fireball, a wind charge) deflects it with ProjectileDeflection.AIM_DEFLECT: its movement becomes the attacker's unit view vector and the attacker its owner, with the no-damage sound. The crosshair finds these projectiles a block round their box (AbstractHurtingProjectile.getPickRadius), a remote client sends the attack for them, and the host turns one a guest strikes along that guest's view. A fireball a player turned back kills the ghast it hits (Ghast.isReflectedFireball: no fire immunity, 1000 damage). lan_e2e.py --check deflect: the host strikes a caged ghast's fireball and the ghast dies; before, the fireball hit the host. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 6ba02f5205ba0f6ca2e68d4b0dfa53c86b768d82) --- crates/horizon-client/src/game.rs | 5 + crates/horizon-client/src/game/deflect.rs | 155 ++++++++++++++++++ crates/horizon-client/src/game/hand.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 16 ++ crates/horizon-client/src/game/remote.rs | 13 +- crates/horizon-client/src/mobs.rs | 9 +- tools/lan_e2e.py | 59 ++++++- 7 files changed, 253 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/game/deflect.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25e8fdeb..675504b1a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -34,6 +34,7 @@ mod crossbow; mod debug_keys; mod decorated_pot; mod dedicated; +mod deflect; mod dispense_fixture; mod dispenser; mod dragon; @@ -6829,6 +6830,10 @@ impl Game<'_> { self.break_painting(i, true); return true; } + // A ghast's fireball or a wind charge in front: turned back. + if self.attack_redirectable() { + return true; + } let hand_damage = 1.0 + self .held() diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs new file mode 100644 index 000000000..a08de87b3 --- /dev/null +++ b/crates/horizon-client/src/game/deflect.rs @@ -0,0 +1,155 @@ +//! A player's blow at a ghast's fireball or a wind charge +//! (`#minecraft:redirectable_projectile`): `Player.attack` turns it with +//! `ProjectileDeflection.AIM_DEFLECT` instead of hurting anything. It flies on +//! along the player's view and is the player's now (`Projectile.deflect` +//! sets the owner), so a ghast it meets dies of it (`Ghast.isReflectedFireball`). +use super::{Game, ray_box, view_vector}; +use horizon_client::{ + mobs::Who, + projectiles::{Projectile, ProjectileKind}, +}; +use horizon_core::geometry::{Aabb, Vec3}; + +/// `AbstractHurtingProjectile.getPickRadius`: the crosshair finds it a block +/// round its box. +const PICK_RADIUS: f64 = 1.0; + +/// `#minecraft:redirectable_projectile`: a ghast's fireball and both wind charges. +pub(super) fn redirectable(p: &Projectile) -> bool { + !p.stuck + && matches!( + p.kind, + ProjectileKind::LargeFireball { .. } + | ProjectileKind::WindCharge + | ProjectileKind::BreezeWindCharge + ) +} + +/// Its box for the crosshair: the entity's (a fireball 1 x 1, a wind charge +/// 0.3125, from its feet up) grown by the pick radius. +fn pick_box(p: &Projectile) -> Aabb { + let size = match p.kind { + ProjectileKind::LargeFireball { .. } => 1.0, + _ => 0.3125, + }; + let half = size / 2.0 + PICK_RADIUS; + Aabb::new( + Vec3::new( + p.position.x - half, + p.position.y - PICK_RADIUS, + p.position.z - half, + ), + Vec3::new( + p.position.x + half, + p.position.y + size + PICK_RADIUS, + p.position.z + half, + ), + ) +} + +impl Game<'_> { + /// The redirectable projectile under the crosshair within the attack + /// reach, and how far along the view it is. + pub(super) fn redirectable_hit(&self) -> Option<(usize, f64)> { + let eye = self.eye_position()?; + let dir = view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + self.creatures + .projectiles + .iter() + .enumerate() + .filter(|(_, p)| redirectable(p)) + .filter_map(|(i, p)| ray_box(eye, dir, reach, pick_box(p)).map(|t| (i, t))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + } + + /// `Player.attack` on a redirectable projectile nearer than any mob or + /// block in view: `AIM_DEFLECT` (its movement the unit view vector), the + /// player its owner, its acceleration power back to 0.1 + /// (`onDeflection` by an attack), and the no-damage sound. True when a + /// projectile was turned. + pub(super) fn attack_redirectable(&mut self) -> bool { + let Some((i, t)) = self.redirectable_hit() else { + return false; + }; + if self.mob_hit().is_some_and(|(_, d)| d < t) { + return false; + } + if let (Some(hit), Some(eye)) = (self.pick(), self.eye_position()) { + let d = (0..3) + .map(|a| (hit.point[a] - eye[a]).powi(2)) + .sum::() + .sqrt(); + if d < t { + return false; + } + } + self.deflect(i); + true + } + + /// `Player.canInteractWithEntity(box, 3.0)` as the server checks an + /// attack packet: the projectile's box within the reach plus 3 of the eyes. + pub(super) fn within_interaction_range(&self, i: usize) -> bool { + let (Some(eye), Some(p)) = (self.eye_position(), self.creatures.projectiles.get(i)) else { + return false; + }; + let b = pick_box(p); + let (lo, hi) = (b.min_position(), b.max_position()); + let (lo, hi) = ( + [lo.x + PICK_RADIUS, lo.y + PICK_RADIUS, lo.z + PICK_RADIUS], + [hi.x - PICK_RADIUS, hi.y - PICK_RADIUS, hi.z - PICK_RADIUS], + ); + let d2: f64 = (0..3) + .map(|a| (eye[a] - eye[a].clamp(lo[a], hi[a])).powi(2)) + .sum(); + let range = if self.creative { 5.0 } else { 3.0 } + 3.0; + d2 < range * range + } + + /// `Projectile.deflect(AIM_DEFLECT, player, player, true)`. + pub(super) fn deflect(&mut self, i: usize) { + let dir = view_vector(self.yaw, self.pitch); + let guest = self.lan_acting; + let p = &mut self.creatures.projectiles[i]; + p.velocity = Vec3::new(dir[0], dir[1], dir[2]); + p.yaw = dir[0].atan2(dir[2]).to_degrees() as f32; + p.pitch = dir[1].atan2(dir[0].hypot(dir[2])).to_degrees() as f32; + p.owner = Some(Who::Player); + // On a server, the guest who struck it (their projectile now). + p.guest = guest; + // Not into the one who turned it on its way out. + p.left_owner = false; + self.reset_attack_strength(); + self.swing_arm(); + let from = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + self.audio + .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_ghast_fireballs_and_wind_charges_are_redirectable() { + let at = Vec3::new(0.0, 64.0, 0.0); + let large = Projectile::fireball( + ProjectileKind::LargeFireball { power: 1 }, + at, + None, + [1.0, 0.0, 0.0], + ); + let small = Projectile::fireball(ProjectileKind::SmallFireball, at, None, [1.0, 0.0, 0.0]); + assert!(redirectable(&large)); + assert!(!redirectable(&small)); + // The pick box: a block round the fireball's 1 x 1 box. + let b = pick_box(&large); + assert_eq!(b.min_position().x, -1.5); + assert_eq!(b.max_position().y, 66.0); + } +} diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 84cea5a5c..a7218ff3c 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -156,6 +156,7 @@ impl Game<'_> { || before(self.dragon_hit().map(|h| h.1)) || before(self.mob_hit().map(|h| h.1)) || before(self.guest_hit().map(|h| h.1)) + || before(self.redirectable_hit().map(|h| h.1)) } /// `LocalPlayer.isHandsBusy`: paddling a boat. fn hands_busy(&self) -> bool { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1c38f9542..514b67723 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1127,6 +1127,22 @@ impl Game<'_> { } return; } + // A ghast's fireball or a wind charge: turned along the guest's own + // view (ServerGamePacketListenerImpl.handleInteract, then + // Player.attack's AIM_DEFLECT). + if let Some(i) = self + .creatures + .projectiles + .iter() + .position(|p| p.id != 0 && p.id as i32 == id && super::deflect::redirectable(p)) + { + self.as_guest(host, conn, |g| { + if g.within_interaction_range(i) { + g.deflect(i); + } + }); + return; + } let (old_yaw, old_pitch) = (host.hub.guests[gi].yaw, host.hub.guests[gi].pitch); if self.look_at_entity(host, gi, id).is_none() { return; diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 17c6e0299..42133a6bf 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3468,7 +3468,18 @@ impl Game<'_> { return true; } let mut instant = false; - if let Some((i, distance)) = self.mob_hit() + // A ghast's fireball or a wind charge nearer than any mob: the + // server turns it (game/deflect.rs). + if let Some((i, distance)) = self.redirectable_hit() + && self.mob_hit().is_none_or(|(_, d)| distance <= d) + && self.before_block(distance) + && self.creatures.projectiles[i].id != 0 + { + self.send(S::Attack(play::Attack { + id: self.creatures.projectiles[i].id as i32, + })); + self.reset_attack_strength(); + } else if let Some((i, distance)) = self.mob_hit() && self.before_block(distance) { self.send(S::Attack(play::Attack { diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index c8155984c..28bcadeed 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1623,13 +1623,18 @@ impl Mob { if !self.alive() || self.removed || self.invulnerable_flag { return false; } - if source.is_fire() && (self.kind.flags.fire_immune) { + // Ghast.isReflectedFireball: a fireball a player turned back is + // no fire to it, and kills it (Ghast.hurtServer: 1000 damage). + let reflected = &*self.kind.id == "minecraft:ghast" + && source.kind == DamageKind::Fireball + && source.attacker == Some(Who::Player); + if source.is_fire() && (self.kind.flags.fire_immune) && !reflected { return false; } if !ai::accepts_damage(self, &source, amount) { return false; } - let mut amount = amount; + let mut amount = if reflected { 1000.0 } else { amount }; if source.kind == DamageKind::FallingBlock && !species::body_slot(self.species()) && self.extra.head.is_some() diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..3940b3913 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -91,6 +91,7 @@ macOS both games render offscreen. Games started here have no audio (HORIZON_NO_ """ import argparse import json +import math import os import re import shutil @@ -111,7 +112,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'deflect', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1697,6 +1698,60 @@ def check_light(host, guest, out): return results +def check_deflect(host, guest, out): + """The host punches a ghast's fireball back: it flies along the host's view and kills the ghast + (Player.attack: AIM_DEFLECT on #redirectable_projectile; Ghast.isReflectedFireball). The ghast is caged + (a window toward the host); the game runs at 4 ticks a second, and once the fireball is within 4.5 blocks + the host looks at the ghast and clicks.""" + if SERVER_THREAD: + # The fireball's position and the host's hurts are read from the host's own level. + return 'skipped (in-frame only)' + x, y, z = (int(v // 1) for v in pos_of(host)) + guest('command', command='gamemode creative') + host('command', command='gamemode survival') + host('command', command='difficulty normal') + gx, gz = x, z + 30 + gy = y + 20 + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy - 1} {gz + 3} minecraft:glass') + host('command', command=f'fill {gx - 3} {gy} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + host('command', command=f'tp @s {gx + 0.5} {gy} {gz + 0.5} -90 0') + host.wait(20) + host.raw('hurtlog') + # The ghast in a glass cage it can't drift out of, a 3 x 3 window toward the host. + host('command', command=f'fill {gx + 13} {gy} {gz - 3} {gx + 19} {gy + 6} {gz + 3} minecraft:glass hollow') + host('command', command=f'fill {gx + 13} {gy + 2} {gz - 1} {gx + 13} {gy + 4} {gz + 1} minecraft:air') + host('command', command=f'summon minecraft:ghast {gx + 16.5} {gy + 1} {gz + 0.5}') + eye = (gx + 0.5, gy + 1.62, gz + 0.5) + host('command', command='tick rate 4') + turned, near, ghast, hurt = None, None, None, [] + try: + deadline = time.monotonic() + 120 + while time.monotonic() < deadline: + balls = [q for q in host.raw('status')['projectiles'] if q['kind'] == 'LargeFireball'] + near = min((math.dist(q['position'], eye) for q in balls), default=None) + if near is not None and near < 4.5: + g = [m['pos'] for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast')][0] + host.raw('look-at', f'{g[0]:.2f}', f'{g[1] + 2:.2f}', f'{g[2]:.2f}') + host.raw('mouse', 'left', 'down') + host.raw('mouse', 'left', 'up') + turned = near + break + host('command', command='tick rate 20') + host.wait(60) + ghast = [m for m in host.raw('mobs', 60).get('near', []) if m['kind'].endswith('ghast') and m['health'] > 0] + hurt = [h for pl in host.raw('hurtlog')['players'] if pl['name'] == 'host' for h in pl['hurts'] + if 'fireball' in h['source'] or 'explosion' in h['source']] + finally: + host('command', command='tick rate 20') + host('command', command='kill @e[type=minecraft:ghast]') + host('command', command=f'fill {gx - 3} {gy - 1} {gz - 3} {gx + 24} {gy + 8} {gz + 3} minecraft:air') + guest('command', command='gamemode survival') + assert turned is not None, f'no fireball came within 4.5 blocks (nearest {near})' + assert not hurt, f'the host was hit: {hurt}' + assert not ghast, f'the ghast lived: the fireball was not turned back ({ghast})' + return {'struck_at': round(turned, 2)} + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1712,7 +1767,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'deflect': check_deflect} def run(ctl, out, resources, checks): From 8df160f63fc03377f9c9a617552f224f0e1340bb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 11:37:16 +0200 Subject: [PATCH 051/115] Piglins throw their barter toward the nearest player, guests included PiglinAi.throwItemsTowardPlayer aims at NEAREST_VISIBLE_PLAYER: the nearest living, non-spectator player within 16 blocks. Only the host was considered, so a LAN guest who bartered saw the loot fly to the host. lan_e2e's new barter check: the guest, in gold boots, drops a gold ingot to a piglin in a glass corridor with the host on the far side; the piglin stays calm and the barter reaches the guest. It fails on the old build (the loot lands on the host's side). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 896f12f7321852bf8e654d466c51692db59882c9) --- crates/horizon-client/src/game/piglins.rs | 27 +++++++++-- tools/lan_e2e.py | 59 ++++++++++++++++++++++- 2 files changed, 79 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 9df5311aa..6280959d8 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -6,7 +6,7 @@ use horizon_client::{ items::ItemStack, mobs::{Species, Who, piglin::ADMIRE}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { @@ -132,12 +132,29 @@ impl Game<'_> { } else { vec![ItemStack::new(&item, 1)] }; - // BehaviorUtils.throwItem toward the nearest visible player, else nearby. - let target = self + // BehaviorUtils.throwItem toward the nearest visible player + // (NEAREST_VISIBLE_PLAYER: within 16, alive, no spectators; the + // guests count as much as the host), else nearby. + let at = m.position; + let host = self .player .as_ref() - .filter(|p| p.position.distance_squared(m.position) < 256.0) - .map(|p| [p.position.x, p.position.y + 1.0, p.position.z]); + .filter(|p| !p.health.dead_or_dying() && !self.spectator()) + .map(|p| [p.position.x, p.position.y, p.position.z]); + let guests = self.lan.iter().flat_map(|h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.position) + }); + let d = |p: &[f64; 3]| at.distance_squared(Vec3::new(p[0], p[1], p[2])); + let target = host + .into_iter() + .chain(guests) + .filter(|p| d(p) < 256.0) + .min_by(|a, b| d(a).total_cmp(&d(b))) + .map(|p| [p[0], p[1] + 1.0, p[2]]); for stack in items { let to = target.unwrap_or_else(|| { let r = &mut self.world.random; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..914526af0 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -111,7 +111,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'barter', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1697,6 +1697,61 @@ def check_light(host, guest, out): return results +def check_barter(host, guest, out): + """The guest, in gold boots, drops a gold ingot to a piglin: the piglin stays calm, takes it, and throws its + barter toward the nearest player, the guest (PiglinAi.throwItemsTowardPlayer: NEAREST_VISIBLE_PLAYER), who + picks it up. The host is nearby on the other side, so a barter thrown at the host misses the guest. A glass + corridor (the hollow box) keeps the piglin between them.""" + x, y, z = (int(v // 1) for v in pos_of(host)) + cz = z + 4 + host('command', command='gamemode creative') + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:glass hollow') + host('command', command=f'fill {x + 2} {y - 1} {cz} {x + 7} {y - 1} {cz} minecraft:stone') + host('command', command=f'tp @s {x - 0.5} {y} {cz + 0.5} -90 0') + guest('command', command=f'tp @s {x + 7.3} {y} {cz + 0.5} 90 30') + guest('command', command='item replace entity @s armor.feet with minecraft:golden_boots') + guest('command', command='give @s minecraft:gold_ingot 1') + host('command', command=f'summon minecraft:piglin {x + 4.5} {y} {cz + 0.5} {{IsImmuneToZombification:1b}}') + guest.wait(20) + before = remote(guest)['health'] + kept = dict(guest('inventory')['counts']) + try: + guest.raw('select', 'minecraft:gold_ingot') + guest.raw('key', 'q', 'tap') + bought, trace = {}, [] + for _ in range(20): + guest.wait(20) + trace.append([(e['type'].split(':')[-1], round(e['pos'][0] - x, 1), round(e['pos'][2] - cz, 1)) + for e in host.raw('entities', 24)['entities'] if e['type'] in ('minecraft:item', 'minecraft:piglin')]) + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + if bought: + guest.wait(40) + break + counts = guest('inventory')['counts'] + bought = {k: n - kept.get(k, 0) for k, n in counts.items() + if k not in ('minecraft:gold_ingot', 'minecraft:golden_boots') and n > kept.get(k, 0)} + piglins = [m for m in host.raw('mobs', 20).get('near', []) if m['kind'].split(':')[-1] == 'piglin'] + health = remote(guest)['health'] + finally: + host('command', command=f'kill @e[type=minecraft:piglin,x={x},y={y - 2},z={cz - 2},dx=10,dy=6,dz=4]') + # What lies on the floor, on the host's side of the piglin's start and on the guest's. + floor = [host('command', command=f'kill @e[type=minecraft:item,x={x0},y={y - 2},z={cz - 3},dx={dx},dy=6,dz=6]') + ['chat'][0] for x0, dx in ((x - 2, 6.5), (x + 4.5, 6))] + host('command', command=f'fill {x + 1} {y - 1} {cz - 1} {x + 8} {y + 2} {cz + 1} minecraft:air') + host('command', command=f'fill {x - 8} {y - 1} {z - 8} {x + 8} {y - 1} {z + 8} minecraft:stone') + guest('command', command='clear @s') + host('command', command='gamemode survival') + assert piglins, 'the piglin is gone' + assert health >= before, f'the piglin hurt the guest in gold boots: {before} -> {health}' + assert bought, f'no barter reached the guest (on the floor, host side then guest side: {floor}; items and the piglin, every second: {trace})' + return {'bought': bought, 'floor': floor} + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1712,7 +1767,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'barter': check_barter} def run(ctl, out, resources, checks): From 73c5a1c5d65474b485566c3666e0d964e07da102 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 00:33:23 +0200 Subject: [PATCH 052/115] Explosions hurt and push every player, through a raised shield ServerExplosion.hurtEntities takes every entity in range, players included, but only the host player was hurt and pushed: LAN guests stood in a blast untouched. The player's part is now its own function, run for the host and then for each guest in the level, swapped in as the player. It also follows Player.hurtServer more closely for everyone: the damage goes through a raised shield (an explosion is blocked like any attack from where the blast is, the shield takes wear), the push is reduced by explosion knockback resistance, and a spectator or a creative player flying is not pushed. tools/lan_e2e.py gains a `blast` check: primed TNT five blocks from a survival guest hurts it (20 -> 4.6) and pushes it away; facing it behind a raised shield, the guest takes nothing. Before this change the guest took no damage and no push. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 0782a598fee9b6de75d367eb11734267df3c7fd4) --- crates/horizon-client/src/game/explosion.rs | 162 ++++++++++++++------ tools/lan_e2e.py | 57 ++++++- 2 files changed, 167 insertions(+), 52 deletions(-) diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 55babd9af..5cf67f586 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -226,6 +226,102 @@ impl Game<'_> { } /// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT); /// the player takes `damage_type`. + /// `ServerExplosion.hurtEntities` for the player: damage scaled by + /// distance and exposure, through a raised shield (`hurtServer` blocks + /// explosions like any attack from where the blast is), then the push + /// (less with explosion knockback resistance; none for spectators or a + /// creative player flying). + pub(super) fn explosion_hurt_player( + &mut self, + center: [f64; 3], + radius: f32, + damage_type: &str, + exploding: Option, + ) { + let diameter = f64::from(radius * 2.0); + // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per level and + // piece, so two Blast Protection IV pieces cancel it). + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let Some(p) = self.player.as_ref() else { + return; + }; + let feet = [p.position.x, p.position.y, p.position.z]; + let dist = ((feet[0] - center[0]).powi(2) + + (feet[1] - center[1]).powi(2) + + (feet[2] - center[2]).powi(2)) + .sqrt() + / diameter; + if dist > 1.0 || p.health.dead_or_dying() { + return; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0], + feet[1] + f64::from(p.dimensions.eye_height), + feet[2], + ]; + let exposure = self.seen_percent( + center, + [feet[0] - w, feet[1], feet[2] - w], + [feet[0] + w, feet[1] + h, feet[2] + w], + ); + let pow = (1.0 - dist) * f64::from(exposure); + let amount = ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32; + let d = [eye[0] - center[0], eye[1] - center[1], eye[2] - center[2]]; + let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + let dir = if l < 1.0e-4 { + [0.0; 3] + } else { + [d[0] / l, d[1] / l, d[2] / l] + }; + let power = pow * (1.0 - resistance); + // `source.doTeamsAllowDamage(entity)`. + let hurtable = exploding.is_none_or(|id| { + horizon_client::scoreboard::teams_allow_damage(self.mob_team(id), self.player_team()) + }); + let blocking = self.player_blocking(Some(center), damage_type, false); + let raised = blocking.is_some(); + let (creative, spectator) = (self.creative, self.spectator()); + let flying = self.player.as_ref().is_some_and(|p| p.flying); + let mut outcome = horizon_client::health::BlockOutcome::default(); + if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(damage_type) + { + // Creative players are invulnerable to explosions. + if !creative + && !spectator + && hurtable + && let Ok(o) = p.hurt_blocking( + &self.motion.health, + self.world.health_rules, + id, + amount, + blocking, + ) + { + outcome = o; + } + if !spectator && !(creative && flying) { + p.velocity = Vec3::new( + p.velocity.x + dir[0] * power, + p.velocity.y + dir[1] * power, + p.velocity.z + dir[2] * power, + ); + } + } + if outcome.hurt && !creative { + self.hurt_armor(amount); + } + if raised { + self.after_block(outcome, amount, None, false); + } + } + fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) { if radius < 1.0e-5 { return; @@ -261,57 +357,23 @@ impl Game<'_> { horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim) }) }; - let player_hurtable = teams_allow(self, self.player_team()); - // Player. - if let Some(p) = self.player.as_ref() { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - if dist <= 1.0 && !p.health.dead_or_dying() { - let w = f64::from(p.dimensions.width) / 2.0; - let h = f64::from(p.dimensions.height); - let eye = [ - feet[0], - feet[1] + f64::from(p.dimensions.eye_height), - feet[2], - ]; - let exposure = self.seen_percent( - center, - [feet[0] - w, feet[1], feet[2] - w], - [feet[0] + w, feet[1] + h, feet[2] + w], - ); - let amount = damage(dist, exposure); - let dir = direction(eye); - let mut hurt = false; - let creative = self.creative; - if let Some(p) = self.player.as_mut() - && let Some(id) = self.motion.health.damage.id(damage_type) - { - // Creative players are invulnerable to explosions. - if !creative && player_hurtable { - hurt = p - .hurt(&self.motion.health, self.world.health_rules, id, amount) - .unwrap_or(false); - } - // Blast protection: `EXPLOSION_KNOCKBACK_RESISTANCE` (0.15 per - // level and piece, so two Blast Protection IV pieces cancel it). - let resistance = p - .attribute("minecraft:explosion_knockback_resistance") - .unwrap_or(0.0); - let power = (1.0 - dist) * f64::from(exposure) * (1.0 - resistance); - // `hitPlayers` skips creative players who are flying: the - // client gets no knockback in the explode packet. - if !(creative && p.flying) { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - } - } - if hurt && !self.creative { - self.hurt_armor(amount); - } + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. + self.explosion_hurt_player(center, radius, damage_type, exploding); + if let Some(mut host) = self.lan.take() { + let guests: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in guests { + self.guest_hit_by(&mut host, conn, |g| { + g.explosion_hurt_player(center, radius, damage_type, exploding); + }); } + self.lan = Some(host); } // Mobs. let mut mobs = std::mem::take(&mut self.mobs); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..eb2437db5 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -64,6 +64,9 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- blast: primed TNT going off beside a guest in survival hurts the guest and pushes it away + (ServerExplosion.hurtEntities takes every player); facing it behind a raised shield, the + guest takes nothing. - plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once the guest steps off (#848). - swings: each side sees the other's arm swing while it mines a block, and the guest sees its own @@ -111,7 +114,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'blast', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1584,6 +1587,56 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_blast(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command='gamemode creative') + x, y, z = (int(v // 1) for v in pos_of(host)) + gx, gz = x + 6, z + floor = f'fill {gx - 6} {y - 1} {gz - 4} {gx + 6} {y - 1} {gz + 4} minecraft:bedrock' + detail = {} + try: + for shielded in (False, True): + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + host('command', command=floor) + host('command', command=f'fill {gx - 6} {y} {gz - 4} {gx + 6} {y + 3} {gz + 4} minecraft:air') + guest('command', command=f'tp @s {gx + 0.5} {y} {gz + 0.5}') + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + hold = None + if shielded: + guest('command', command='item replace entity @s weapon.offhand with minecraft:shield') + guest.wait(5) + guest.raw('look-at', gx + 5.5, y + 0.5, gz + 0.5) + hold = threading.Thread(target=guest.raw, args=('use-item', '--hold', 2.5)) + hold.start() + time.sleep(0.5) + before = remote(guest)['health'] + at = pos_of(guest) + # Five blocks off: a blast that hurts without killing (about 14 at full exposure). + host('command', command=f'summon minecraft:tnt {gx + 5.5} {y} {gz + 0.5} {{fuse:10s}}') + # The guest's own controller is busy holding the shield up: the host waits. + host.wait(14) + after = remote(guest)['health'] + moved = pos_of(guest) + if hold: + hold.join() + guest.shot(out, f'blast-{"shield" if shielded else "open"}') + detail['shield' if shielded else 'open'] = { + 'before': before, 'after': after, 'pushed': round(at[0] - moved[0], 2)} + finally: + host('command', command='gamemode survival') + guest('command', command='clear @s') + host('command', command=floor) + open_, shield = detail['open'], detail['shield'] + assert open_['after'] < open_['before'], f'the blast never hurt the guest: {detail}' + assert open_['pushed'] > 0, f'the blast never pushed the guest away: {detail}' + assert shield['after'] >= shield['before'], f'the shield did not stop the blast: {detail}' + return detail + + def light_differences(host, guest, lo, hi): """Positions of the box loaded on both sides, and those whose sky or block light differ.""" h, g = host.raw('light', *lo, *hi), guest.raw('light', *lo, *hi) @@ -1709,7 +1762,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, - 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, + 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, 'time': check_time, 'growth': check_growth} From 67569ef98423c6bdf65784b2715d139ea7f3204f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 09:15:36 +0200 Subject: [PATCH 053/115] A LAN guest's worn armour protects it The hub's players are server players too, and in vanilla the armour they wear counts against every hit (LivingEntity.collectEquipmentChanges puts each piece's attribute modifiers on the player, getDamageAfterArmorAbsorb reads them). Horizon only put them on the host: a guest who put armour on in its inventory menu (the hub moves it), joined wearing it, respawned with it kept or came through a portal (a new body each time) was hurt as if it wore nothing. Iron armour, 15 points, should take a 10-damage blow down to 6; a guest took the full 10. Each guest now keeps its own list of applied equipment modifiers, swapped in with the rest of its state for its turn, and its armour and main hand are put on its attributes whenever they differ from what they were put on for (a new body starts with none). lan_e2e `worn`: the guest shift-clicks iron armour on in its inventory and takes 10 mob-attack damage: 6 with it, 10 without (failed before: 10 and 10). Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e0549f88cebfe20625f66dd04348252cef6cea6c) --- crates/horizon-client/src/game/lan_actions.rs | 29 ++++++++- tools/lan_e2e.py | 63 ++++++++++++++++++- 2 files changed, 89 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1c38f9542..48ecb86b6 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -64,6 +64,12 @@ pub(super) struct GuestPlay { xp_delay: u32, /// What last killed the guest outright (`/kill`): the death message's key. death_cause: Option, + /// The equipment modifiers on the guest's attributes (`apply_equipment`) + /// and the armour and main hand they were put on for: the hub's player + /// is a `ServerPlayer` too, whose worn armour counts + /// (`LivingEntity.collectEquipmentChanges`). + modifiers: Vec<(String, String)>, + equipped: Option>>, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -130,6 +136,8 @@ pub(super) struct GuestSwap { swings: u32, /// How many projectiles there were: those added since are the guest's. projectiles: usize, + /// The host's equipment modifiers. + modifiers: Vec<(String, String)>, } impl GuestPlay { @@ -193,7 +201,8 @@ impl Game<'_> { return None; } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; - if host.hub.guests[i].motion.is_none() { + let fresh = host.hub.guests[i].motion.is_none(); + if fresh { let p = Vec3::new( host.hub.guests[i].position[0], host.hub.guests[i].position[1], @@ -207,6 +216,10 @@ impl Game<'_> { } } let mut play = host.play.remove(&conn).unwrap_or_default(); + if fresh { + // A new body (joined, respawned, changed level): nothing on it yet. + play.equipped = None; + } let g = &mut host.hub.guests[i]; // The guest's body. let Some(mut motion) = g.motion.take() else { @@ -310,6 +323,17 @@ impl Game<'_> { let packets = std::mem::take(&mut self.guest_packets); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); + let modifiers = std::mem::replace( + &mut self.applied_modifiers, + std::mem::take(&mut play.modifiers), + ); + // Its worn armour on its attributes, when it changed. + let mut equipped: Vec> = self.armor.to_vec(); + equipped.push(self.inventory.get(self.selected).cloned().flatten()); + if play.equipped.as_ref() != Some(&equipped) { + self.apply_equipment(); + play.equipped = Some(equipped); + } Some(GuestSwap { conn, i, @@ -355,6 +379,7 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, }) } @@ -406,7 +431,9 @@ impl Game<'_> { packets, swings, projectiles, + modifiers, } = swap; + play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers); // What the guest shot is theirs (Projectile.setOwner). for p in self.creatures.projectiles.iter_mut().skip(projectiles) { if p.owner == Some(horizon_client::mobs::Who::Player) && p.guest.is_none() { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..cc96e6540 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -64,6 +64,8 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- worn: iron armour the guest puts on in its inventory protects it: a 10-damage blow takes 6 + (armour 15, LivingEntity.getDamageAfterArmorAbsorb), and the full 10 without it. - plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once the guest steps off (#848). - swings: each side sees the other's arm swing while it mines a block, and the guest sees its own @@ -111,7 +113,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1697,6 +1699,63 @@ def check_light(host, guest, out): return results +def check_worn(host, guest, out): + pieces = ['iron_helmet', 'iron_chestplate', 'iron_leggings', 'iron_boots'] + guest('command', command='gamemode survival') + taken = {} + try: + for worn in (False, True): + guest('command', command='clear @s') + if remote(guest)['health'] <= 0: + guest.raw('respawn') + guest.wait(40) + if worn: + for piece in pieces: + guest('command', command=f'give @s minecraft:{piece}') + guest.wait(10) + # Shift-clicked from the hotbar onto the body in the inventory menu (the hub moves them). + guest.raw('key', 'e', 'tap') + guest.raw('wait-for', 'screen', 'inventory') + for piece in pieces: + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{piece}'), 'shift') + guest.wait(2) + guest.raw('key', 'esc', 'tap') + guest.wait(5) + guest('command', command='effect give @s minecraft:instant_health 1 5') + guest.wait(30) + before = remote(guest)['health'] + if not SERVER_THREAD: + host.raw('hurtlog') + # A mob's blow (no attacker: no difficulty scaling); armour counts against it. + guest('command', command='damage @s 10 minecraft:mob_attack') + if SERVER_THREAD: + # The server's hurt log isn't on a control socket here: the health the guest is + # sent, read as soon as it drops (natural regeneration heals it again after). + health = before + for _ in range(40): + guest.wait(1) + health = remote(guest)['health'] + if health < before: + break + taken['worn' if worn else 'bare'] = [round(before - health, 2)] + continue + guest.wait(10) + log = [h for p in host.raw('hurtlog')['players'] if p['name'] == GUEST_NAME for h in p['hurts']] + taken['worn' if worn else 'bare'] = [(h['amount'], h['armor'], round(h['taken'], 2)) for h in log] + finally: + guest('command', command='clear @s') + guest('command', command='effect give @s minecraft:instant_health 1 5') + if SERVER_THREAD: + # Natural regeneration may heal up to a point before the health arrives. + assert len(taken['bare']) == 1 and 9.0 <= taken['bare'][0] <= 10.0, f'10 damage on no armour: {taken}' + assert len(taken['worn']) == 1 and 5.0 <= taken['worn'][0] <= 6.0, \ + f'10 damage through iron armour (15) should take 6: {taken}' + return taken + assert taken['bare'] == [(10.0, 0.0, 10.0)], f'10 damage on no armour: {taken}' + assert taken['worn'] == [(10.0, 15.0, 6.0)], f'10 damage through iron armour (15) should take 6: {taken}' + return taken + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1712,7 +1771,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'worn': check_worn} def run(ctl, out, resources, checks): From def242ecc1703b23e493034517e683fff3d55dff Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:34:42 +0200 Subject: [PATCH 054/115] A mob a guest kills is the guest's kill LivingEntity.die credits the kill to lastHurtByPlayer: the killed statistic, the mob_kills custom statistic, the kill score criteria and the player_killed_entity trigger belong to that player. Horizon kept only whether a player had hurt the mob, and the death ran as the host, so a LAN or server guest's kills counted in the host's statistics and advancements. The mobs a player hurt now remember which player (the acting guest's connection, or the host), and the killer's side of the death runs as that guest. lan_e2e `kills`: a pig the guest kills shows in the guest's minecraft.killed:minecraft.pig score, not the host's. Part of #484 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 9 +++-- crates/horizon-client/src/game/creatures.rs | 35 +++++++++++++++---- .../horizon-client/src/game/sculk_fixture.rs | 2 +- crates/horizon-client/src/game/wind.rs | 2 +- tools/lan_e2e.py | 35 +++++++++++++++++-- 5 files changed, 69 insertions(+), 14 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25e8fdeb..1d91c2d08 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1236,7 +1236,9 @@ struct Game<'a> { /// swap just before an attack keeps them, with the new item's enchantments /// (attribute swapping). attack_item: Option>, - last_hurt_by_player: HashSet, + /// Mobs a player hurt (`LivingEntity.lastHurtByPlayer`), with the guest + /// it was by connection (None: the host). + last_hurt_by_player: HashMap>, /// Mobs whose death (`LivingEntity.die`) has been handled. died: HashSet, /// Client-ticked block-entity animation state (`game/block_entity_anims.rs`). @@ -6937,7 +6939,8 @@ impl Game<'_> { (actual * 0.5) as u32, ); } - self.last_hurt_by_player.insert(self.mobs[index].id); + self.last_hurt_by_player + .insert(self.mobs[index].id, self.lan_acting); let sound = if crit { "minecraft:entity.player.attack.crit" } else if scale > 0.9 { @@ -11323,7 +11326,7 @@ impl<'a> Game<'a> { raiding: Default::default(), attack_ticks: 100, attack_item: None, - last_hurt_by_player: HashSet::new(), + last_hurt_by_player: HashMap::new(), died: HashSet::new(), be_anims: { let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 218d9e85c..ca34efb9f 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -622,7 +622,8 @@ impl Game<'_> { } /// LivingEntity.die / dropAllDeathLoot. fn mob_died(&mut self, m: &Mob) { - let by_player = self.last_hurt_by_player.remove(&m.id) || m.ai.last_hurt_by_player > 0; + let killer = self.last_hurt_by_player.remove(&m.id); + let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0; let mut dying = m.clone(); // LivingEntity.die: the death is heard, and a sculk catalyst nearby // takes the experience (before the loot is dropped). @@ -636,11 +637,22 @@ impl Game<'_> { } }); if by_player { - self.stats.add("killed", &m.kind.id, 1); - self.stats.custom("mob_kills", 1); - self.score_player_killed(super::commands::Target::Mob(m.id)); - let view = self.mob_entity(m); - self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + // A guest's kill is theirs: their statistics, scores and + // advancements (LivingEntity.die credits lastHurtByPlayer). + let guest = killer.flatten().filter(|_| self.lan_acting.is_none()); + let credited = guest.is_some_and(|conn| { + let Some(mut host) = self.lan.take() else { + return false; + }; + let done = self + .as_guest(&mut host, conn, |g| g.credit_kill(m)) + .is_some(); + self.lan = Some(host); + done + }); + if !credited { + self.credit_kill(m); + } } self.score_entity_removed(m.id); self.raider_died(m, by_player); @@ -675,6 +687,15 @@ impl Game<'_> { } } } + /// The killer's side of a mob's death: `ServerPlayer.awardKillScore`'s + /// statistics and scores, and the `player_killed_entity` trigger. + fn credit_kill(&mut self, m: &Mob) { + self.stats.add("killed", &m.kind.id, 1); + self.stats.custom("mob_kills", 1); + self.score_player_killed(super::commands::Target::Mob(m.id)); + let view = self.mob_entity(m); + self.trigger_entity("minecraft:player_killed_entity", "entity", &view); + } /// `dropAllDeathLoot` through `mobs::drops`: the entity loot table from the /// world's random sequence, equipment by drop chance, species extras and /// the experience orbs, spawned in order. @@ -1973,7 +1994,7 @@ impl Game<'_> { .find(|m| m.id == id) .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } hurt } diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 890e571b8..d71cd5431 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -665,7 +665,7 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { m.damage(amount, horizon_client::mobs::Damage::player(at)); } - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } "set" => { let n = |i: usize| words[i].parse::().unwrap_or(0); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 355b5b877..72e6ee0e8 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -131,7 +131,7 @@ impl Game<'_> { m.damage(1.0, source); } if p.owner == Some(Who::Player) { - self.last_hurt_by_player.insert(id); + self.last_hurt_by_player.insert(id, self.lan_acting); } } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..8cf0df7df 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,7 @@ address. The script then checks, from both sides, what a guest's game used to ge drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; +- kills: a pig the guest kills counts in the guest's killed statistic, not the host's (#484); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -111,7 +112,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -613,6 +614,36 @@ def check_pvp(host, guest, out): return hits +def check_kills(host, guest, out): + # A mob the guest kills is the guest's kill (#484): LivingEntity.die credits lastHurtByPlayer, so the + # killed statistic (and its scoreboard criterion) counts for the guest, not the host. + host('command', command='scoreboard objectives add parity_kills minecraft.killed:minecraft.pig') + for g in (host, guest): + g('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + try: + # Between the two, in front of the guest, with one health left. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz:.2f} {{NoAI:1b,Health:1.0f}}') + guest.wait(30) + guest.raw('look-at', f'{hx + 1.5:.2f}', f'{hy + 0.5:.2f}', f'{hz:.2f}') + guest.wait(10) + guest.raw('attack') + guest.wait(20) + host('command', command=f'scoreboard players get {GUEST_NAME} parity_kills') + host('command', command=f'scoreboard players get {host.player} parity_kills') + host.wait(10) + chat = host.raw('messages', 10)['chat'] + guest.shot(out, 'kills') + finally: + host('command', command='kill @e[type=minecraft:pig]') + host('command', command='scoreboard objectives remove parity_kills') + assert any(f'{GUEST_NAME} has 1 [parity_kills]' in line for line in chat), f"the guest's kill is not theirs: {chat}" + assert not any(f'{host.player} has 1 [parity_kills]' in line for line in chat), f"the host got the guest's kill: {chat}" + return chat + + def dead_players(game, want, ticks=60): """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" for _ in range(ticks // 5): @@ -1712,7 +1743,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'kills': check_kills} def run(ctl, out, resources, checks): From 5763854b0d97e2a9e3f94d216d985f20719b86ce Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:32:30 +0200 Subject: [PATCH 055/115] A player's arrow hurts the other players on a served world A remote player's projectiles never hit other players: a player's shots only looked for mobs and the host, a guest's flew as if the host had shot it (so it could not hit the host until it left the host's box), and a hit on a guest from another guest ran as the shooter, who has no hub to reach the victim. No bow PvP on a server or between LAN players. A player's arrows, snowballs and eggs now meet every player, a guest's flying from that guest (Projectile.getOwner). A hit on another player runs as the victim's hurt, refused when the pvp game rule is off or the teams are allies without friendly fire (ServerPlayer.canHarmPlayer), which turns the arrow back as a raised shield does (AbstractArrow.onHitEntity). Pearls, potions and wind charges fly past players as before. lan_e2e `arrows`: the guest shoots the host and the host the guest with a bow, both hurt; with pvp off, no harm. Part of #484 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/combat.rs | 3 + crates/horizon-client/src/game/creatures.rs | 26 ++++- crates/horizon-client/src/game/lan_pvp.rs | 102 +++++++++++++++++++- tools/lan_e2e.py | 38 +++++++- 4 files changed, 164 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index da3851d9a..70ae082aa 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -25,6 +25,9 @@ pub(super) struct CombatTracker { pub(super) last_hurt_mob: Option<(u32, i64)>, /// The mob whose projectile is hitting the player now. pub(super) projectile_owner: Option, + /// The projectile hitting the player now is another player's that + /// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally). + pub(super) refuse_player_hit: bool, /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 218d9e85c..f67a7960a 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -1393,7 +1393,8 @@ impl Game<'_> { from: [f64; 3], damage_type: &str, ) -> bool { - if self.creative { + // ServerPlayer.canHarmPlayer refused another player's projectile. + if self.creative || self.combat.refuse_player_hit { return false; } let projectile = self @@ -1631,14 +1632,30 @@ impl Game<'_> { w: &w, targets: targets_guests, }; + let guest_entities = self.lan_guest_entities(); projectiles.retain_mut(|p| { let mob_shot = !matches!(p.owner, Some(Who::Player)); - let (keep, hit) = match (p.arrow.is_some(), mob_shot) { + // A player's arrows, snowballs and eggs meet every player; a + // guest's flies from that guest (Projectile.getOwner), not + // from the host, until it has left them. + let pvp = !mob_shot && super::lan_pvp::meets_players(&p.kind); + let shooter = p + .guest + .filter(|_| pvp) + .and_then(|c| guest_entities.iter().find(|(g, _)| *g == c)) + .map(|&(_, id)| Who::Mob(id)); + if shooter.is_some() { + p.owner = shooter; + } + let (keep, hit) = match (p.arrow.is_some(), mob_shot || pvp) { (true, false) => horizon_client::arrows::tick(p, &scene, &arrow_targets), (true, true) => horizon_client::arrows::tick(p, &scene, &arrow_targets_guests), (false, false) => p.tick(&pw), (false, true) => p.tick(&pw_guests), }; + if shooter.is_some() { + p.owner = Some(Who::Player); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -1690,6 +1707,11 @@ impl Game<'_> { } self.creatures.projectiles.append(&mut projectiles); for (p, hit) in hits { + // A player's arrow on another player lands as the victim's hurt. + if let Some(victim) = self.projectile_pvp_victim(&p, hit) { + self.projectile_hits_player(&p, hit, victim)?; + continue; + } // A guest's projectile lands as theirs: a pearl takes them, what // it hurts answers to them. One hitting the host (`Who::Player` // here) stays the host's hit. diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index a7347ab2a..d2c643088 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -3,9 +3,26 @@ //! is worked out as the attacker (weapon, attack strength, critical hit, //! enchantments, a mace's smash) and lands on the victim like any player //! attack (blocking, armour, knockback), when the `pvp` game rule allows it -//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). +//! (`ServerPlayer.canHarmPlayer`, `isPvpAllowed`). A player's arrow on +//! another player lands the same way. use super::{Game, lan::LanHost, lan_mobs::guest_bounds, ray_box, view_vector}; +use horizon_client::{ + Result, + mobs::Who, + projectiles::{Hit, Projectile, ProjectileKind}, +}; + +/// The player projectiles that meet other players: arrows (their hurt), and +/// snowballs and eggs, which break on them (`Player.hurtServer` takes no 0 +/// damage). Pearls, potions and wind charges fly past players as before. +pub(super) fn meets_players(kind: &ProjectileKind) -> bool { + matches!( + kind, + ProjectileKind::Arrow { .. } | ProjectileKind::Snowball | ProjectileKind::Egg + ) +} + /// Who a player's attack lands on. #[derive(Clone, Copy)] pub(super) enum Victim { @@ -105,6 +122,89 @@ impl Game<'_> { }) } + /// The guests by connection, with their entity ids. + pub(super) fn lan_guest_entities(&self) -> Vec<(u32, u32)> { + self.lan.as_ref().map_or_else(Vec::new, |host| { + host.hub + .guests + .iter() + .map(|g| (g.conn, g.entity_id as u32)) + .collect() + }) + } + + /// The player a player's projectile hit, when it hit one: the host for a + /// guest's shot, or a guest. + pub(super) fn projectile_pvp_victim(&self, p: &Projectile, hit: Hit) -> Option { + if p.owner != Some(Who::Player) || !meets_players(&p.kind) { + return None; + } + let Hit::Entity { who, .. } = hit else { + return None; + }; + match who { + Who::Player => p.guest.map(|_| Victim::Host), + Who::Mob(id) => self + .lan + .as_ref()? + .hub + .guests + .iter() + .find(|g| g.entity_id as u32 == id) + .map(|g| Victim::Guest(g.conn)), + } + } + + /// A player's projectile on a player: the hit runs as the victim, whose + /// hurt refuses it when the `pvp` game rule or their teams forbid it + /// (`ServerPlayer.canHarmPlayer`; `AbstractArrow.onHitEntity` then turns + /// the arrow back). + pub(super) fn projectile_hits_player( + &mut self, + p: &Projectile, + hit: Hit, + victim: Victim, + ) -> Result<()> { + let Hit::Entity { at, .. } = hit else { + return Ok(()); + }; + let Some(mut host) = self.lan.take() else { + return self.projectile_hit(p, hit); + }; + let team_of = |game: &Self, name: &str| game.score.board.players_team(name).cloned(); + let attacker = match p.guest { + Some(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + None => self.player_team().cloned(), + }; + let target = match victim { + Victim::Host => self.player_team().cloned(), + Victim::Guest(conn) => host.hub.guest(conn).and_then(|g| team_of(self, &g.name)), + }; + let refused = !(self.ui.rules.bool("pvp") + && horizon_client::scoreboard::teams_allow_damage(target.as_ref(), attacker.as_ref())); + let on_player = Hit::Entity { + who: Who::Player, + at, + }; + let result = match victim { + Victim::Host => { + self.lan = Some(host); + self.combat.refuse_player_hit = refused; + let r = self.projectile_hit(p, on_player); + self.combat.refuse_player_hit = false; + return r; + } + Victim::Guest(conn) => self.guest_hit_by(&mut host, conn, |g| { + g.combat.refuse_player_hit = refused; + let r = g.projectile_hit(p, on_player); + g.combat.refuse_player_hit = false; + r + }), + }; + self.lan = Some(host); + result.unwrap_or(Ok(())) + } + /// The hit landing on the victim with its extra knockback, then the /// attacker's attack sound. Whether the victim was hurt. pub(super) fn pvp_land(&mut self, host: &mut LanHost, victim: Victim, s: &Strike) -> bool { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..699de83f8 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -20,6 +20,7 @@ address. The script then checks, from both sides, what a guest's game used to ge drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; +- arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -111,7 +112,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -613,6 +614,39 @@ def check_pvp(host, guest, out): return hits +def check_arrows(host, guest, out): + # A player's arrow on another player (#484): AbstractArrow.onHitEntity, refused by + # ServerPlayer.canHarmPlayer with the pvp game rule off (the arrow turns back). + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + g('command', command='item replace entity @s weapon.mainhand with minecraft:bow') + g('command', command='give @s minecraft:arrow 16') + hits = {} + try: + for name, rule, shooter in (('guest shoots host', 'true', guest), ('host shoots guest', 'true', host), + ('pvp off', 'false', guest)): + host('command', command=f'gamerule pvp {rule}') + for g in (host, guest): + g('command', command='effect give @s minecraft:instant_health 1 5') + face_each_other(host, guest) + shooter.wait(20) + victim = (lambda: host('state')['player']['health']) if shooter is guest else (lambda: remote(guest)['health']) + before = victim() + shooter.raw('use-item', '--hold', 1.3) # a full draw (BowItem: 20 ticks) + shooter.wait(20) + hits[name] = (before, victim()) + shooter.shot(out, 'arrows-' + name.replace(' ', '-')) + finally: + host('command', command='gamerule pvp true') + for g in (host, guest): + g('command', command='clear @s') + assert hits['guest shoots host'][1] < hits['guest shoots host'][0], f"the guest's arrow did not hurt the host: {hits}" + assert hits['host shoots guest'][1] < hits['host shoots guest'][0], f"the host's arrow did not hurt the guest: {hits}" + assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}' + return hits + + def dead_players(game, want, ticks=60): """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" for _ in range(ticks // 5): @@ -1712,7 +1746,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'arrows': check_arrows} def run(ctl, out, resources, checks): From a4247e9323f45f2e1a41c1e9715a3ed1406aa4ea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:46:32 +0200 Subject: [PATCH 056/115] A guest's door, trapdoor, fence gate, lever and button use is predicted Vanilla's MultiPlayerGameMode.useItemOn runs the use on the client's own level inside startPrediction, records each block it changes under the packet's sequence in BlockStatePredictionHandler, and keeps them until ClientboundBlockChangedAckPacket settles them (a use the server refused goes back). A Horizon guest only sent the use: its door opened one round trip later. The guest already ran the use on a dry copy of its level to know whether the click ends there; the blocks that use changes are now kept on its level as predictions under the use's sequence, as the break prediction does, when they are all hand-operated blocks: a wooden or copper door, trapdoor or fence gate, a lever or a button (an iron door has no hand use and changes nothing). The sound still comes from the server. lan_e2e `predict`: with the host process frozen, the oak door the guest clicks is already open on the guest's side (both halves), stays open on both sides once the server answers, and an iron door stays shut. Fixes #869 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 68 +++++++++++++++++++++--- tools/lan_e2e.py | 44 +++++++++++++-- 2 files changed, 102 insertions(+), 10 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 17c6e0299..d308f9bc0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3244,7 +3244,11 @@ impl Game<'_> { .and_then(|h| self.res.items().get(&h.item)) .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { - let reacts = hand == Hand::Main && self.remote_block_reacts(&hit, held.as_ref()); + let (reacts, changes) = if hand == Hand::Main { + self.remote_block_reacts(&hit, held.as_ref()) + } else { + (false, Vec::new()) + }; let seq = self.next_sequence(); let cursor = [ (hit.point[0] - f64::from(hit.pos[0])) as f32, @@ -3270,6 +3274,9 @@ impl Game<'_> { r.use_target = Some(hit.pos); r.placing = Some((target, ticks)); } + if reacts { + self.predict_use(&changes, seq); + } if held_block { self.with_hand(hand, Game::swing_arm); return true; @@ -3279,15 +3286,60 @@ impl Game<'_> { false } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the + /// use changed on this client's level at once, each kept as predicted + /// under the use's sequence until the server acknowledges it (a use the + /// server refused goes back). Only the blocks a hand opens or flips: a + /// wooden or copper door, trapdoor or fence gate, a lever or a button; + /// whatever else the use changes waits for the server. + fn predict_use( + &mut self, + changes: &[(horizon_core::position::BlockPos, BlockStateId)], + seq: i32, + ) { + let facts = self.res.facts(); + let predicted = |state: BlockStateId| { + let name = facts.get(state).name.trim_start_matches("minecraft:"); + ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) + || name.ends_with("_fence_gate") + || name.ends_with("_button") + || name == "lever" + }; + if changes.is_empty() + || !changes + .iter() + .all(|(p, s)| predicted(*s) && predicted(self.world.block(p.x, p.y, p.z))) + { + return; + } + for &(p, state) in changes { + let pos = [p.x, p.y, p.z]; + let before = self.world.block(p.x, p.y, p.z); + // BlockStatePredictionHandler.retainKnownServerState. + if let Some(r) = self.remote.as_mut() { + r.predictions + .entry(pos) + .and_modify(|e| e.0 = seq) + .or_insert((seq, before.0 as i32)); + } + self.set_block(pos, state.0 as i32); + } + } + /// Whether the block hit takes a main-hand right click with `held` /// (`BlockState.useItemOn`, then `useWithoutItem`): a door, a button, a - /// container. Vanilla's client runs it on its own level first; this runs - /// it on a copy that keeps no change. - fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> bool { + /// container, and the blocks it changed. Vanilla's client runs it on its + /// own level first; this runs it on a copy, and `predict_use` keeps the + /// changes it predicts. + fn remote_block_reacts( + &self, + hit: &super::Hit, + held: Option<&ItemStack>, + ) -> (bool, Vec<(horizon_core::position::BlockPos, BlockStateId)>) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { - return false; + return (false, Vec::new()); } use horizon_core::geometry::Direction; let face = match hit.face { @@ -3303,7 +3355,8 @@ impl Game<'_> { changed: HashMap::new(), random: horizon_core::random::LegacyRandom::new(0), }; - self.res + let reacts = self + .res .behaviours() .use_item_on( &mut level, @@ -3314,7 +3367,8 @@ impl Game<'_> { self.use_context(), held.map(|s| &*s.item), ) - .consumes_action() + .consumes_action(); + (reacts, level.changed.into_iter().collect()) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..d3762a025 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -52,6 +52,8 @@ address. The script then checks, from both sides, what a guest's game used to ge its crafting grid and gathers a stack with a double click; the server has each. - sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it gets up with Escape, and once the host sleeps too the night ends and both wake. +- predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its + prediction), and stays open once the server answers; an iron door stays shut (#869). - push: a cow standing in the guest pushes it just clear of the cow (the guest's own client pushes it, as in vanilla), not ever faster across the ground. - eat: holding right click with bread, the guest's own screen plays the eating (the item in use @@ -111,7 +113,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1255,6 +1257,42 @@ def check_sleep(host, guest, out): assert lying['host'] and lying['guest'], f'a sleeping player is drawn standing: {detail}' assert not lying['after'], f'a player up again is still drawn lying: {detail}' return detail +def check_predict(host, guest, out): + # MultiPlayerGameMode.useItemOn under startPrediction (#869): the guest's door opens on its own screen + # at once, with the host (the server) frozen, and the server's answer later agrees; an iron door + # (no hand use) stays shut on both sides. + guest('command', command='gamemode survival') + guest('command', command='clear @s') + x, y, z = (int(v // 1) for v in pos_of(guest)) + wood, iron = (x - 1, y, z + 2), (x + 1, y, z + 2) + for (bx, by, bz), kind in ((wood, 'oak_door'), (iron, 'iron_door')): + for half, dy in (('lower', 0), ('upper', 1)): + host('command', command=f'setblock {bx} {by + dy} {bz} minecraft:{kind}[facing=north,hinge=right,half={half}]') + guest.wait(20) + state = lambda game, at: game.raw('block', *at)['state'] + seen = {} + os.kill(host.pid, signal.SIGSTOP) + try: + guest.raw('interact', *wood) + seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2]))) + guest.raw('interact', *iron) + seen['guest_iron_frozen'] = state(guest, iron) + finally: + os.kill(host.pid, signal.SIGCONT) + guest.wait(20) + seen['guest_after'] = state(guest, wood) + seen['host_after'] = state(host, wood) + seen['iron_after'] = (state(guest, iron), state(host, iron)) + guest.shot(out, 'predict') + for (bx, by, bz) in (wood, iron): + host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air') + assert all('open=true' in s for s in seen['guest_frozen']), f'the door waited for the server: {seen}' + assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}' + assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}' + assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}' + return seen + + def check_push(host, guest, out): guest('command', command='gamemode survival') x, y, z = (int(v // 1) + 0.5 for v in pos_of(guest)) @@ -1712,7 +1750,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'predict': check_predict} def run(ctl, out, resources, checks): @@ -1721,7 +1759,7 @@ def run(ctl, out, resources, checks): host.d.env['HORIZON_SERVER_THREAD'] = '1' results = {} try: - host('launch', wait=False, offscreen=sys.platform == 'darwin') + host.pid = host('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] # Guests' commands need the world's Allow Commands as well as the LAN's (#372): a creative # world has them; everyone plays in survival. host.raw('open', 'Lan', 5, 'creative') From ceff635615c893c104191ed9776cda9f67028462 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:14:06 +0200 Subject: [PATCH 057/115] A guest draws a bow, and lets go to shoot A client of a server sent the bow's use but never started using the item itself, so letting go of the button sent no RELEASE_USE_ITEM: the server kept the guest drawing and never shot. BowItem.use runs on the client too (startUsingItem, with an arrow or in creative), and Minecraft.handleKeybinds releases the item in use once the button is up. The guest now draws on its own side as well (held until the button lets go or another slot is picked), so the server shoots when it lets go. lan_e2e: `arrows` passes both ways now (the guest's arrow hurts the host); the `pvp` and `arrows` checks allow the victim natural regeneration while pvp is off (it healed 19.3 -> 20 and failed the exact check). Fixes #484 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 22 +++++++++++++++++++--- tools/lan_e2e.py | 5 +++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 17c6e0299..bca93f9a1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3336,6 +3336,16 @@ impl Game<'_> { // MultiPlayerGameMode.useItem runs the use here too: food starts // being eaten (Consumable.startConsuming). self.with_hand(hand, |g| g.start_eating(&info)); + // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting + // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. + if &*held.item == "minecraft:bow" { + self.with_hand(hand, |g| { + if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) + { + g.using = Some((g.held_slot(), 0)); + } + }); + } item_has_use(&info) } @@ -3351,14 +3361,20 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` for a consumable on a server client: the - /// eating animation and its crumbs. The server eats it and sends the - /// stack, the hunger and the sounds. + /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// consumable's eating animation and its crumbs. The server eats it and + /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // A drawn bow: held until the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) + .then_some((slot, ticks + 1)); + return; + } let consumable = stack .as_ref() .and_then(|s| self.res.items().get(&s.item)) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 699de83f8..e764f4512 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -608,7 +608,8 @@ def check_pvp(host, guest, out): host('command', command='team remove parity_allies') assert hits['guest hits host'][1] < hits['guest hits host'][0], f'the guest did not hurt the host: {hits}' assert hits['host hits guest'][1] < hits['host hits guest'][0], f'the host did not hurt the guest: {hits}' - assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off still hurts: {hits}' + # Natural regeneration may heal the victim meanwhile. + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off still hurts: {hits}' for name in ('guest hits teammate', 'host hits teammate'): assert hits[name][1] == hits[name][0], f'friendly fire off still hurts ({name}): {hits}' return hits @@ -643,7 +644,7 @@ def check_arrows(host, guest, out): g('command', command='clear @s') assert hits['guest shoots host'][1] < hits['guest shoots host'][0], f"the guest's arrow did not hurt the host: {hits}" assert hits['host shoots guest'][1] < hits['host shoots guest'][0], f"the host's arrow did not hurt the guest: {hits}" - assert hits['pvp off'][1] == hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}' + assert hits['pvp off'][1] >= hits['pvp off'][0], f'pvp off, an arrow still hurts: {hits}' return hits From 56591efa5f4b38f20ce3474b5d8283d15475f989 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 23:14:07 +0200 Subject: [PATCH 058/115] A guest hears its door at once, and only once Vanilla plays a block use's sound with `level.playSound(player, ...)`: the player who clicked hears it from their own client's use, and the server sends it to everyone else. Horizon's guest waited for the server's sound, one round trip after its predicted door had already opened. The guest now plays the sounds of the use it predicts (doors, trapdoors, fence gates, levers, buttons), and the server sends the sounds of such a use to the other players only. The control socket's `status` counts the positional sounds each game played (`heard`). lan_e2e `predict`: with the host frozen, the guest already hears its door; once the server answers, the guest and the host have each heard it once. Fixes #869 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 7 ++ crates/horizon-client/src/game/control.rs | 1 + crates/horizon-client/src/game/lan_actions.rs | 30 +++++++ crates/horizon-client/src/game/remote.rs | 78 ++++++++++++++----- tools/lan_e2e.py | 11 ++- 5 files changed, 106 insertions(+), 21 deletions(-) diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 62bdc041f..997eb7728 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -157,6 +157,9 @@ pub struct Audio { /// Positional sounds played since the last drain, kept while the world /// is open to the network so guests hear them too. pub capture: Option>, + /// How many times each positional sound played (the control socket's `status`), + /// with or without an audio device. + pub heard: std::collections::BTreeMap, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -542,6 +545,7 @@ impl Audio { random: LegacyRandom::new(crate::sound_engine::unique_seed()), source_override: None, capture: None, + heard: Default::default(), } } #[cfg(not(feature = "audio"))] @@ -682,6 +686,9 @@ impl Audio { if let (Some(capture), Some(at)) = (self.capture.as_mut(), at) { capture.push((event.to_owned(), at, volume, pitch)); } + if at.is_some() { + *self.heard.entry(event.to_owned()).or_default() += 1; + } self.sync_volumes(); let event = crate::sound_events::normalize(event); let source = self diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6c69904ac..d79f69d3c 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -912,6 +912,7 @@ impl Game<'_> { status["pending_uploads"] = self.pending_uploads.len().into(); status["destroying"] = json!(destroying); status["physical_keys"] = json!(physical_keys); + status["heard"] = json!(self.audio.heard); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); // Primed TNT, falling blocks, projectiles, tridents and end crystals. diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1c38f9542..6b4fc1f77 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -805,6 +805,8 @@ impl Game<'_> { ], }; let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let logged = self.world.block_log.as_ref().map_or(0, Vec::len); + let heard = self.audio.capture.as_ref().map_or(0, Vec::len); let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); g.guest_use = Some(GuestUse::OnBlock(hand)); @@ -815,6 +817,7 @@ impl Game<'_> { g.swings_started != swings }); self.lan_swing_back(host, conn, swung); + self.guest_use_sounds(host, conn, logged, heard); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -1962,6 +1965,33 @@ impl Game<'_> { } } + /// `level.playSound(player, ...)` of a guest's use it predicted (`remote::hand_operated` + /// blocks only, as the guest decides): the others hear it now, the guest already did. + fn guest_use_sounds(&mut self, host: &mut LanHost, conn: u32, logged: usize, heard: usize) { + let changed: Vec<(i32, i32, i32)> = self + .world + .block_log + .as_ref() + .map_or(&[][..], |log| log.get(logged..).unwrap_or(&[])) + .to_vec(); + let facts = self.res.facts(); + if changed.is_empty() + || !changed.iter().all(|&(x, y, z)| { + super::remote::hand_operated(&facts.get(self.world.block(x, y, z)).name) + }) + { + return; + } + let Some(capture) = self.audio.capture.as_mut() else { + return; + }; + let sounds: Vec<_> = capture.drain(heard.min(capture.len())..).collect(); + for (name, at, volume, pitch) in sounds { + let source = horizon_client::settings::sound_source(&name) as i32; + host.hub.sound(&name, at, volume, pitch, source, Some(conn)); + } + } + /// 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/remote.rs b/crates/horizon-client/src/game/remote.rs index d308f9bc0..39becf059 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3247,7 +3247,7 @@ impl Game<'_> { let (reacts, changes) = if hand == Hand::Main { self.remote_block_reacts(&hit, held.as_ref()) } else { - (false, Vec::new()) + (false, DryUse::default()) }; let seq = self.next_sequence(); let cursor = [ @@ -3292,19 +3292,9 @@ impl Game<'_> { /// server refused goes back). Only the blocks a hand opens or flips: a /// wooden or copper door, trapdoor or fence gate, a lever or a button; /// whatever else the use changes waits for the server. - fn predict_use( - &mut self, - changes: &[(horizon_core::position::BlockPos, BlockStateId)], - seq: i32, - ) { + fn predict_use(&mut self, (changes, sounds): &DryUse, seq: i32) { let facts = self.res.facts(); - let predicted = |state: BlockStateId| { - let name = facts.get(state).name.trim_start_matches("minecraft:"); - ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) - || name.ends_with("_fence_gate") - || name.ends_with("_button") - || name == "lever" - }; + let predicted = |state: BlockStateId| hand_operated(&facts.get(state).name); if changes.is_empty() || !changes .iter() @@ -3324,6 +3314,21 @@ impl Game<'_> { } self.set_block(pos, state.0 as i32); } + // `level.playSound(player, ...)`: the clicker hears it from its own use; the + // server sends it to the others only. + for (pos, sound, volume, pitch) in sounds { + let at = [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 0.5, + f64::from(pos.z) + 0.5, + ]; + let name = if sound.contains(':') { + sound.to_string() + } else { + format!("minecraft:{sound}") + }; + self.audio.play(&name, Some(at), *volume, *pitch); + } } /// Whether the block hit takes a main-hand right click with `held` @@ -3331,15 +3336,11 @@ impl Game<'_> { /// container, and the blocks it changed. Vanilla's client runs it on its /// own level first; this runs it on a copy, and `predict_use` keeps the /// changes it predicts. - fn remote_block_reacts( - &self, - hit: &super::Hit, - held: Option<&ItemStack>, - ) -> (bool, Vec<(horizon_core::position::BlockPos, BlockStateId)>) { + fn remote_block_reacts(&self, hit: &super::Hit, held: Option<&ItemStack>) -> (bool, DryUse) { // Player.isSecondaryUseActive with something in either hand. let hands_full = self.stack_in(self.selected).is_some() || self.offhand.is_some(); if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { - return (false, Vec::new()); + return (false, DryUse::default()); } use horizon_core::geometry::Direction; let face = match hit.face { @@ -3354,6 +3355,7 @@ impl Game<'_> { world: &self.world, changed: HashMap::new(), random: horizon_core::random::LegacyRandom::new(0), + sounds: Vec::new(), }; let reacts = self .res @@ -3368,7 +3370,7 @@ impl Game<'_> { held.map(|s| &*s.item), ) .consumes_action(); - (reacts, level.changed.into_iter().collect()) + (reacts, (level.changed.into_iter().collect(), level.sounds)) } /// MultiPlayerGameMode.useItem for `hand`, if it holds something: whether @@ -4270,9 +4272,45 @@ struct DryLevel<'w> { world: &'w horizon_client::world::World, changed: HashMap, random: horizon_core::random::LegacyRandom, + /// The sounds the use plays (a door's creak). + sounds: Vec, +} + +type DrySound = ( + horizon_core::position::BlockPos, + std::sync::Arc, + f32, + f32, +); +/// What a use on the dry level changed, and the sounds it played. +type DryUse = ( + Vec<(horizon_core::position::BlockPos, BlockStateId)>, + Vec, +); + +/// The blocks a guest's hand flips that its use predicts (and hears at once): a wooden or +/// copper door, trapdoor or fence gate, a lever or a button. An iron door or trapdoor has +/// no hand use. +pub(super) fn hand_operated(name: &str) -> bool { + let name = name.trim_start_matches("minecraft:"); + ((name.ends_with("_door") || name.ends_with("_trapdoor")) && !name.starts_with("iron_")) + || name.ends_with("_fence_gate") + || name.ends_with("_button") + || name == "lever" } impl horizon_world::level::LevelAccess for DryLevel<'_> { + fn emit(&mut self, event: horizon_world::level::LevelEvent) { + if let horizon_world::level::LevelEvent::Sound { + pos, + sound, + volume, + pitch, + } = event + { + self.sounds.push((pos, sound, volume, pitch)); + } + } fn block_state(&self, pos: horizon_core::position::BlockPos) -> BlockStateId { self.changed .get(&pos) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d3762a025..81dfa51d3 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -53,7 +53,8 @@ address. The script then checks, from both sides, what a guest's game used to ge - sleep: at night the guest lies down in its own bed (not the host); alone it stays night, it gets up with Escape, and once the host sleeps too the night ends and both wake. - predict: with the host frozen, the oak door the guest opens opens on the guest's screen at once (its - prediction), and stays open once the server answers; an iron door stays shut (#869). + prediction) and creaks there at once, stays open once the server answers, and each side hears + it once; an iron door stays shut (#869). - push: a cow standing in the guest pushes it just clear of the cow (the guest's own client pushes it, as in vanilla), not ever faster across the ground. - eat: holding right click with bread, the guest's own screen plays the eating (the item in use @@ -1271,10 +1272,14 @@ def check_predict(host, guest, out): guest.wait(20) state = lambda game, at: game.raw('block', *at)['state'] seen = {} + creaks = lambda game: sum(n for s, n in game('status')['heard'].items() if 'door' in s) + heard = {'guest': creaks(guest), 'host': creaks(host)} os.kill(host.pid, signal.SIGSTOP) try: guest.raw('interact', *wood) seen['guest_frozen'] = (state(guest, wood), state(guest, (wood[0], wood[1] + 1, wood[2]))) + # level.playSound(player, ...): the clicker hears its own door at once. + seen['guest_heard_frozen'] = creaks(guest) - heard['guest'] guest.raw('interact', *iron) seen['guest_iron_frozen'] = state(guest, iron) finally: @@ -1283,6 +1288,8 @@ def check_predict(host, guest, out): seen['guest_after'] = state(guest, wood) seen['host_after'] = state(host, wood) seen['iron_after'] = (state(guest, iron), state(host, iron)) + # ... and not a second time from the server; the host hears it once. + seen['heard_after'] = {'guest': creaks(guest) - heard['guest'], 'host': creaks(host) - heard['host']} guest.shot(out, 'predict') for (bx, by, bz) in (wood, iron): host('command', command=f'fill {bx} {by} {bz} {bx} {by + 1} {bz} minecraft:air') @@ -1290,6 +1297,8 @@ def check_predict(host, guest, out): assert 'open=true' in seen['guest_after'] and 'open=true' in seen['host_after'], f'the door did not stay open: {seen}' assert 'open=false' in seen['guest_iron_frozen'], f'the guest opened an iron door by hand: {seen}' assert all('open=false' in s for s in seen['iron_after']), f'an iron door opened: {seen}' + assert seen['guest_heard_frozen'] == 1 and seen['heard_after'] == {'guest': 1, 'host': 1}, \ + f'the door is not heard once on each side: {seen}' return seen From dfe795bc090809090993c44c2a032f108efbf3f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 02:42:12 +0000 Subject: [PATCH 059/115] Faster Perlin volumes and climate search, same results PerlinNoise::add_volume worked out each Y coordinate's cell, offset and fade once per X/Z column. Every column walks the same Y coordinates, so they are now computed once per volume. The arithmetic is unchanged, so the output is bit for bit the same. ClimateIndex kept its tree as nodes with a Vec of child ids each. The built tree is now renumbered breadth first into flat arrays, so a branch's children are one contiguous run. The search visits the same nodes in the same order, so ties resolve exactly as before. terrain_bench (seed 12345, 8x8 chunks, 1 thread, medians of 3 runs): terrain 14.5 -> 12.4 ms/chunk, biomes 1.20 -> 1.06 ms/chunk. Checked against vanilla 26.3 in-process: 2304 chunks on seeds 12345, -1 and 987654321987 identical, and the biome-source and biome-generation parity suites (2.1M lines) match. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01M3pNrSHA2ifNrH7SAMHgSW --- crates/horizon-core/src/noise/perlin.rs | 58 ++++++++++++----- .../src/worldgen/climate/index.rs | 65 ++++++++++++------- 2 files changed, 84 insertions(+), 39 deletions(-) diff --git a/crates/horizon-core/src/noise/perlin.rs b/crates/horizon-core/src/noise/perlin.rs index 725373eff..92fa2a880 100644 --- a/crates/horizon-core/src/noise/perlin.rs +++ b/crates/horizon-core/src/noise/perlin.rs @@ -164,6 +164,31 @@ impl PerlinNoise { return Err(DensityError::BufferTooShort); } let [size_x, size_y, size_z] = volume.sizes(); + // Every X/Z column walks the same Y coordinates, so their cells, offsets + // and fades are computed once per volume instead of once per column. + let mut stack = [YSample::default(); STACK_Y]; + let mut heap = Vec::new(); + let ys = if size_y <= STACK_Y { + &mut stack[..size_y] + } else { + heap.resize(size_y, YSample::default()); + &mut heap[..] + }; + for (y, sample) in ys.iter_mut().enumerate() { + let input_y = f64::from(volume.coordinate(1, y)) * y_scale; + let shifted_y = wrap(input_y) + self.table.offsets[1]; + let cell = floor_i32(shifted_y); + let dy = shifted_y - f64::from(cell); + *sample = YSample { + cell, + fade: smoothstep(dy as f32), + offset: match fudge_y_scale { + Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, + None => dy as f32, + }, + }; + } + let ys = &*ys; let mut index = 0; for z in 0..size_z { let shifted_z = @@ -182,37 +207,40 @@ impl PerlinNoise { let mut previous_y = i32::MIN; let mut xz_dots = [0.0_f32; 8]; let mut y_gradients = [0.0_f32; 8]; - for y in 0..size_y { - let input_y = f64::from(volume.coordinate(1, y)) * y_scale; - let shifted_y = wrap(input_y) + self.table.offsets[1]; - let cell_y = floor_i32(shifted_y); - let dy = shifted_y - f64::from(cell_y); - let fade_y = smoothstep(dy as f32); - if previous_y != cell_y { - let gradients = self.gradients_at(p, q, cell_y, cell_z); + for (sample, out) in ys.iter().zip(&mut buffer[index..index + size_y]) { + if previous_y != sample.cell { + let gradients = self.gradients_at(p, q, sample.cell, cell_z); for i in 0..8 { xz_dots[i] = gradients[i][0] as f32 * (dx - (i & 1) as f32) + gradients[i][2] as f32 * (dz - ((i >> 2) & 1) as f32); y_gradients[i] = gradients[i][1] as f32; } - previous_y = cell_y; + previous_y = sample.cell; } - let dy = match fudge_y_scale { - Some(scale) => (dy - compute_fudge_y(input_y, dy, scale)) as f32, - None => dy as f32, - }; + let dy = sample.offset; let values = std::array::from_fn(|i| { xz_dots[i] + y_gradients[i] * (dy - ((i >> 1) & 1) as f32) }); - buffer[index] += amplitude * lerp3([fade_x, fade_y, fade_z], values); - index += 1; + *out += amplitude * lerp3([fade_x, sample.fade, fade_z], values); } + index += size_y; } } Ok(()) } } +/// Y columns up to this height keep their per-Y samples on the stack. +const STACK_Y: usize = 64; + +#[derive(Clone, Copy, Default)] +struct YSample { + cell: i32, + fade: f32, + /// The Y offset inside the cell used for the corner values, after any fudge. + offset: f32, +} + #[derive(Clone, Debug)] pub struct SmearedPerlinNoise { base: PerlinNoise, diff --git a/crates/horizon-world/src/worldgen/climate/index.rs b/crates/horizon-world/src/worldgen/climate/index.rs index 3e9b50f51..6a602ed92 100644 --- a/crates/horizon-world/src/worldgen/climate/index.rs +++ b/crates/horizon-world/src/worldgen/climate/index.rs @@ -202,8 +202,11 @@ fn build( #[derive(Debug)] pub struct ClimateIndex { entries: Vec<(ParameterPoint, T)>, - nodes: Vec, - root: usize, + /// The built tree renumbered breadth first, root at 0, so each branch's + /// children are one contiguous run and a search walks memory in order. + spaces: Vec<[Parameter; 7]>, + /// Per node: its first child and child count, or its entry and 0 for a leaf. + links: Vec<(u32, u32)>, } impl ClimateIndex { pub fn new(entries: Vec<(ParameterPoint, T)>) -> Result { @@ -232,10 +235,25 @@ impl ClimateIndex { .collect(); let children = (0..nodes.len()).collect(); let root = build(&mut nodes, children, branching)?; + let mut order = vec![root]; + let mut links = Vec::with_capacity(nodes.len()); + let mut next = 0; + while next < order.len() { + let node = &nodes[order[next]]; + next += 1; + links.push(match &node.children { + Children::Leaf(entry) => (*entry as u32, 0), + Children::Branch(children) => { + let first = order.len() as u32; + order.extend_from_slice(children); + (first, children.len() as u32) + } + }); + } Ok(Self { entries, - nodes, - root, + spaces: order.iter().map(|id| nodes[*id].space).collect(), + links, }) } pub fn entries(&self) -> &[(ParameterPoint, T)] { @@ -263,18 +281,18 @@ impl ClimateIndex { } /// Preorder leaf entry indices expose stable tree layout for comparison. pub fn leaf_order(&self) -> Vec { - fn walk(nodes: &[Node], id: usize, out: &mut Vec) { - match &nodes[id].children { - Children::Leaf(entry) => out.push(*entry), - Children::Branch(children) => { - for child in children { - walk(nodes, *child, out); + fn walk(links: &[(u32, u32)], id: usize, out: &mut Vec) { + match links[id] { + (entry, 0) => out.push(entry as usize), + (first, count) => { + for child in first..first + count { + walk(links, child as usize, out); } } } } let mut result = Vec::with_capacity(self.entries.len()); - walk(&self.nodes, self.root, &mut result); + walk(&self.links, 0, &mut result); result } fn search( @@ -283,19 +301,20 @@ impl ClimateIndex { values: &[i64; 7], previous: Option, ) -> Result { - let Children::Branch(children) = &self.nodes[id].children else { + let (first, count) = self.links[id]; + if count == 0 { return Ok(id); - }; + } let mut best = previous; - let mut fitness = previous.map_or(i64::MAX, |id| distance(&self.nodes[id].space, values)); - for child in children { - let lower = distance(&self.nodes[*child].space, values); + let mut fitness = previous.map_or(i64::MAX, |id| distance(&self.spaces[id], values)); + for child in first as usize..(first + count) as usize { + let lower = distance(&self.spaces[child], values); if fitness > lower { - let result = self.search(*child, values, best)?; - let next = if result == *child { + let result = self.search(child, values, best)?; + let next = if result == child { lower } else { - distance(&self.nodes[result].space, values) + distance(&self.spaces[result], values) }; if fitness > next { fitness = next; @@ -313,13 +332,11 @@ pub struct ClimateSearch<'a, T> { } impl<'a, T> ClimateSearch<'a, T> { pub fn find(&mut self, target: TargetPoint) -> Result<&'a T, IndexError> { - let result = self - .index - .search(self.index.root, &target.parameters(), self.last)?; + let result = self.index.search(0, &target.parameters(), self.last)?; self.last = Some(result); - let Children::Leaf(entry) = self.index.nodes[result].children else { + let (entry, 0) = self.index.links[result] else { unreachable!("search returns a leaf"); }; - Ok(&self.index.entries[entry].1) + Ok(&self.index.entries[entry as usize].1) } } From 86b58b71fab6f682201002c2d258996450dde3f0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 21:19:46 +0200 Subject: [PATCH 060/115] Client of a server: abilities from the server, flight sent back A player who joined already in creative could not fly: the remote client kept only instabuild and the flying speed of ClientboundPlayerAbilitiesPacket, and the motion step clears flying for a player that may not fly. The packet also comes before the client has a player (it is made at the first teleport). Single player creative on its server thread could not fly at all; a LAN guest only after a game mode change. - The remote client keeps the last abilities and applies flying, may fly, invulnerable and the flying speed to the player, also when the player is made (ClientPacketListener.handlePlayerAbilities). - When its flight turns on or off (double jump, spectator, landing) it sends ServerboundPlayerAbilitiesPacket (LocalPlayer.onUpdateAbilities). - The hub keeps it as the guest's flying when the guest may fly (handlePlayerAbilities), so the save has it, and a game mode change sets it as GameType.updatePlayerAbilities does. - lan_e2e `flight`: the guest, and on the server thread the host's window, fly in creative, stay up, and stop in survival. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/remote.rs | 35 +++++++++++++- crates/horizon-client/src/lan/hub.rs | 13 ++++++ crates/horizon-protocol/src/packets/play.rs | 14 ++++++ tools/lan_e2e.py | 51 ++++++++++++++++++++- 4 files changed, 109 insertions(+), 4 deletions(-) diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 17c6e0299..f7346199a 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -99,6 +99,10 @@ pub(super) struct Remote { last_input: u8, was_sprinting: bool, carried: Option, + /// The last ClientboundPlayerAbilitiesPacket. Vanilla's LocalPlayer + /// holds its abilities from the login on; here the player is made at + /// the first teleport, which takes them then. + abilities: Option, loaded_sent: bool, /// The view distance last sent in ClientInformation. sent_view: i8, @@ -313,6 +317,7 @@ impl Game<'_> { last_input: 0, was_sprinting: false, carried: None, + abilities: None, loaded_sent: false, sent_view: view, predictions: HashMap::new(), @@ -1840,9 +1845,10 @@ impl Game<'_> { }, C::PlayerAbilities(p) => { self.creative = p.flags & 8 != 0; - if let Some(player) = &mut self.player { - player.flying_speed = p.flying_speed; + if let Some(r) = self.remote.as_mut() { + r.abilities = Some(p); } + self.apply_remote_abilities(); } C::SetHeldSlot(p) => { self.selected = p.slot.clamp(0, 8) as usize; @@ -2485,6 +2491,7 @@ impl Game<'_> { self.previous_eye = 1.62; self.clock.reset(); self.apply_remote_health(); + self.apply_remote_abilities(); } } self.previous_position = position; @@ -2620,6 +2627,7 @@ impl Game<'_> { [player.velocity.x, player.velocity.y, player.velocity.z], [player.position.x, player.position.y, player.position.z], ); + let was_flying = player.flying; player.yaw = self.yaw; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. @@ -2642,6 +2650,9 @@ impl Game<'_> { } .controlled_simulation_tick(keys)?; } + // LocalPlayer.onUpdateAbilities: flight turned on or off (a double + // jump, a spectator, landing) is sent to the server. + let flying = player.flying; let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; @@ -2676,9 +2687,29 @@ impl Game<'_> { if !dead { self.remote_tick_using(); } + if flying != was_flying { + self.send(S::PlayerAbilities(play::PlayerAbilitiesRequest { + flags: if flying { 2 } else { 0 }, + })); + } self.remote_send_state(input); Ok(()) } + + /// ClientPacketListener.handlePlayerAbilities: the player flies, may fly + /// and is invulnerable as the server says (bits 2, 4 and 1). + fn apply_remote_abilities(&mut self) { + let (Some(player), Some(a)) = ( + self.player.as_mut(), + self.remote.as_ref().and_then(|r| r.abilities.as_ref()), + ) else { + return; + }; + player.invulnerable = a.flags & 1 != 0; + player.flying = a.flags & 2 != 0; + player.may_fly = a.flags & 4 != 0; + player.flying_speed = a.flying_speed; + } /// The local player's share of every touching entity's /// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy` /// lets entities push only the local player, so the server never sends diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 9c65e9292..4e8269e80 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1872,6 +1872,7 @@ impl Hub { // (handlePlayerKnownMovement), PlayerInput once loaded. let acted = match &packet { S::AcceptTeleportation(_) + | S::PlayerAbilities(_) | S::MovePlayerStatus(_) | S::MovePlayerRot(_) | S::PlayerLoaded(_) @@ -1909,6 +1910,11 @@ impl Hub { self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events); } } + // handlePlayerAbilities: the client flies only if it may. + S::PlayerAbilities(p) => { + let g = &mut self.guests[i]; + g.flying = p.flags & 2 != 0 && (g.creative() || g.spectator()); + } S::MovePlayerPos(p) => { self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events); } @@ -2183,6 +2189,13 @@ impl Hub { return; }; g.game_mode = mode; + // GameType.updatePlayerAbilities: a spectator flies, survival and + // adventure don't, creative keeps what it had. + if g.spectator() { + g.flying = true; + } else if !g.creative() { + g.flying = false; + } let uuid = g.uuid; g.send(&C::GameEvent(play::GameEvent { event: game_event::CHANGE_GAME_MODE, diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 95a68d1ef..c5d5eb68c 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1674,6 +1674,8 @@ packet!( ); packet!(ChangeDifficultyRequest { difficulty: i32 => VarInt }); packet!(LockDifficulty { locked: bool => Bool }); +// ServerboundPlayerAbilitiesPacket: only whether the player flies (2). +packet!(PlayerAbilitiesRequest { flags: i8 => Byte }); packet!(SetGameRule { entries: Vec => List }); packet!(ChunkBatchReceived { chunks_per_tick: f32 => Float }); packet!( @@ -1786,6 +1788,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY, PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, PingRequest(crate::packets::status::Ping) = PING_REQUEST, + PlayerAbilities(PlayerAbilitiesRequest) = PLAYER_ABILITIES, PlayerAction(PlayerAction) = PLAYER_ACTION, PlayerCommand(PlayerCommand) = PLAYER_COMMAND, PlayerInput(PlayerInput) = PLAYER_INPUT, @@ -1805,6 +1808,17 @@ mod tests { use super::*; use crate::{chunk::BlockEntityInfo, packets::round_trip, text::literal}; + #[test] + fn serverbound_abilities_carry_only_flying() { + // ServerboundPlayerAbilitiesPacket.write: one byte, 2 when flying. + let flying = Serverbound::PlayerAbilities(PlayerAbilitiesRequest { flags: 2 }); + assert_eq!( + flying.encode(), + [crate::ids::play::serverbound::PLAYER_ABILITIES as u8, 2] + ); + round_trip(flying, Serverbound::encode, Serverbound::decode); + } + #[test] fn world_options_packets_match_vanilla_stream_codecs() { // mcsrc.dev 26.3: difficulty is a VarInt, locking is a Boolean, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 0b40e55e4..61697550b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -74,6 +74,9 @@ address. The script then checks, from both sides, what a guest's game used to ge server's game time after the guest's game stalls for a few seconds (#848). - growth: far from the host, the chunks around the guest tick (#890): water placed there flows and wheat on farmland grows (random ticks), however the host runs its world. +- flight: a player in creative double-taps jump and flies, stays up, and stops flying in survival: + the guest, and on the server thread the host's window too, take what may fly from the + server's abilities (ClientPacketListener.handlePlayerAbilities). - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). @@ -111,7 +114,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight'] class Game: @@ -1607,6 +1610,50 @@ def same_light(host, guest, lo, hi, what, ticks=100): f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}') +def check_flight(host, guest, out): + def double_jump(game): + # LocalPlayer.aiStep: a second jump press within 7 ticks of the first toggles flight. + for hold in (1, 4): + game.raw('key', 'space', 'down') + game.wait(hold) + game.raw('key', 'space', 'up') + game.wait(2) + game.wait(10) + return game('state')['player'] + + def set_mode(game, mode): + # On a client of a server the mode and its abilities (may fly) come back with the server's + # answer, later when the machine is busy: a double jump before them is two plain jumps. + game('command', command=f'gamemode {mode}') + for _ in range(100): + if game('state').get('gamemode') == mode: + break + game.wait(1) + game.wait(10) + + players = [('guest', guest)] + ([('host', host)] if SERVER_THREAD else []) + seen = {} + try: + for name, game in players: + set_mode(game, 'creative') + ground = game('state')['player'] + up = double_jump(game) + game.wait(20) + later = game('state')['player'] + set_mode(game, 'survival') + fell = game('state')['player'] + seen[name] = {'flying': up['flying'], 'rose': round(up['position'][1] - ground['position'][1], 2), + 'stayed': round(later['position'][1] - up['position'][1], 2), + 'survival_flying': fell['flying']} + finally: + for _, game in players: + game('command', command='gamemode survival') + for name, s in seen.items(): + assert s['flying'] and s['rose'] > 1 and abs(s['stayed']) < 0.1, f'{name} does not fly in creative: {seen}' + assert not s['survival_flying'], f'{name} still flies in survival: {seen}' + return seen + + def check_growth(host, guest, out): """Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them.""" x0, y0, z0 = pos_of(guest) @@ -1712,7 +1759,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, - 'time': check_time, 'growth': check_growth} + 'time': check_time, 'growth': check_growth, 'flight': check_flight} def run(ctl, out, resources, checks): From 0468b75c435215617e187ebdd87db194e917f6dc Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 16:17:11 +0200 Subject: [PATCH 061/115] Run single player on its server thread by default Single player's world now runs on the integrated server thread unless asked otherwise, as vanilla's does, so a world tick no longer holds up a frame. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` keeps the world in the frame as an escape hatch; `--server-thread` stays. lan_e2e.py sets the host's mode explicitly either way. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4ff23b686d44249c9c8d6dc9d0f9d3c12ed6afcb) --- crates/horizon-client/src/game.rs | 10 ++++++---- crates/horizon-client/src/game/integrated.rs | 6 +++--- tools/lan_e2e.py | 4 ++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25e8fdeb..35814dd6c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -267,8 +267,9 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, - /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on - /// an integrated server thread (game/integrated.rs). + /// Single player runs on an integrated server thread (game/integrated.rs), + /// as vanilla's does: the default. `--no-server-thread` or + /// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead. server_thread: bool, /// Set on the integrated server's own options: it draws nothing, so it skips meshing. integrated: bool, @@ -323,7 +324,7 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), - server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"), + server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0"), integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); @@ -332,7 +333,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} 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 --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\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 --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\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 {} 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 --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\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 --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\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_core::VANILLA_VERSION ); return Ok(None); @@ -347,6 +348,7 @@ impl Options { "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), "--server-thread" => o.server_thread = true, + "--no-server-thread" => o.server_thread = false, _ => { let value = args .next() diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 6e1fdf589..ef5775174 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -6,9 +6,9 @@ //! the world's options) with [`Integrated::call`], as vanilla's client calls //! into its `IntegratedServer`. //! -//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the -//! player joins as a network player, and the server side of a network player -//! does not do everything single player does yet. +//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs +//! the world in the frame instead (the escape hatch while the network +//! player's side catches up with the in-frame one). use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 40c081a5a..70b44407b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -1777,8 +1777,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name def run(ctl, out, resources, checks): host, guest = Game('host', ctl, resources), Game('guest', ctl, resources) - if SERVER_THREAD: - host.d.env['HORIZON_SERVER_THREAD'] = '1' + # Either way explicitly: the game's default is the server thread. + host.d.env['HORIZON_SERVER_THREAD'] = '1' if SERVER_THREAD else '0' results = {} try: host('launch', wait=False, offscreen=sys.platform == 'darwin') From 2f883b5cdbc44dd573bbe4f16dca2eec920ae8d3 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 20:54:13 +0200 Subject: [PATCH 062/115] Keep the command harness in the frame; compare finished border chunks - The command harness (HORIZON_COMMAND_SCRIPT) drives the world itself, without the event loop, so it does not start the server thread. - `status` lists the minecarts a client of a server was sent. - save_roundtrip: single player's server thread finishes the chunks its player tracks, as vanilla's integrated server does, including some that vanilla's server (view distance 4) left before their terrain or light. Those had no blocks, light or heightmaps to compare yet. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 2818c89f242fd0856c098ceeb7c809c776120240) --- crates/horizon-client/src/game.rs | 5 +++- crates/horizon-client/src/game/control.rs | 4 ++- crates/horizon-client/src/game/remote.rs | 22 ++++++++++++++++ tools/test_save_roundtrip_parity.py | 32 ++++++++++++++++++++--- 4 files changed, 58 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 35814dd6c..affc120e7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -324,7 +324,10 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), - server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0"), + // The command harness (HORIZON_COMMAND_SCRIPT) drives the world + // itself, without the event loop: it stays in the frame. + server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") + && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6c69904ac..28e6c56c0 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -879,7 +879,9 @@ impl Game<'_> { "tridents": self.tridents.len(), "rockets": self.rockets.len(), "fight": self.dragon_status(), - "carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>(), + // A client of a server (single player's server thread) knows the + // carts it was sent. + "carts": self.remote_carts().unwrap_or_else(|| self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>()), "riding": self.riding, "using": self.using, "render_distance": self.streaming.radius, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index f7346199a..b770e71a9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -529,6 +529,28 @@ impl Game<'_> { } } + /// The minecarts the server sent, for the control socket's `status` + /// (their velocity is not tracked here). + pub(super) fn remote_carts(&self) -> Option> { + let r = self.remote.as_ref()?; + let mut carts: Vec<&Tracked> = r + .entities + .values() + .filter(|t| t.kind.ends_with("minecart")) + .collect(); + carts.sort_by(|a, b| { + a.position + .partial_cmp(&b.position) + .unwrap_or(std::cmp::Ordering::Equal) + }); + Some( + carts + .into_iter() + .map(|t| serde_json::json!({"kind": t.kind, "position": t.position, "velocity": [0.0, 0.0, 0.0]})) + .collect(), + ) + } + /// The names in the server's player list, sorted. pub(super) fn remote_online_names(&self) -> Option> { let r = self.remote.as_ref()?; diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index e2531a657..72bea8845 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -68,6 +68,14 @@ IGNORED = { # differently (no worldgen heightmaps, entities in entities/) is accepted. r'^chunk\.promoted\.(Status|Heightmaps\.(OCEAN_FLOOR_WG|WORLD_SURFACE_WG)|entities)$': 'a proto chunk vanilla left at its view distance, finished by Horizon', + # Single player's server thread sends the chunks its player tracks (view distance 6 + # and its outer ring), as vanilla's integrated server does, so it finishes some that + # vanilla's server (view distance 4) left before their terrain: those had no blocks, + # light or heightmaps to compare yet. + r'^chunk\.blank\.': + 'a chunk vanilla left before its terrain (no blocks yet), finished by Horizon', + r'^chunk\.unlit\.': + 'a chunk vanilla left before its light, finished (and lit) by Horizon', # Horizon keeps simulating between loading and saving (it needs a few seconds of # chunk generation first), so counters and positions of live things move on. r'^chunk\.block_entities\.\(2, -60, 5\)\.(cooking_time_spent|lit_time_remaining|Items\[\]\.count)$': @@ -464,6 +472,13 @@ def normalize_chunk(root): return out, sections +# ChunkStatus before NOISE: nothing has filled the chunk's blocks yet. +BLANK_STATUSES = {'minecraft:empty', 'minecraft:structure_starts', 'minecraft:structure_references', + 'minecraft:biomes'} +# ChunkStatus LIGHT and later: the chunk's light is saved. +LIT_STATUSES = {'minecraft:light', 'minecraft:spawn', 'minecraft:full'} + + def compare_chunks(vanilla, horizon, report): for key in sorted(set(vanilla) | set(horizon)): if key not in horizon: @@ -476,9 +491,10 @@ def compare_chunks(vanilla, horizon, report): ha, hs = normalize_chunk(horizon[key]) out = [] diff(va, ha, 'chunk', out) - if va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full': - promoted = re.compile(r'^chunk\.(Status|Heightmaps\.\w+_WG|entities)$') - out = [(path.replace('chunk.', 'chunk.promoted.', 1) if promoted.match(path) else path, p, q) + promoted = va.get('Status') != 'minecraft:full' and ha.get('Status') == 'minecraft:full' + if promoted: + rule = re.compile(r'^chunk\.(Status|Heightmaps\.\w+_WG|entities)$') + out = [(path.replace('chunk.', 'chunk.promoted.', 1) if rule.match(path) else path, p, q) for path, p, q in out] for y in sorted(set(vs) | set(hs)): empty = {'blocks': ['minecraft:air'] * 4096, 'biomes': None, 'BlockLight': None, 'SkyLight': None} @@ -493,6 +509,16 @@ def compare_chunks(vanilla, horizon, report): if a[light] != b[light]: out.append((f'chunk.sections.{light}[{y}]', None if a[light] is None else 'present', None if b[light] is None else 'present')) + # Before its terrain a chunk has no blocks, light or heightmaps yet. + if promoted and va.get('Status') in BLANK_STATUSES: + blank = re.compile(r'^chunk\.(Heightmaps|sections)\.') + out = [(path.replace('chunk.', 'chunk.blank.', 1) if blank.match(path) else path, p, q) + for path, p, q in out] + # Before its light step a chunk saves no light; Horizon lights what it finishes. + elif promoted and va.get('Status') not in LIT_STATUSES: + unlit = re.compile(r'^chunk\.sections\.(SkyLight|BlockLight)\[') + out = [(path.replace('chunk.', 'chunk.unlit.', 1) if unlit.match(path) else path, p, q) + for path, p, q in out] for path, p, q in out: report.append((f'{path} @{key}', p, q)) From 55891f9c95d083afd6247f97bd7ea9fd3b6b5864 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 17 Oct 2026 19:34:46 +0200 Subject: [PATCH 063/115] Wait for the server's block in the agent's place, try hidden spots On a client of a server (single player's server thread, a LAN guest) the placed block comes with the server's answer: `place` waits up to a second for it before reporting no change. agent_control_e2e tries the next free spot when the tree's trunk above the broken log hides a spot's faces. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 9821bb7ef54112200c720c2ca91f10187b4ea693) --- crates/horizon-client/src/game/agent.rs | 12 +++++++++++- tools/agent_control_e2e.py | 23 +++++++++++++++-------- 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 5d7d294dd..9a5cd6a58 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -1840,11 +1840,21 @@ impl Game<'_> { if self.ticks < *report_tick && !timed_out { return None; } - let after = pos.map(|p| self.block_json(p)); let changed = match (*pos, *before) { (Some(p), Some(b)) => self.world.block(p[0], p[1], p[2]) != b, _ => false, }; + // A client of a server (single player's server thread, a LAN + // guest) sees the block once the server's answer comes. + if *place + && !changed + && self.remote.is_some() + && self.ticks < *report_tick + 20 + && !timed_out + { + return None; + } + let after = pos.map(|p| self.block_json(p)); let used = delta(inventory, &self.inventory_counts()); let mut v = json!({ "ok": !*place || changed, diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 4edc7ae55..a3690f9d7 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -253,20 +253,27 @@ def scenario(d, out): # 5. Place a plank beside the player and read it back. p = d('state')['player']['block_pos'] - target = None + hotbar = d('inventory')['hotbar'] + if not any(s.get('item') == planks_id for s in hotbar): + raise Failed(f'{planks_id} did not land in the hotbar: {hotbar}') + target = placed = None for dx, dz in [(2, 0), (-2, 0), (0, 2), (0, -2), (2, 1), (1, 2), (-2, -1), (-1, -2)]: at = (p[0] + dx, p[1], p[2] + dz) here = d('block', x=at[0], y=at[1], z=at[2])['block'] below = d('block', x=at[0], y=at[1] - 1, z=at[2])['block'] - if here in ('minecraft:air', 'minecraft:short_grass') and below not in ('minecraft:air', 'minecraft:water'): - target = at - break + if here not in ('minecraft:air', 'minecraft:short_grass') or below in ('minecraft:air', 'minecraft:water'): + continue + # The tree's trunk above the broken log can hide a spot's faces: try the next one. + try: + placed = d('place', x=at[0], y=at[1], z=at[2], item=planks_id) + except Failed as e: + if 'no visible face' in str(e): + continue + raise + target = at + break if target is None: raise Failed(f'no free spot beside {p} to place a block') - hotbar = d('inventory')['hotbar'] - if not any(s.get('item') == planks_id for s in hotbar): - raise Failed(f'{planks_id} did not land in the hotbar: {hotbar}') - placed = d('place', x=target[0], y=target[1], z=target[2], item=planks_id) assert placed['changed'], placed back = d('block', x=target[0], y=target[1], z=target[2]) assert back['block'] == planks_id, back From 8b75ac3cdbb2a1432464a416df26380a2fc6367f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 17:31:43 +0200 Subject: [PATCH 064/115] lan_e2e and agent_control_e2e on the server thread From b9f3821f (fix/server-thread-default): the host window draws what it was sent on the server thread, and agent_control_e2e waits two ticks where the server answers a click. Co-Authored-By: Claude Opus 5.5 --- tools/agent_control_e2e.py | 4 ++++ tools/lan_e2e.py | 26 ++++++++++++++++++++------ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index a3690f9d7..a01c25ef9 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -244,10 +244,12 @@ def scenario(d, out): d('click_slot', slot=log_slot) # pick up the logs d('click_slot', slot=100, right=True) # put one in the crafting grid d('click_slot', slot=log_slot) # put the rest back + d('wait', ticks=2) # the server crafts the result (single player's server thread) result = next(s for s in d('screen')['slots'] if s['slot'] == 200) assert result.get('item') == planks_id and result['count'] == 4, result d('click_slot', slot=200, shift=True) # craft into the inventory d('close') + d('wait', ticks=2) inventory = d('inventory') assert inventory['counts'].get(planks_id, 0) >= 4, inventory @@ -329,6 +331,7 @@ def ui_scenario(d, out): # 3. The inventory's slots are widgets too, with their stacks. d('give', item='oak_log', count=2) + d('wait', ticks=2) # single player's server thread gives them d('open_inventory') tree = widgets(d) log = next(w for w in tree.values() if w['kind'] == 'slot' and (w.get('stack') or {}).get('item') == 'minecraft:oak_log') @@ -336,6 +339,7 @@ def ui_scenario(d, out): d('click', id=log['id']) d('click', id='slot-100', right=True) d('click', id=log['id']) + d('wait', ticks=2) assert widgets(d)['slot-200']['stack']['item'] == 'minecraft:oak_planks' d('close') shot = d('screenshot', path=str(out / f'{d.name}-ui.png')) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 70b44407b..40ab181e1 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -168,6 +168,11 @@ def remote(guest): return guest('status')['server'] +def dead(guest): + """Whether the guest is dead: its death screen (the last health it was sent can stay above 0).""" + return guest('state').get('screen') == 'dead' or remote(guest)['health'] <= 0 + + def back_to_game(game): """Close whatever screen a failed check left open, without opening the pause menu.""" try: @@ -227,9 +232,15 @@ def check_armour(host, guest, out): face_each_other(host, guest) host.shot(out, 'armour') guest.shot(out, 'armour') - seen = lan_guest(host).get('model_armor') - assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \ - f'the host draws the guest in {seen}' + if SERVER_THREAD: + # The host's window is a client of its server thread: what it draws is what it was sent. + seen = [e for e in remote(host).get('player_equipment', [])] + assert all(any(item in json.dumps(e) for e in seen) for item in + ('diamond_chestplate', 'diamond_leggings')), f'the host draws the guest in {seen}' + else: + seen = lan_guest(host).get('model_armor') + assert seen == [None, 'minecraft:diamond_chestplate', 'minecraft:diamond_leggings', None], \ + f'the host draws the guest in {seen}' host_gear = [e for e in remote(guest).get('player_equipment', [])] assert any('golden_chestplate' in json.dumps(e) for e in host_gear), f'the guest sees the host in {host_gear}' return 'each in their own' @@ -559,7 +570,7 @@ def check_hazards(host, guest, out): x, y, z = hx + 3, hy, hz for name, fill, ticks in (('lava', 'minecraft:lava', 60), ('wall', 'minecraft:stone', 60), ('drowning', 'minecraft:water', 500), ('void', None, 60)): - if remote(guest)['health'] <= 0: + if dead(guest): guest.raw('respawn') guest.wait(40) # A stone box around the guest holds the lava and the water in. @@ -582,7 +593,7 @@ def check_hazards(host, guest, out): host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y + 2} {z + 1} minecraft:air') host('command', command=f'fill {x - 1} {y - 1} {z - 1} {x + 1} {y - 1} {z + 1} minecraft:stone') guest.wait(20) - if remote(guest)['health'] <= 0: + if dead(guest): guest.raw('respawn') guest.wait(40) # [food, saturation, exhaustion]: 8 s of sprint-jumping is about 2 of exhaustion; every 4 @@ -595,6 +606,9 @@ def check_hazards(host, guest, out): def check_pvp(host, guest, out): + if dead(guest): + guest.raw('respawn') + guest.wait(40) for g in (host, guest): g('command', command='gamemode survival') g('command', command='item replace entity @s weapon.mainhand with minecraft:iron_sword') @@ -1104,7 +1118,7 @@ def check_walls(host, guest, out): for g in (host, guest): back_to_game(g) # The trial spawner's zombies may have killed the guest. - if guest('state').get('screen') == 'dead' or remote(guest)['health'] <= 0: + if dead(guest): guest.raw('respawn') guest.wait(40) face_each_other(host, guest) From 05e169f4e3cb32aa655b24eb5f1c9ea298af4ebd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:20:31 +0200 Subject: [PATCH 065/115] agent_control_e2e pick: wait for the server to clear the cursor Step 2 clones a stack in the creative tab and closes the screen. The clone lived only on the client: ItemPickerMenu's carried stack is the inventoryMenu's, and AbstractContainerMenu.removed clears the carried stack only for a ServerPlayer, so vanilla's client still holds it when the survival inventory opens. With a stack in hand the middle button's release sends CLONE (AbstractContainerScreen.mouseReleased); the server finds the carried stack it was told about wrong and sends the empty one (broadcastChanges). On single player's server thread that answer takes a round trip, as in vanilla, so step 3 now waits up to 20 ticks for it. The in-frame world puts the clone away when the menu closes. Co-Authored-By: Claude Opus 5.5 --- tools/agent_control_e2e.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index a01c25ef9..6464425fa 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -500,6 +500,15 @@ def pick_scenario(d, out): d('give', item='oak_log', count=2) assert d('open_inventory')['screen'] == 'inventory' d('click', id='slot-0', middle=True) + # The clone of step 2 lived only on this client: ItemPickerMenu's carried stack is the + # inventoryMenu's, and AbstractContainerMenu.removed clears it only for a ServerPlayer. With a + # stack in hand, mouseReleased sends CLONE, the server finds the carried stack it was told about + # wrong and sends the empty one back (broadcastChanges). On the server thread that takes a + # round trip, as in vanilla; in the frame, closing the menu already put the clone away. + for _ in range(20): + if carried() is None: + break + d('wait', ticks=1) assert carried() is None, carried() assert widgets(d)['slot-0']['stack'] == {'item': 'minecraft:oak_log', 'count': 2} d('close') From b7453b129bda2b6531a4f7816ca52f34b412c235 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 21 Oct 2026 20:55:30 +0200 Subject: [PATCH 066/115] agent_control_e2e survival: wait for the log's drop or its pickup On single player's server thread the broken log's drop and its pickup both come from the server, a few ticks after `break` answers: the pickup could land before the scenario looked for the drop, which it then never found (StopIteration). Step 3 now waits up to 20 ticks for the logs in the inventory or the drop to walk to. Co-Authored-By: Claude Opus 5.5 --- tools/agent_control_e2e.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index 6464425fa..977d2e292 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -227,11 +227,18 @@ def scenario(d, out): raise Failed('no reachable tree near spawn') assert broke['block_before'].startswith(log_id), broke assert broke['drops'].get(log_id, 0) >= 1, broke - if broke['picked_up'].get(log_id, 0) < 1: + # On a client of a server (single player's server thread) the drop and its pickup both come from + # the server a few ticks later: wait for the logs in the inventory, or walk to the drop. + for _ in range(20): + if broke['picked_up'].get(log_id, 0) >= 1 or d('inventory')['counts'].get(log_id, 0) >= 1: + break items = d('entities', radius=8, type='item')['entities'] - drop = next(e for e in items if e['item']['item'] == log_id) - d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=1.0, timeout=20) # pickup reaches a block; the drop may lie under the trunk - d('wait', ticks=10) + drop = next((e for e in items if e['item']['item'] == log_id), None) + if drop is not None: + d('goto', x=drop['pos'][0], y=drop['pos'][1], z=drop['pos'][2], near=1.0, timeout=20) # pickup reaches a block; the drop may lie under the trunk + d('wait', ticks=10) + break + d('wait', ticks=1) inventory = d('inventory') assert inventory['counts'].get(log_id, 0) >= 1, inventory From f59f6e3e84483ea6a7ef2c76062176260b8b2bf0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:16:44 +0200 Subject: [PATCH 067/115] lan_e2e portals: take the portals away afterwards The guest came home into its Nether portal's frame, with an obsidian ceiling three blocks up, and the host onto the End portal it had set at spawn; both stayed there for the rest of the run. Under that ceiling a double jump rises about 1.2 blocks at most, and whether the flight check saw it depended on timing: `flight` failed in full --server-thread runs (portals runs only there) and passed alone. The check now clears the frame and the End portal in the overworld, and puts the guest back where it started, also when it fails. Co-Authored-By: Claude Opus 5.5 --- tools/lan_e2e.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 61697550b..40c081a5a 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -421,6 +421,20 @@ def check_portals(host, guest, out): if not SERVER_THREAD: return 'skipped (needs --server-thread)' x, y, z = (int(v // 1) for v in pos_of(guest)) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + try: + return portals(host, guest, out, x, y, z, hx, hy, hz) + finally: + # The guest comes home into its portal's frame (an obsidian ceiling three blocks up) and the + # host onto its End portal at spawn: take both away so the next checks start in the open. + home = 'execute in minecraft:overworld run' + guest('command', command=f'{home} fill {x - 1} {y} {z + 3} {x + 2} {y + 3} {z + 3} minecraft:air') + host('command', command=f'{home} setblock {hx} {hy} {hz} minecraft:air') + guest('command', command=f'{home} tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(20) + + +def portals(host, guest, out, x, y, z, hx, hy, hz): nether_portal(guest, x, y, z + 3) guest.wait(5) guest('command', command=f'tp @s {x + 0.5} {y} {z + 3.5}') @@ -435,7 +449,6 @@ def check_portals(host, guest, out): below = guest.raw('block', arrived[0], arrived[1] - 1, arrived[2]) assert below.get('loaded') and below.get('block') != 'minecraft:air', f'under the guest in the Nether: {below}' # The host takes an End portal while the guest is in the Nether: three levels at once. - hx, hy, hz = (int(v // 1) for v in pos_of(host)) host('command', command=f'setblock {hx} {hy} {hz} minecraft:end_portal') end = wait_dimension(host, 'minecraft:the_end', 600) host.wait(40) From 832f879b27f2fd9e4db913db51c6f836bf928d3f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 03:52:00 +0200 Subject: [PATCH 068/115] Dynamic lights: held, dropped and burning light sources (Horizon Extras) A new Horizon Extras option, Lighting > Dynamic lights (`dynamicLights`, off by default): a torch, lantern or other light-emitting item held by a player or mob, dropped as an item, or any entity on fire lights the blocks, entities and hand around it, as LambDynamicLights and OptiFine do. Client-only and at render time: the light engine, chunk meshes and saves never see it. Each frame the game picks the 16 sources nearest the camera (dynamic_light::select) and passes them in Globals; terrain.wgsl and entity.wgsl raise each vertex's block light to `level - distance` when that is brighter. Off, the count in globals.time.z is 0, nothing is gathered and the shaders' loop runs zero times, so no pipeline is rebuilt either way. An item glows like its block's default state (torch 14, lantern and glowstone 15, lit redstone torch 7); a lava bucket 15; burning entities 15. Fixes #814 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/dynamic_light.rs | 133 ++++++++++++++++++ crates/horizon-client/src/entity.wgsl | 18 ++- crates/horizon-client/src/extras.rs | 25 +++- crates/horizon-client/src/game.rs | 14 ++ .../horizon-client/src/game/dynamic_lights.rs | 67 +++++++++ crates/horizon-client/src/gfx.rs | 16 ++- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/terrain.wgsl | 20 ++- docs/extras.md | 18 ++- 9 files changed, 301 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-client/src/dynamic_light.rs create mode 100644 crates/horizon-client/src/game/dynamic_lights.rs diff --git a/crates/horizon-client/src/dynamic_light.rs b/crates/horizon-client/src/dynamic_light.rs new file mode 100644 index 000000000..4502b3356 --- /dev/null +++ b/crates/horizon-client/src/dynamic_light.rs @@ -0,0 +1,133 @@ +//! Horizon Extras' dynamic lights (docs/extras.md): a torch, lantern or other light source held by +//! a player or mob, dropped as an item, or an entity on fire lights the blocks and entities +//! around it. Not in vanilla; off by default. +//! +//! Client-only and at render time: the light engine, chunk meshes and saves never see it. Each +//! frame the game picks the [`MAX`] sources nearest the camera; terrain.wgsl and entity.wgsl +//! raise a vertex's block light to `level - distance` (one level per block, as block light falls +//! off) when that is brighter. Off, the list is empty and the shaders skip the loop. +use crate::blocks::BlockFacts; +use glam::DVec3; +use horizon_world::registry::BlockRegistry; +use std::collections::HashMap; + +/// Lights the shaders read: `Globals.dynamic_lights` in gfx.rs, terrain.wgsl and entity.wgsl. +pub const MAX: usize = 16; +/// What an entity on fire gives off, as a lit campfire or fire block does. +pub const BURNING: u8 = 15; +/// Sources farther than this from the camera light nothing it can see well. +const REACH: f64 = 96.0; + +/// How brightly each item glows when held or dropped. +#[derive(Debug, Default)] +pub struct Luminance(HashMap); + +impl Luminance { + /// A block item glows like its block's default state (`getLightEmission`): torches 14, + /// lanterns and glowstone 15, a lit redstone torch 7; a furnace's item, unlit, not at all. + pub fn new(facts: &BlockFacts, registry: &BlockRegistry) -> Self { + let mut map = HashMap::new(); + for (id, state) in facts.states.iter().enumerate() { + if state.emission == 0 || *state.item != *state.name { + continue; + } + if registry.default_state(&state.name).map(|d| d.0 as usize) == Some(id) { + map.insert(state.item.to_string(), state.emission); + } + } + // A bucket of lava glows as lava does. + map.insert("minecraft:lava_bucket".into(), 15); + Self(map) + } + + pub fn of(&self, item: &str) -> u8 { + self.0.get(item).copied().unwrap_or(0) + } + + #[cfg(test)] + fn from_pairs(pairs: &[(&str, u8)]) -> Self { + Self(pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()) + } +} + +/// One light this frame: where it is (world space) and its level, 1 to 15. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Source { + pub at: DVec3, + pub level: u8, +} + +/// The [`MAX`] sources nearest `camera` within reach, as the shaders read them: camera-relative +/// position and level. Overwrites `out`. +pub fn select(sources: &[Source], camera: DVec3, out: &mut Vec<[f32; 4]>) { + out.clear(); + let key = |s: &Source| s.at.distance_squared(camera); + let mut near: Vec<&Source> = sources + .iter() + .filter(|s| s.level > 0 && key(s) <= REACH * REACH) + .collect(); + near.sort_by(|a, b| key(a).total_cmp(&key(b))); + out.extend(near.into_iter().take(MAX).map(|s| { + let p = (s.at - camera).as_vec3(); + [p.x, p.y, p.z, f32::from(s.level.min(15))] + })); +} + +/// The block light a vertex at `pos` (camera-relative) gets from `lights`, 0 to 15: the WGSL +/// `dynamic_block_light` in Rust, for tests. +pub fn level_at(pos: [f32; 3], lights: &[[f32; 4]]) -> f32 { + lights.iter().fold(0.0f32, |level, l| { + let d = + ((pos[0] - l[0]).powi(2) + (pos[1] - l[1]).powi(2) + (pos[2] - l[2]).powi(2)).sqrt(); + level.max(l[3] - d) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn nearest_sources_win() { + let camera = DVec3::new(100.0, 64.0, 100.0); + let mut sources: Vec = (0..40) + .map(|i| Source { + at: camera + DVec3::new(f64::from(i), 0.0, 0.0), + level: 14, + }) + .collect(); + sources.push(Source { + at: camera + DVec3::new(0.5, 0.0, 0.0), + level: 0, + }); + sources.push(Source { + at: camera + DVec3::new(0.0, 0.0, 200.0), + level: 15, + }); + let mut out = Vec::new(); + select(&sources, camera, &mut out); + assert_eq!(out.len(), MAX); + assert_eq!(out[0], [0.0, 0.0, 0.0, 14.0]); + assert_eq!(out[MAX - 1][0], (MAX - 1) as f32); + select(&[], camera, &mut out); + assert!(out.is_empty()); + } + + #[test] + fn light_falls_off_a_level_per_block() { + let torch = [[0.0, 0.0, 0.0, 14.0]]; + assert_eq!(level_at([0.0, 0.0, 0.0], &torch), 14.0); + assert_eq!(level_at([3.0, 4.0, 0.0], &torch), 9.0); + assert_eq!(level_at([20.0, 0.0, 0.0], &torch), 0.0); + let two = [[0.0, 0.0, 0.0, 14.0], [10.0, 0.0, 0.0, 15.0]]; + assert_eq!(level_at([8.0, 0.0, 0.0], &two), 13.0); + assert_eq!(level_at([0.0; 3], &[]), 0.0); + } + + #[test] + fn item_luminance() { + let l = Luminance::from_pairs(&[("minecraft:torch", 14)]); + assert_eq!(l.of("minecraft:torch"), 14); + assert_eq!(l.of("minecraft:stone"), 0); + } +} diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 42113df78..2c6af26f9 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -14,11 +14,13 @@ struct Globals { // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) - // y: Nether cardinal lighting. + // y: Nether cardinal lighting, z: how many dynamic_lights are set. time: vec4, crumbling_sprite: vec4, // Selection outline parameters (read by terrain.wgsl). outline_params: vec4, + // Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs). + dynamic_lights: array, 16>, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var atlas: texture_2d; @@ -58,13 +60,25 @@ fn overlay_texel(overlay: u32) -> vec4 { if overlay >= 16u && overlay < 32u { return vec4(1.0, 1.0, 1.0, WHITE_OVERLAY_ALPHA[overlay - 16u]); } return vec4(1.0); } +// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units +// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one +// level less per block. time.z of them are set: none when the extra is off, so no loop runs. +fn dynamic_block_light(pos: vec3) -> f32 { + let count = min(u32(globals.time.z), 16u); + var level = 0.0; + for (var i = 0u; i < count; i++) { + let l = globals.dynamic_lights[i]; + level = max(level, l.w - distance(pos, l.xyz)); + } + return level * 16.0; +} fn entity_vertex(position: vec3, uv: vec2, overlay: u32, color: vec4, light: vec4, normal: vec4) -> Out { var out: Out; out.clip = globals.view_proj * vec4(position, 1.0); out.proj = vec4(out.clip.xy * 0.5 + out.clip.w * 0.5, out.clip.zw); out.uv = uv; - let l = vec2(f32(light.y), f32(light.x)); + let l = vec2(max(f32(light.y), dynamic_block_light(position)), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); // Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit. diff --git a/crates/horizon-client/src/extras.rs b/crates/horizon-client/src/extras.rs index adbc6e23a..c7be78019 100644 --- a/crates/horizon-client/src/extras.rs +++ b/crates/horizon-client/src/extras.rs @@ -69,6 +69,8 @@ impl Corner { #[derive(Clone, Debug, PartialEq)] pub struct Extras { pub fullbright: bool, + /// Held, dropped and burning light sources light their surroundings (`dynamic_light`). + pub dynamic_lights: bool, pub zoom: bool, /// A vanilla key name (`key.keyboard.z`). pub zoom_key: String, @@ -110,6 +112,7 @@ impl Default for Extras { fn default() -> Self { Self { fullbright: false, + dynamic_lights: false, zoom: false, zoom_key: "key.keyboard.z".into(), zoom_level: 4, @@ -158,6 +161,7 @@ impl Extras { }; match key.trim() { "fullbright" => e.fullbright = flag(e.fullbright), + "dynamicLights" => e.dynamic_lights = flag(e.dynamic_lights), "zoom" => e.zoom = flag(e.zoom), "zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(), "zoomLevel" => { @@ -201,8 +205,9 @@ impl Extras { } pub fn serialize(&self) -> String { format!( - "fullbright:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", + "fullbright:{}\ndynamicLights:{}\nzoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\nmouseTweaks:{}\nmouseTweaksWheel:{}\nsort:{}\nsortKey:{}\n", bool_text(self.fullbright), + bool_text(self.dynamic_lights), bool_text(self.zoom), self.zoom_key, self.zoom_level, @@ -423,6 +428,7 @@ impl Cps { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Item { Fullbright, + DynamicLights, Zoom, ZoomKey, ZoomLevel, @@ -452,6 +458,7 @@ pub fn rows() -> Vec> { vec![ Err("Lighting"), Ok(Fullbright), + Ok(DynamicLights), Err("Zoom"), Ok(Zoom), Ok(ZoomKey), @@ -501,6 +508,7 @@ impl Item { pub fn caption(self) -> &'static str { match self { Item::Fullbright => "Fullbright", + Item::DynamicLights => "Dynamic lights", Item::Zoom => "Zoom", Item::ZoomKey => "Zoom key", Item::ZoomLevel => "Starting zoom", @@ -533,7 +541,8 @@ impl Item { KeystrokesCorner | KeystrokesCps => Keystrokes, MouseTweaksWheel => MouseTweaks, SortKey => Sort, - Fullbright | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort | AutoReconnect => { + Fullbright | DynamicLights | Zoom | Minimap | Fps | Keystrokes | MouseTweaks | Sort + | AutoReconnect => { return None; } }) @@ -542,6 +551,9 @@ impl Item { pub fn description(self) -> &'static str { match self { Item::Fullbright => "Show blocks and entities at full light, even in dark areas.", + Item::DynamicLights => { + "Torches and other light sources held, dropped or on fire light the blocks around them." + } Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.", Item::ZoomKey => "Click, then press a key. Escape unbinds it.", Item::ZoomLevel => "The zoom the key starts at.", @@ -581,7 +593,7 @@ impl Item { use crate::graphics_style::Cost; match self { Item::Fullbright | Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None), - Item::Minimap => Some(Cost::Low), + Item::Minimap | Item::DynamicLights => Some(Cost::Low), Item::AutoReconnect | Item::MouseTweaks | Item::Sort => Some(Cost::None), _ => None, } @@ -590,6 +602,7 @@ impl Item { pub fn switch(self, e: &Extras) -> Option { Some(match self { Item::Fullbright => e.fullbright, + Item::DynamicLights => e.dynamic_lights, Item::Zoom => e.zoom, Item::ZoomSmooth => e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity, @@ -632,6 +645,7 @@ impl Item { pub fn cycle(self, e: &mut Extras, back: bool) { match self { Item::Fullbright => e.fullbright = !e.fullbright, + Item::DynamicLights => e.dynamic_lights = !e.dynamic_lights, Item::Zoom => e.zoom = !e.zoom, Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth, Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity, @@ -677,7 +691,7 @@ mod tests { #[test] fn everything_is_off_by_default_and_round_trips() { let d = Extras::default(); - assert!(!d.fullbright); + assert!(!d.fullbright && !d.dynamic_lights); assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect); assert!(!d.mouse_tweaks && !d.sort); assert_eq!(Extras::parse(""), d); @@ -685,6 +699,9 @@ mod tests { let mut e = d.clone(); Item::Fullbright.cycle(&mut e, false); assert_eq!(Item::Fullbright.switch(&e), Some(true)); + Item::DynamicLights.cycle(&mut e, false); + assert_eq!(Item::DynamicLights.switch(&e), Some(true)); + assert_eq!(Extras::parse(&e.serialize()), e); e.zoom = true; e.zoom_key = "key.keyboard.c".into(); e.zoom_level = 6; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a25e8fdeb..092783ca8 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -37,6 +37,7 @@ mod dedicated; mod dispense_fixture; mod dispenser; mod dragon; +mod dynamic_lights; mod enchant_effects; mod end; mod entity_culling; @@ -1177,6 +1178,10 @@ struct Game<'a> { renderer: Option, /// CPU geometry storage retained across frames, including empty/title frames. entity_vertices: Vec, + /// Horizon Extras' dynamic lights this frame (`dynamic_lights.rs`), and how brightly each + /// item glows (built the first time the extra is on). + dynamic_lights: Vec<[f32; 4]>, + luminance: Option, /// Name tags drawn over everything (`RenderPipelines.TEXT_SEE_THROUGH`). see_through_vertices: Vec, started: Instant, @@ -9636,6 +9641,11 @@ impl Game<'_> { .then(|| self.border_draw(camera.to_array(), alpha as f32)) .flatten(); let see_through = std::mem::take(&mut self.see_through_vertices); + if title { + self.dynamic_lights.clear(); + } else { + self.gather_dynamic_lights(camera, alpha); + } let frame = Frame { shader: self.shader_inputs(camera, alpha as f32), nether_lighting: self.dim == Dim::Nether, @@ -9693,6 +9703,7 @@ impl Game<'_> { color: sky.cloud_color, }), entities: &entities, + dynamic_lights: &self.dynamic_lights, additive: &additive, see_through: &see_through, celestial: if self.settings.horizon.sky || title { @@ -11283,6 +11294,8 @@ impl<'a> Game<'a> { window: None, renderer: None, entity_vertices: Vec::new(), + dynamic_lights: Vec::new(), + luminance: None, see_through_vertices: Vec::new(), health_hud: hud_layout::HealthHud::default(), started: now, @@ -12156,6 +12169,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { hud, nether_lighting: false, entities: &[], + dynamic_lights: &[], clouds: None, additive: &[], see_through: &[], diff --git a/crates/horizon-client/src/game/dynamic_lights.rs b/crates/horizon-client/src/game/dynamic_lights.rs new file mode 100644 index 000000000..cd4223d82 --- /dev/null +++ b/crates/horizon-client/src/game/dynamic_lights.rs @@ -0,0 +1,67 @@ +//! Horizon Extras' dynamic lights (`horizon_client::dynamic_light`): the light sources near the +//! camera this frame. Nothing is gathered while the extra is off. +use super::{Game, shield}; +use glam::DVec3; +use horizon_client::dynamic_light::{self, BURNING, Luminance, Source}; + +impl Game<'_> { + /// Fills `dynamic_lights` for the frame: the player's and mobs' held items and fire, and + /// glowing dropped items, the nearest [`dynamic_light::MAX`] of them. + pub(super) fn gather_dynamic_lights(&mut self, camera: DVec3, alpha: f64) { + let mut out = std::mem::take(&mut self.dynamic_lights); + out.clear(); + if !self.settings.extras.dynamic_lights { + self.dynamic_lights = out; + return; + } + if self.luminance.is_none() { + self.luminance = Some(Luminance::new(self.res.facts(), self.pack.assets.registry)); + } + let lum = self.luminance.as_ref().expect("built above"); + let held = |item: Option<&str>| item.map_or(0, |i| lum.of(i)); + let mut sources = Vec::new(); + if let Some(p) = &self.player + && !p.spectator + { + let feet = self + .previous_position + .lerp(p.position, self.clock.camera_fraction()); + let level = held(self.stack_in(self.selected).map(|s| &*s.item)) + .max(held(self.stack_in(shield::OFFHAND_SLOT).map(|s| &*s.item))) + .max(if p.fire_ticks > 0 { BURNING } else { 0 }); + // About where the hands are. + sources.push(Source { + at: DVec3::new(feet.x, feet.y + 1.2, feet.z), + level, + }); + } + for m in self.mobs.iter().filter(|m| !m.removed) { + let level = held(m.extra.main_hand.as_deref()) + .max(held(m.extra.off_hand.as_deref())) + .max(if m.fire_ticks > 0 { BURNING } else { 0 }); + if level == 0 { + continue; + } + let at = m.previous.lerp(m.position, alpha); + sources.push(Source { + at: DVec3::new(at.x, at.y + f64::from(m.height()) * 0.6, at.z), + level, + }); + } + for item in &self.dropped { + let level = lum + .of(&item.stack.item) + .max(if item.fire_ticks > 0 { BURNING } else { 0 }); + if level == 0 { + continue; + } + let at = item.previous.lerp(item.position, alpha); + sources.push(Source { + at: DVec3::new(at.x, at.y + 0.25, at.z), + level, + }); + } + dynamic_light::select(&sources, camera, &mut out); + self.dynamic_lights = out; + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 127aaf737..da53c42ed 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -107,13 +107,16 @@ struct Globals { fog_ends: [f32; 4], /// Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: [[f32; 4]; 2], - /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting, zw unused. + /// x: vanilla's `GameTime` uniform; y: nether cardinal lighting; z: how many + /// `dynamic_lights` are set; w unused. time: [f32; 4], /// Atlas rect of a destroy stage (entity.wgsl takes only its size: every stage's is the same, /// and each crack carries its own stage's origin). crumbling_sprite: [f32; 4], /// Framebuffer size, selection stroke width, perspective layering scale. outline_params: [f32; 4], + /// Horizon Extras' dynamic lights: camera-relative position and level (`dynamic_light`). + dynamic_lights: [[f32; 4]; crate::dynamic_light::MAX], } pub type SectionKey = (i32, i32, i32); struct SectionGpu { @@ -186,6 +189,8 @@ pub struct Frame<'a> { pub nether_lighting: bool, /// Camera-relative entity geometry textured from the shared atlas. pub entities: &'a [Vertex], + /// Horizon Extras' dynamic lights, nearest first (`dynamic_light::select`); empty when off. + pub dynamic_lights: &'a [[f32; 4]], /// Cloud mesh inputs; geometry and GPU storage are retained by the renderer. pub clouds: Option>, /// Additive translucent geometry after the entities (lightning, dragon rays). @@ -2908,10 +2913,17 @@ impl Renderer { time: [ frame.shader_game_time, f32::from(frame.nether_lighting), - 0.0, + frame.dynamic_lights.len().min(crate::dynamic_light::MAX) as f32, 0.0, ], outline_params: outline_params(self.config.width, self.config.height), + dynamic_lights: { + let mut lights = [[0.0; 4]; crate::dynamic_light::MAX]; + for (to, from) in lights.iter_mut().zip(frame.dynamic_lights) { + *to = *from; + } + lights + }, }; self.uploads .buffer(&mut encoder, &self.globals, 0, bytemuck::bytes_of(&globals)); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 7a69de4aa..4cf0c5c48 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -51,6 +51,7 @@ pub mod datapack; pub mod debug_chart; pub mod debug_keys; pub mod debug_overlay; +pub mod dynamic_light; pub mod effects; pub mod enchant; pub mod end_crystal; diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index be3405b23..c0a2fc6fd 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -16,11 +16,14 @@ struct Globals { fog_ends: vec4, // Atlas rects (u0, v0, width, height) of end_sky.png and end_portal.png. end_portal_sprites: array, 2>, - // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000) + // x: vanilla's GameTime ((game time % 24000 + partial tick) / 24000), z: how many + // dynamic_lights are set time: vec4, // Atlas rect of the current destroy stage (read by entity.wgsl). crumbling_sprite: vec4, outline_params: vec4, + // Horizon Extras' dynamic lights: camera-relative position and level (dynamic_light.rs). + dynamic_lights: array, 16>, } @group(0) @binding(0) var globals: Globals; @group(0) @binding(1) var sprites: texture_2d_array; @@ -67,6 +70,18 @@ struct TerrainOut { @location(3) spherical: f32, @location(4) cylindrical: f32, } +// Horizon Extras' dynamic lights (dynamic_light.rs): the block light, in the vertex's units +// (16 per level), a vertex at camera-relative `pos` gets from the frame's light sources, one +// level less per block. time.z of them are set: none when the extra is off, so no loop runs. +fn dynamic_block_light(pos: vec3) -> f32 { + let count = min(u32(globals.time.z), 16u); + var level = 0.0; + for (var i = 0u; i < count; i++) { + let l = globals.dynamic_lights[i]; + level = max(level, l.w - distance(pos, l.xyz)); + } + return level * 16.0; +} fn sample_lightmap(sky: f32, block: f32) -> vec4 { let uv = vec2(block, sky) * 16.0; return textureSampleLevel(lightmap, lightmap_sampler, @@ -105,7 +120,8 @@ fn terrain_vertex(position: vec3, uv: vec2, layer: u32, color: vec4 Date: Thu, 22 Oct 2026 07:24:24 +0200 Subject: [PATCH 069/115] Moving pistons: pass the block position to particle_sprite (main build fix) #1113 (moving pistons) and #1115 (break particles, which gave particle_sprite a position for its biome tint) each passed alone; together main no longer compiled. A moving block now takes its tint at its own block position, as vanilla's moving-block renderer reads the level's tint there. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/moving_pistons.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs index 8b47483df..17247850e 100644 --- a/crates/horizon-client/src/game/moving_pistons.rs +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -88,7 +88,9 @@ impl Game<'_> { light: u32, out: &mut Vec, ) { - let tint = self.particle_sprite(state).map(|(_, tint)| tint); + let tint = self + .particle_sprite(state, [seed.x, seed.y, seed.z]) + .map(|(_, tint)| tint); let start = out.len(); self.block_model_vertices( state, From 8e700aa68362a9d9b0c377c84fbb760055a4e8e9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 01:57:06 +0200 Subject: [PATCH 070/115] Riptide: run vanilla's auto-spin attack after the launch Releasing a Riptide trident now starts LivingEntity.startAutoSpinAttack(20, 8.0): for 20 ticks the player takes the SPIN_ATTACK pose (0.6x0.6, eye height 0.4), hits the first living entity its swept box touches for the spin's damage and bounces back (velocity x -0.2), and stops on a horizontal collision. The player model spins (setupRotations: rotX(-90 - xRot), rotY(age * -75)), SpinAttackEffectLayer draws the riptide boxes, and the first-person hand uses ItemInHandRenderer's spin transform. LAN guests see the host's spin through living flag bit 4. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/first_person.rs | 8 ++ crates/horizon-client/src/game.rs | 33 ++++++++- crates/horizon-client/src/game/lan.rs | 4 +- crates/horizon-client/src/game/perspective.rs | 44 +++++++++++ crates/horizon-client/src/game/trident.rs | 35 +++++++++ crates/horizon-client/src/mobs.rs | 2 + crates/horizon-client/src/mobs/render.rs | 9 ++- crates/horizon-client/src/motion.rs | 74 +++++++++++++++++++ crates/horizon-client/src/pose.rs | 8 +- 9 files changed, 210 insertions(+), 7 deletions(-) diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index a25d9f537..463d51437 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -21,6 +21,8 @@ pub enum ItemPose { Trident { ticks_used: f32, }, + /// Riptide's spin (`isAutoSpinAttack`): the item held up like a fork. + SpinAttack, Bow { ticks_used: f32, }, @@ -67,6 +69,12 @@ pub fn item_pose(left: bool, inverse_height: f32, attack: f32, pose: ItemPose) - if matches!(pose, ItemPose::Using) { return m; } + if matches!(pose, ItemPose::SpinAttack) { + return m + * Mat4::from_translation(Vec3::new(invert * -0.4, 0.8, 0.3)) + * Mat4::from_rotation_y((invert * 65.0f32).to_radians()) + * Mat4::from_rotation_z((invert * -85.0f32).to_radians()); + } let charging = match pose { ItemPose::Bow { ticks_used } => { let power = ticks_used / 20.0; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..36c16e61f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -896,6 +896,8 @@ struct WorldRest { behaviours: Behaviours, player_arm: Option, player_type: Option>, + /// `SpinAttackEffectModel` (Riptide's spinning boxes). + spin_attack: Option, stations: horizon_client::stations::StationData, } @@ -971,6 +973,9 @@ impl Resources { fn player_type(&self) -> &Option> { &self.rest().player_type } + fn spin_attack(&self) -> &Option { + &self.rest().spin_attack + } fn stations(&self) -> &horizon_client::stations::StationData { &self.rest().stations } @@ -3907,6 +3912,7 @@ impl Game<'_> { } let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); + let spin_targets = self.spin_targets(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -3984,6 +3990,7 @@ impl Game<'_> { .any(|s| immune.is_some_and(|t| t.contains(&*s.item))); // The dimension's FAST_LAVA: the Nether's lava pushes harder. player.fluids.fast_lava = self.dim == Dim::Nether; + player.spin_targets = spin_targets; let grounded = player.ground.on_ground; let before = ( grounded, @@ -4006,6 +4013,7 @@ impl Game<'_> { } } let events = std::mem::take(&mut player.events); + let spin_hit = player.spin_hit.take(); let glider_wear = std::mem::take(&mut player.glider_wear); if glider_wear > 0 && !self.creative @@ -4024,6 +4032,7 @@ impl Game<'_> { self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); + self.end_spin_attack(spin_hit); self.record_combat(&events); for event in events { match event { @@ -6751,7 +6760,13 @@ impl Game<'_> { /// enchantments. pub(super) fn melee_damage(&mut self, target_kind: &str) -> (f32, f32, bool) { let hand_damage = 1.0 + self.attack_item_info().map_or(0.0, |i| i.attack_damage); - let damage = hand_damage + self.effect_attack_bonus(); + // Riptide's spin replaces the attack damage attribute. + let spin = self.player.as_ref().map_or(0.0, |p| p.auto_spin_attack_dmg); + let damage = if spin > 0.0 { + spin + } else { + hand_damage + self.effect_attack_bonus() + }; let scale = self.attack_strength_scale(); let mut amount = damage * (0.2 + scale * scale * 0.8); // Item.getAttackDamageBonus (a mace's smash), before the critical hit. @@ -6879,6 +6894,14 @@ impl Game<'_> { return false; } } + self.attack_mob(index); + // Minecraft.startAttack swings after the attack. + self.swing_arm(); + true + } + /// `Player.attack` on a mob: the damage, knockback, sweep, particles and + /// sounds. + pub(super) fn attack_mob(&mut self, index: usize) { let target_kind = self.mobs[index].kind.id.clone(); let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:")); let (amount, scale, crit) = self.melee_damage(&target_kind); @@ -6896,7 +6919,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.knockback", from, 1.0, 1.0); } - self.swing_arm(); // LivingEntity.setLastHurtMob (tamed wolves join in). self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time)); let old_health = self.mobs[index].health; @@ -6989,7 +7011,6 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); } - true } /// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step. /// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the @@ -8489,6 +8510,10 @@ impl Game<'_> { } let shown = self.hands_to_render(); let used_hand = self.used_hand(); + let spinning = self + .player + .as_ref() + .is_some_and(|p| p.auto_spin_attack_ticks > 0); for (i, (hand, item)) in Hand::BOTH .into_iter() .zip(self.visible_hand_items()) @@ -8608,6 +8633,7 @@ impl Game<'_> { ItemPose::Using } } + _ if spinning => ItemPose::SpinAttack, _ => ItemPose::Swing, }; let m = to_world @@ -12052,6 +12078,7 @@ fn load_world_rest( player_type: perspective::player_type(root), player_arm: horizon_client::mobs::load_model(root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), + spin_attack: horizon_client::mobs::load_model(root, "minecraft:spin_attack#main"), }) } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index f9ea1262b..8e641b61f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -740,7 +740,9 @@ impl Game<'_> { equipment, health: p.health.health(), attributes: horizon_client::lan::attributes::syncable(&p.attributes), - living_flags: living_flags(self.using), + // Bit 4: Riptide's spin (LivingEntity.isAutoSpinAttack). + living_flags: living_flags(self.using) + | if p.auto_spin_attack_ticks > 0 { 4 } else { 0 }, bed: self.sleeping, }) } diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index ec46120dd..bd2721648 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -312,6 +312,7 @@ impl Game<'_> { let crouching = p.pose == Pose::Crouching; let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); + let spinning = p.auto_spin_attack_ticks > 0; let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); let using_off_hand = self .using @@ -397,6 +398,7 @@ impl Game<'_> { m.velocity = velocity; m.extra.fall_flying = fall_flying; m.extra.fall_fly_ticks = fly_ticks; + m.extra.auto_spin_attack = spinning; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; m.extra.using_off_hand = using_off_hand; @@ -451,6 +453,7 @@ impl Game<'_> { out, ); self.player_elytra_geometry(m, camera, alpha as f32, packed, out); + self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); } /// `extractEntityInInventoryFollowsMouse`: the player in the box @@ -592,6 +595,47 @@ impl Game<'_> { out, ); } + /// `SpinAttackEffectLayer`: Riptide's two boxes turning around a spinning + /// player (`SpinAttackEffectModel.setupAnim`). + fn spin_attack_geometry( + &self, + m: &Mob, + camera: glam::DVec3, + partial: f32, + light: u32, + out: &mut Vec, + ) { + if !m.extra.auto_spin_attack { + return; + } + let (Some(model), Some(rect)) = ( + self.res.spin_attack().as_ref(), + self.gui.atlas.sprites.get("entity/trident/trident_riptide"), + ) else { + return; + }; + let age = m.age as f32 + partial; + horizon_client::mobs::render_model( + model, + horizon_client::mobs::render::base_transform(m, partial, camera), + &|part| { + let mut p = part.pose; + if let Some(i) = part + .name + .strip_prefix("box") + .and_then(|i| i.parse::().ok()) + { + let angle = age * -(45.0 + f32::from(i + 1) * 5.0); + p[4] = wrap(angle).to_radians(); + } + p + }, + [rect.u0, rect.v0, rect.u1, rect.v1], + light, + 0, + out, + ); + } } fn player_preview_quads( diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index b24f4540e..c31094596 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -122,6 +122,38 @@ impl Game<'_> { let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) } + /// The living entities a spinning player can touch this tick, for + /// `LivingEntity.checkAutoSpinAttack` (none when not spinning). + pub(super) fn spin_targets(&self) -> Vec<(u32, Aabb)> { + let Some(p) = self + .player + .as_ref() + .filter(|p| p.auto_spin_attack_ticks > 0) + else { + return Vec::new(); + }; + // A spin moves a few blocks a tick at most. + let near = p.bounds().inflate(Vec3::new(16.0, 16.0, 16.0)); + self.mobs + .iter() + .filter(|m| m.alive() && m.bounds().intersects(near)) + .map(|m| (m.id, m.bounds())) + .collect() + } + /// `Player.doAutoAttackOnTouch`: the touched entity takes `Player.attack` + /// with the spin's damage; once the spin is over its damage is cleared. + pub(super) fn end_spin_attack(&mut self, hit: Option) { + if let Some(id) = hit + && let Some(index) = self.mobs.iter().position(|m| m.id == id) + { + self.attack_mob(index); + } + if let Some(p) = self.player.as_mut() + && p.auto_spin_attack_ticks <= 0 + { + p.auto_spin_attack_dmg = 0.0; + } + } /// `TridentItem.releaseUsing`. pub(super) fn release_trident(&mut self, ticks: u32) { if ticks < 10 { @@ -152,6 +184,9 @@ impl Game<'_> { p.velocity.y + d[1] * f64::from(strength), p.velocity.z + d[2] * f64::from(strength), ); + // Player.startAutoSpinAttack(20, 8, stack). + p.auto_spin_attack_ticks = 20; + p.auto_spin_attack_dmg = 8.0; if p.ground.on_ground { p.position.y += 1.2; } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 28bcadeed..e87032f07 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -690,6 +690,8 @@ pub struct Extra { pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, + /// `LivingEntity.isAutoSpinAttack` (Riptide). + pub auto_spin_attack: bool, pub main_hand_left: bool, pub elytra: ElytraAnimation, pub swim: SwimAnimation, diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 99548ec3f..4248f22c6 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -771,6 +771,11 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .sqrt() .min(1.0); base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if m.extra.auto_spin_attack { + // Riptide: lying along the look direction, spinning 75 degrees a tick. + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + base *= glam::Mat4::from_rotation_x((-90.0 - pitch).to_radians()) + * glam::Mat4::from_rotation_y(((m.age as f32 + alpha) * -75.0).to_radians()); } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { // isEntityUpsideDown base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) @@ -781,7 +786,9 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; - base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + if !m.extra.auto_spin_attack { + base *= glam::Mat4::from_rotation_x((scale * (-90.0 - pitch)).to_radians()); + } let yaw = m.previous_head_yaw + wrap(m.head_yaw - m.previous_head_yaw) * alpha; let (look_x, look_z) = (-(yaw.to_radians()).msin(), (yaw.to_radians()).mcos()); let v = m.velocity; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 7bdaea785..192e900a1 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -247,6 +247,14 @@ pub struct PlayerMotion { pub glide_ending: bool, /// Glider durability to take this tick (updateFallFlying). pub glider_wear: u32, + /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's + /// spin. The damage stays until the game has dealt the hit. + pub auto_spin_attack_ticks: i32, + pub auto_spin_attack_dmg: f32, + /// The living entities the game put near a spinning player (id, box). + pub spin_targets: Vec<(u32, Aabb)>, + /// The entity the spin touched this tick (`doAutoAttackOnTouch`). + pub spin_hit: Option, pub sprinting: bool, pub sprint_input: crate::sprint::SprintState, pub shift_key_down: bool, @@ -409,6 +417,10 @@ impl PlayerMotion { fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, + auto_spin_attack_ticks: 0, + auto_spin_attack_dmg: 0.0, + spin_targets: Vec::new(), + spin_hit: None, sprinting: false, sprint_input: crate::sprint::SprintState::default(), shift_key_down: false, @@ -919,6 +931,7 @@ impl MotionWorld<'_, '_, '_> { input.z = 0.0; } self.jump_phase()?; + let before_travel = self.player.bounds(); // Player.travel: swim steering, then LivingEntity.travel (fluids // first, then gliding, then air), keeping 0.6 of the vertical speed // while flying. @@ -973,8 +986,26 @@ impl MotionWorld<'_, '_, '_> { { self.freeze_damage()?; } + if self.player.auto_spin_attack_ticks > 0 { + self.player.auto_spin_attack_ticks -= 1; + self.check_auto_spin_attack(before_travel); + } Ok(()) } + /// `LivingEntity.checkAutoSpinAttack`: the first living entity in the + /// box swept this tick takes the hit and ends the spin, bouncing the + /// player back at a fifth of its speed; a wall ends it too. + fn check_auto_spin_attack(&mut self, before: Aabb) { + let swept = before.union_bounds(self.player.bounds()); + let p = &mut self.player; + if let Some(&(id, _)) = p.spin_targets.iter().find(|(_, b)| b.intersects(swept)) { + p.spin_hit = Some(id); + p.auto_spin_attack_ticks = 0; + p.velocity = p.velocity.scale(-0.2); + } else if p.collision.horizontal { + p.auto_spin_attack_ticks = 0; + } + } /// `hurtServer(damageSources().freeze(), 1)` for a fully frozen player. fn freeze_damage(&mut self) -> Result<()> { let id = self @@ -2659,6 +2690,49 @@ mod tests { } } #[test] + fn a_riptide_spin_lies_flat_and_ends_on_the_first_entity_it_touches() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let ahead = Aabb::new(Vec3::new(20.2, 9.0, 21.5), Vec3::new(20.8, 11.0, 22.1)); + for target in [None, Some(ahead)] { + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + player.auto_spin_attack_ticks = 20; + player.auto_spin_attack_dmg = 8.0; + player.velocity = Vec3::new(0.0, 0.0, 1.0); + player.spin_targets = target.map(|b| (7, b)).into_iter().collect(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.simulation_tick([0.0, 0.0], false).unwrap(); + if target.is_some() { + // Touched: the hit, no more spin, bounced back at a fifth. + assert_eq!(w.player.spin_hit, Some(7)); + assert_eq!(w.player.auto_spin_attack_ticks, 0); + assert!(w.player.velocity.z < 0.0, "{:?}", w.player.velocity); + assert_eq!(w.player.pose, crate::pose::Pose::Standing); + } else { + assert_eq!(w.player.spin_hit, None); + assert_eq!(w.player.auto_spin_attack_ticks, 19); + assert_eq!(w.player.pose, crate::pose::Pose::SpinAttack); + assert_eq!(w.player.dimensions.height, 0.6); + } + } + } + #[test] fn a_landing_glide_lasts_a_tick_so_a_jump_keeps_its_speed() { let root = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client") diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index 9c8124b0e..e34b1f1fc 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -14,6 +14,7 @@ pub enum Pose { Crouching, Swimming, FallFlying, + SpinAttack, } impl Pose { pub fn name(self) -> &'static str { @@ -22,13 +23,14 @@ impl Pose { Self::Crouching => "CROUCHING", Self::Swimming => "SWIMMING", Self::FallFlying => "FALL_FLYING", + Self::SpinAttack => "SPIN_ATTACK", } } pub fn dimensions(self, scale: f32) -> Dimensions { let (height, eye_height) = match self { Self::Standing => (1.8, 1.62), Self::Crouching => (1.5, 1.27), - Self::Swimming | Self::FallFlying => (0.6, 0.4), + Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4), }; Dimensions { width: 0.6 * scale, @@ -98,11 +100,13 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - // Player.getDesiredPose: swimming before gliding. + // Player.getDesiredPose: swimming, gliding, Riptide's spin. let desired = if self.player.swimming { Pose::Swimming } else if self.player.fall_flying { Pose::FallFlying + } else if self.player.auto_spin_attack_ticks > 0 { + Pose::SpinAttack } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { From c2b7f3a4ea2dc5fdb86f4aa6469eabc4b2a26e22 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:55:54 +0200 Subject: [PATCH 071/115] Slow-frame and slow-tick lines show the CPU time of each span HORIZON_SPIKES spans keep the thread's CPU time beside their wall time, and the slow-frame line gives the render thread's CPU time in the frame. A span that mostly waited (for the GPU, a lock or a core) prints both (`submit 30.2/0.1`), so a frame that waited reads apart from one that worked. Found the cause of #678's long frames: the render thread losing its core in queue.submit. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 21 +++-- crates/horizon-client/src/game/levels.rs | 7 +- crates/horizon-client/src/spans.rs | 100 ++++++++++++++++++++--- docs/graphics.md | 2 +- 4 files changed, 103 insertions(+), 27 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..518fba2db 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10933,6 +10933,10 @@ impl ApplicationHandler for Game<'_> { WindowEvent::RedrawRequested => { self.observe_fullscreen(); let now = Instant::now(); + let frame_cpu = self + .options + .spikes + .and_then(|_| horizon_client::spans::thread_cpu()); let elapsed = now.duration_since(self.previous); self.frame_ticks = elapsed.as_secs_f32() * 20.0; self.previous = now; @@ -10999,15 +11003,16 @@ impl ApplicationHandler for Game<'_> { let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0; let spans = horizon_client::spans::take(); if cpu > threshold { - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); + // The render thread's own CPU time in the frame: + // far below the wall time, the frame waited. + let worked = horizon_client::spans::thread_cpu() + .zip(frame_cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); log::info!( - "Horizon: slow frame {cpu:.1} ms ({} ticks): {}", - steps, - list.join(", ") + "Horizon: slow frame {cpu:.1} ms{worked} ({steps} ticks): {}", + horizon_client::spans::describe(&spans) ); } } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 31b34a9d0..7df5541b4 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -312,15 +312,10 @@ impl Game<'_> { .map_or_else(String::new, |(end, start)| { format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) }); - let list: Vec = spans - .iter() - .filter(|(_, ms)| *ms >= 0.5) - .map(|(n, ms)| format!("{n} {ms:.1}")) - .collect(); log::info!( "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", self.mobs.len(), - list.join(", ") + horizon_client::spans::describe(&spans) ); } result diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index 5c37f2bfc..ce69be8ce 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,8 +1,10 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time //! exceeds MS milliseconds, and of every server tick (dedicated or -//! integrated) longer than MS. Costs one clock read per span when enabled -//! and a relaxed load otherwise. +//! integrated) longer than MS. Each span keeps its wall time and the +//! thread's CPU time inside it, so a span that waited (for a lock, the GPU +//! or a core on a busy machine) shows apart from one that worked. Costs two +//! clock reads per span when enabled and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, @@ -11,7 +13,15 @@ use std::{ static ENABLED: AtomicBool = AtomicBool::new(false); thread_local! { - static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; + static SPANS: RefCell> = const { RefCell::new(Vec::new()) }; +} + +/// A named timing: wall milliseconds and the thread's CPU milliseconds in it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Span { + pub name: &'static str, + pub ms: f32, + pub cpu_ms: f32, } pub fn enable(on: bool) { @@ -23,10 +33,13 @@ pub fn time(name: &'static str, f: impl FnOnce() -> T) -> T { if !ENABLED.load(Ordering::Relaxed) { return f(); } - let started = Instant::now(); + let (started, cpu) = (Instant::now(), thread_cpu()); let out = f(); let ms = started.elapsed().as_secs_f32() * 1000.0; - SPANS.with(|s| s.borrow_mut().push((name, ms))); + let cpu_ms = thread_cpu() + .zip(cpu) + .map_or(ms, |(end, start)| (end - start).as_secs_f32() * 1000.0); + SPANS.with(|s| s.borrow_mut().push(Span { name, ms, cpu_ms })); out } /// The CPU time this thread has used, where the platform tells it: a tick @@ -42,21 +55,84 @@ pub fn thread_cpu() -> Option { None } /// The frame's spans, summed by name, slowest first; clears them. -pub fn take() -> Vec<(&'static str, f32)> { +pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); - let mut sums: Vec<(&'static str, f32)> = Vec::new(); - for (name, ms) in spans { - match sums.iter_mut().find(|(n, _)| *n == name) { - Some(entry) => entry.1 += ms, - None => sums.push((name, ms)), + let mut sums: Vec = Vec::new(); + for span in spans { + match sums.iter_mut().find(|s| s.name == span.name) { + Some(sum) => { + sum.ms += span.ms; + sum.cpu_ms += span.cpu_ms; + } + None => sums.push(span), } } - sums.sort_by(|a, b| b.1.total_cmp(&a.1)); + sums.sort_by(|a, b| b.ms.total_cmp(&a.ms)); sums } +/// `name wall` for spans of at least 0.5 ms, with `/cpu` when the thread +/// worked for less than nine tenths of it: the slow-frame and slow-tick lines. +pub fn describe(spans: &[Span]) -> String { + let list: Vec = spans + .iter() + .filter(|s| s.ms >= 0.5) + .map(|s| { + if s.cpu_ms < s.ms * 0.9 { + format!("{} {:.1}/{:.1}", s.name, s.ms, s.cpu_ms) + } else { + format!("{} {:.1}", s.name, s.ms) + } + }) + .collect(); + list.join(", ") +} #[cfg(test)] mod tests { + use super::Span; + + /// Spans of one name add up; a span the thread spent mostly waiting + /// shows its CPU time after the wall time, short ones are left out. + #[test] + fn spans_sum_by_name_and_show_waits() { + super::SPANS.with(|s| { + s.borrow_mut().extend([ + Span { + name: "tick", + ms: 2.0, + cpu_ms: 2.0, + }, + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2, + }, + Span { + name: "tick", + ms: 3.0, + cpu_ms: 2.9, + }, + Span { + name: "hud", + ms: 0.3, + cpu_ms: 0.3, + }, + ]); + }); + let spans = super::take(); + assert_eq!( + spans[0], + Span { + name: "submit", + ms: 30.0, + cpu_ms: 0.2 + } + ); + assert_eq!((spans[1].name, spans[1].ms), ("tick", 5.0)); + assert_eq!(super::describe(&spans), "submit 30.0/0.2, tick 5.0"); + assert!(super::take().is_empty()); + } + /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. #[cfg(unix)] diff --git a/docs/graphics.md b/docs/graphics.md index b1c3c0209..34032a641 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -64,7 +64,7 @@ python3 tools/graphics_bench.py --compare baseline-4080 mine-gpu # markdown ta vscreen is a headless compositor whose frames are software-rendered (lavapipe), so its frame times measure the CPU, rasterisation included. `--offscreen` (`horizon-client --offscreen`) renders into a texture on the most powerful GPU instead of the window, which measures the RTX 4080 under the same compositor. `--distances`, `--scenes` and `--build` pick a subset or another build. Results go to `benchmarks/graphics/