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