diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index d5ef55d37..726ac278b 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -199,6 +199,28 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> { velocity.z.to_bits() )), MotionEvent::SplashEvent => Some("splash-event".into()), + MotionEvent::Swim { volume, pitch } => Some(format!( + "sound swim entity {:08x} {:08x}", + volume.to_bits(), + pitch.to_bits() + )), + MotionEvent::Emission { + state, + in_water: true, + .. + } => Some(format!("muffled-step {}", state.0)), + MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!( + "column-particle {} {:016x},{:016x},{:016x} 1 {:016x},{:016x},{:016x} {:016x}", + if *bubble { "bubble" } else { "splash" }, + position.x.to_bits(), + position.y.to_bits(), + position.z.to_bits(), + 0f64.to_bits(), + if *bubble { 0.01f64 } else { 0.0 }.to_bits(), + 0f64.to_bits(), + if *bubble { 0.2f64 } else { 1.0 }.to_bits() + )), + MotionEvent::Drown => Some("broadcast 67".into()), // The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so. MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()), MotionEvent::Waypoint { receiver, enabled } => Some(format!( @@ -399,7 +421,8 @@ fn main() -> Result<()> { Some(vector(&op["value"])) }, ), - "block" => { + // A block, or every block of the box from position to "to". + "block" | "fill" => { let p = &op["position"]; let mut state = assets .registry @@ -417,12 +440,15 @@ fn main() -> Result<()> { .id(&definition) .ok_or("missing fixture state")?; } - world.scene.set( - p[0].as_i64().unwrap() as i32, - p[1].as_i64().unwrap() as i32, - p[2].as_i64().unwrap() as i32, - state, - )?; + let at = |v: &Value, i: usize| v[i].as_i64().unwrap() as i32; + let to = if op["to"].is_array() { &op["to"] } else { p }; + for x in at(p, 0)..=at(to, 0) { + for y in at(p, 1)..=at(to, 1) { + for z in at(p, 2)..=at(to, 2) { + world.scene.set(x, y, z, state)?; + } + } + } } "landing" => { let p = &op["position"]; @@ -443,6 +469,23 @@ fn main() -> Result<()> { // Entity.baseTick's fluid phase alone (wasEyeInWater, // updateFluidInteraction, lava fall halving, firstTick). "fluid_tick" => world.fluid_base_tick()?, + // LivingEntity.baseTick's air supply alone. + "air_tick" => world.tick_environment_damage()?, + "air" => world.player.air = op["value"].as_i64().unwrap() as i32, + "pitch" => world.player.pitch = single(&op["value"]), + "swimming" => world.player.swimming = op["value"].as_bool().unwrap(), + "effect" => { + let on = op["value"].as_bool().unwrap(); + let status = &mut world.player.status; + match op["name"].as_str().unwrap() { + "minecraft:dolphins_grace" => status.dolphins_grace = on, + "minecraft:water_breathing" | "minecraft:conduit_power" => { + status.water_breathing = on + } + "minecraft:breath_of_the_nautilus" => status.breath_of_the_nautilus = on, + other => return Err(format!("unknown fixture effect {other}").into()), + } + } "travel" => world.travel_in_air(vector(&op["value"]))?, "tick" => { let v = vector(&op["value"]); @@ -569,7 +612,7 @@ fn main() -> Result<()> { let stuck = player.stuck_multiplier; writeln!( out, - "block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}", + "block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x} swim {} {} air {}", check_block.0, player.ticks_frozen, player.in_powder_snow, @@ -582,7 +625,10 @@ fn main() -> Result<()> { player.is_eye_in_fluid(WATER), player.fluids.first_tick, player.fluid_height(WATER).to_bits(), - player.fluid_height(LAVA).to_bits() + player.fluid_height(LAVA).to_bits(), + player.swimming, + player.fluids.was_eye_in_water, + player.air )?; writeln!( out, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5e2156f10..9abc6c74a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2972,6 +2972,7 @@ impl Game<'_> { elytra.damage += glider_wear; } let feet = [player.position.x, player.position.y, player.position.z]; + let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z]; self.previous_eye = self.eye; self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; @@ -2981,13 +2982,59 @@ impl Game<'_> { match event { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), MotionEvent::Emission { - position, state, .. + state, in_water, .. } if !crouching => { - // Entity.playStepSound: the block's step sound at 0.15 volume. let sounds = self.res.facts.get(state).sounds.clone(); + // Entity.playStepSound: the block's step sound at 0.15 volume, + // muffled under the swim sound in water. + let (volume, pitch) = if in_water { + (sounds.volume * 0.05, sounds.pitch * 0.8) + } else { + (sounds.volume * 0.15, sounds.pitch) + }; + self.audio.play(&sounds.step, Some(feet), volume, pitch); + } + MotionEvent::Swim { volume, pitch } => { self.audio - .play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); - let _ = position; + .play("minecraft:entity.player.swim", Some(feet), volume, pitch); + } + MotionEvent::Drown => { + // LivingEntity.makeDrownParticles: eight bubbles moving + // with the player. + use horizon_client::particles::{ParticleOptions, ParticleType}; + for _ in 0..8 { + let mut triangle = || { + let r = self.particles.random(); + r.next_double() - r.next_double() + }; + let p = [ + feet[0] + triangle(), + feet[1] + triangle(), + feet[2] + triangle(), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Bubble), + p, + player_velocity, + ); + } + } + MotionEvent::BubbleColumnParticle { bubble, position } => { + // ServerLevel.sendParticles: SPLASH (speed 1) or BUBBLE + // (y spread 0.01, speed 0.2), one each. + use horizon_client::particles::{ParticleOptions, ParticleType}; + let (kind, spread, speed) = if bubble { + (ParticleType::Bubble, [0.0, 0.01, 0.0], 0.2) + } else { + (ParticleType::Splash, [0.0; 3], 1.0) + }; + self.particles.send_particles( + &ParticleOptions::simple(kind), + [position.x, position.y, position.z], + spread, + speed, + 1, + ); } MotionEvent::Fall(horizon_client::landing::FallEvent::Sound { sound, diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 24a2d0e3a..19e7092a2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1756,12 +1756,24 @@ impl Game<'_> { let crouching = player.pose == horizon_client::pose::Pose::Crouching; let feet = [player.position.x, player.position.y, player.position.z]; for event in events { - if let horizon_client::motion::MotionEvent::Emission { state, .. } = event - && !crouching - { - let sounds = self.res.facts.get(state).sounds.clone(); - self.audio - .play(&sounds.step, Some(feet), sounds.volume * 0.15, sounds.pitch); + match event { + horizon_client::motion::MotionEvent::Emission { + state, in_water, .. + } if !crouching => { + let sounds = self.res.facts.get(state).sounds.clone(); + // Player.playStepSound: muffled under the swim sound in water. + let (volume, pitch) = if in_water { + (sounds.volume * 0.05, sounds.pitch * 0.8) + } else { + (sounds.volume * 0.15, sounds.pitch) + }; + self.audio.play(&sounds.step, Some(feet), volume, pitch); + } + horizon_client::motion::MotionEvent::Swim { volume, pitch } => { + self.audio + .play("minecraft:entity.player.swim", Some(feet), volume, pitch); + } + _ => {} } } // The server owns health and hunger: undo local food/fall changes. diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index c5d9c2c0b..a9a4864ce 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -95,6 +95,8 @@ pub enum HealthEvent { FreezeDamage(f32), /// `SweetBerryBushBlock.entityInside` pricking a moving entity. SweetBerryBushDamage(f32), + /// `LivingEntity.baseTick` drowning an entity out of air. + DrownDamage(f32), Updated { id: u8, value: f32, @@ -128,6 +130,7 @@ impl HealthEvent { Self::SweetBerryBushDamage(amount) => { format!("damage sweet_berry_bush {:08x}", amount.to_bits()) } + Self::DrownDamage(amount) => format!("damage drown {:08x}", amount.to_bits()), Self::Updated { id, value, dirty } => { format!("updated {id} {:08x} {dirty}", value.to_bits()) } diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 1be338e2c..dce1f2adc 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -125,10 +125,17 @@ pub enum MotionEvent { state: BlockStateId, position: BlockPos, }, - /// `Entity.walkingStepSound` on this block. + /// `Entity.walkingStepSound` on this block: `Player.playStepSound` + /// muffles it under a swim sound when `in_water`. Emission { position: BlockPos, state: BlockStateId, + in_water: bool, + }, + /// `Entity.waterSwimSound`: `entity.player.swim`. + Swim { + volume: f32, + pitch: f32, }, Bounce { position: BlockPos, @@ -172,6 +179,15 @@ pub enum MotionEvent { }, /// ...and the SPLASH game event. SplashEvent, + /// `Entity.sendBubbleColumnParticles`: a SPLASH (or BUBBLE) particle + /// over the top of a bubble column the player rides. + BubbleColumnParticle { + bubble: bool, + position: Vec3, + }, + /// Entity event 67 (`LivingEntity.makeDrownParticles`): eight bubbles + /// around a drowning player. + Drown, } pub struct PlayerMotion { pub swimming: bool, @@ -514,13 +530,18 @@ impl PlayerMotion { .map_err(attribute_error)?; Ok(()) } - /// Local input sprint phase for the resident dry, standing, empty-equipment - /// player. Fluid, pose, vehicle, ability-flight and effect bindings remain - /// separate; hunger and collision conditions use this actor's actual state. + /// Local input sprint phase (`LocalPlayer.aiStep`'s sprint decisions). + /// Vehicle, item-use and effect bindings remain separate; hunger, flight, + /// water and collision conditions use this actor's actual state. pub fn sprint_input_tick(&mut self, keys: crate::sprint::Keys) -> Result<()> { let conditions = crate::sprint::Conditions { sprinting: self.sprinting, enough_food: self.health.food.has_enough_food(), + may_fly: self.may_fly, + flying: self.flying, + // Entity.isInShallowWater. + shallow_water: self.fluids.was_touching_water && !self.is_under_water(), + fall_flying: self.fall_flying, on_ground: self.ground.on_ground, horizontal_collision: self.collision.horizontal, minor_horizontal_collision: self.collision.minor, @@ -680,7 +701,7 @@ impl MotionWorld<'_, '_, '_> { } else if !was_jumping && jumping && !self.player.was_auto_jump { if self.player.jump_trigger_time == 0 { self.player.jump_trigger_time = 7; - } else { + } else if !self.player.swimming { self.player.flying = !self.player.flying; if self.player.flying && self.player.ground.on_ground { self.jump_from_ground()?; @@ -689,7 +710,8 @@ impl MotionWorld<'_, '_, '_> { } } let toggled = flying_before != self.player.flying; - // Player.tryToStartFallFlying (canGlide: airborne, not flying, a glider). + // Player.tryToStartFallFlying (canGlide: airborne, not flying, a glider; + // never from inside a liquid). let can_glide = self.player.glider && !self.player.ground.on_ground && !self.player.flying @@ -701,11 +723,8 @@ impl MotionWorld<'_, '_, '_> { // LivingEntity.tick fallFlyTicks, then updateFallFlying. if self.player.fall_flying { self.player.fall_fly_ticks += 1; - let still = self.player.glider - && !self.player.ground.on_ground - && !self.player.flying - && !self.player.fluids.was_touching_water - && !self.player.is_in_lava(); + // canGlide alone: water and lava don't end a glide. + let still = self.player.glider && !self.player.ground.on_ground && !self.player.flying; if !still { self.player.fall_flying = false; } else if (self.player.fall_fly_ticks + 1) % 10 == 0 @@ -716,6 +735,13 @@ impl MotionWorld<'_, '_, '_> { } else { self.player.fall_fly_ticks = 0; } + // LocalPlayer.goDownInWater, before LivingEntity.aiStep's velocity cleanup. + if self.player.fluids.was_touching_water + && self.player.shift_key_down + && !self.player.flying + { + self.player.velocity.y += f64::from(-0.04f32); + } if self.player.flying { // Vertical flight: jump up, shift down, three times the flying speed. let ya = i32::from(jumping) - i32::from(self.player.shift_key_down); @@ -762,6 +788,9 @@ impl MotionWorld<'_, '_, '_> { .food_tick(&self.resources.health, self.scene.health_rules) } pub fn controlled_simulation_tick(&mut self, keys: crate::sprint::Keys) -> Result<()> { + // The base tick (fluids, swimming) precedes LocalPlayer.aiStep. + self.player.health.advance_clock(); + self.fluid_base_tick()?; self.update_local_crouching()?; let mut keys = keys; // LocalPlayer.aiStep: a pending auto-jump presses jump for this tick @@ -771,8 +800,6 @@ impl MotionWorld<'_, '_, '_> { self.player.auto_jump_time -= 1; keys.jump = true; } - self.player.health.advance_clock(); - self.fluid_base_tick()?; self.player.sprint_input_tick(keys)?; self.player.shift_key_down = keys.shift; let direction = keys.direction(); @@ -821,34 +848,16 @@ impl MotionWorld<'_, '_, '_> { input.x = 0.0; input.z = 0.0; } - if self.player.shift_key_down - && !self.player.flying - && self.player.fluids.was_touching_water - { - self.player.velocity.y -= f64::from(0.04f32); - } - if self.player.jumping { - let in_lava = self.player.is_in_lava(); - let height = self.player.fluid_height(if in_lava { LAVA } else { WATER }); - let water_jump = self.player.fluids.was_touching_water - && height > 0.0 - && (!self.player.ground.on_ground || height > 0.4); - let lava_jump = in_lava && (!self.player.ground.on_ground || height > 0.4); - if !self.player.flying && (water_jump || lava_jump) { - self.player.velocity.y += f64::from(0.04f32); - } else if self.player.ground.on_ground && self.player.no_jump_delay == 0 { - self.jump_from_ground()?; - self.player.no_jump_delay = 10; - } - } else { - self.player.no_jump_delay = 0; - } + self.jump_phase()?; + // Player.travel: swim steering, then LivingEntity.travel (fluids + // first, then gliding, then air), keeping 0.6 of the vertical speed + // while flying. if self.player.swimming { let look_y = horizon_world::view_direction::view_vector(self.player.pitch, self.player.yaw).y; let near_surface = BlockPos::containing(Vec3::new( self.player.position.x, - self.player.position.y + 0.9, + self.player.position.y + 1.0 - 0.1, self.player.position.z, )); if look_y <= 0.0 @@ -859,20 +868,19 @@ impl MotionWorld<'_, '_, '_> { self.player.velocity.y += (look_y - self.player.velocity.y) * blend; } } - if self.player.fall_flying { - self.travel_fall_flying()?; - } else if self.player.flying { - // Player.travel while flying: keep 0.6 of the vertical speed. - let y = self.player.velocity.y; - self.travel_in_air(input)?; - self.player.velocity.y = y * 0.6; - } else if !self.player.flying + let flying_y = self.player.flying.then_some(self.player.velocity.y); + if !self.player.flying && (self.player.fluids.was_touching_water || self.player.is_in_lava()) { horizon_world::living_fluid::travel_in_fluid(self, input)?; + } else if self.player.fall_flying { + self.travel_fall_flying()?; } else { self.travel_in_air(input)?; } + if let Some(y) = flying_y { + self.player.velocity.y = y * 0.6; + } if self.player.block_effects { self.apply_effects_from_blocks()?; } @@ -1028,6 +1036,10 @@ impl MotionWorld<'_, '_, '_> { f64::from(1.0e-5_f32), f64::from(1.0e-5_f32), )); + // Mth.square(0.9999900000002526): a long move counts every block it + // crosses as precise. + let far = 0.999_990_000_000_252_6_f64; + let moved_far = from.distance_squared(to) > far * far; let mut hits = Vec::new(); let mut iterations = 0; let alive = !self.player.health.dead_or_dying(); @@ -1101,6 +1113,10 @@ impl MotionWorld<'_, '_, '_> { } "minecraft:cobweb" => self.web_inside(), "minecraft:sweet_berry_bush" => self.sweet_berry_bush_inside(state)?, + "minecraft:bubble_column" => { + let precise = moved_far || deflated.intersects(Aabb::block(p)); + self.bubble_column_inside(state, p, precise)? + } "minecraft:nether_portal" => self .player .events @@ -1596,8 +1612,8 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { Ok(block + efficiency * (1.0 - block)) } } -// The player's footsteps. Swimming, flapping and the step game event are -// not bound here (the sculk listeners track the player's steps themselves). +// The player's footsteps and swim sounds. Flapping and the step game event +// are not bound here (the sculk listeners track the player's steps themselves). impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { type Error = Box; type State = BlockStateId; @@ -1664,10 +1680,17 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { fn in_water(&mut self) -> Result { Ok(self.player.fluids.was_touching_water) } + /// `Player.playStepSound`: in water a swim sound, then the step muffled. fn walking_step_sound(&mut self, position: BlockPos, state: BlockStateId) -> Result<()> { - self.player - .events - .push(MotionEvent::Emission { position, state }); + let in_water = self.player.fluids.was_touching_water; + if in_water { + self.water_swim_sound()?; + } + self.player.events.push(MotionEvent::Emission { + position, + state, + in_water, + }); Ok(()) } fn step_event(&mut self, _: BlockStateId) -> Result<()> { @@ -1676,7 +1699,18 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { fn next_step(&mut self) -> Result { Ok(self.player.steps.next_step()) } + /// `Entity.waterSwimSound` and `playSwimSound` (the level random stands + /// in for the entity's, as for the splash). fn water_swim_sound(&mut self) -> Result<()> { + let v = self.player.velocity; + let volume = 1.0_f32.min( + (v.x * v.x * f64::from(0.2_f32) + v.y * v.y + v.z * v.z * f64::from(0.2_f32)).sqrt() + as f32 + * 0.35, + ); + let random = &mut self.scene.random; + let pitch = 1.0 + (random.next_float() - random.next_float()) * 0.4; + self.player.events.push(MotionEvent::Swim { volume, pitch }); Ok(()) } fn entity_event(&mut self, _: MovementEvent) -> Result<()> { diff --git a/crates/horizon-client/src/motion/environment.rs b/crates/horizon-client/src/motion/environment.rs index 7f1dca470..4ba5e7099 100644 --- a/crates/horizon-client/src/motion/environment.rs +++ b/crates/horizon-client/src/motion/environment.rs @@ -38,7 +38,8 @@ impl MotionWorld<'_, '_, '_> { } Ok(()) } - pub(super) fn tick_environment_damage(&mut self) -> Result<()> { + /// `LivingEntity.baseTick`'s air supply and drowning, then lava. + pub fn tick_environment_damage(&mut self) -> Result<()> { let eye = BlockPos::containing(self.player.position.add_vector(Vec3::new( 0.0, f64::from(self.player.dimensions.eye_height), @@ -56,6 +57,13 @@ impl MotionWorld<'_, '_, '_> { && !self.player.invulnerable && !self.player.spectator { + // decreaseAirSupply's getAttribute: the instance exists from now + // on, even unmodified. + let key = self.player.attributes.key("minecraft:oxygen_bonus"); + self.player + .attributes + .get_instance(key) + .map_err(|e| format!("oxygen bonus: {e:?}"))?; let oxygen = self .player .attribute("minecraft:oxygen_bonus")? @@ -65,6 +73,10 @@ impl MotionWorld<'_, '_, '_> { } if self.player.air <= -20 { self.player.air = 0; + self.player.events.push(MotionEvent::Drown); + self.player.events.push(MotionEvent::Health( + crate::health::HealthEvent::DrownDamage(2.0), + )); self.environment_hurt("minecraft:drown", 2.0)?; } } else if !submerged @@ -153,7 +165,7 @@ impl LivingFluidWorld for MotionWorld<'_, '_, '_> { })) } fn fluid_jump_threshold(&mut self) -> Result { - Ok(0.4) + Ok(self.player.fluid_jump_threshold()) } fn is_free(&mut self, v: Vec3) -> Result { let b = self.player.bounds().move_by(v); @@ -166,7 +178,92 @@ impl LivingFluidWorld for MotionWorld<'_, '_, '_> { Ok(false) } } +impl PlayerMotion { + /// `Entity.getFluidJumpThreshold`: 0.4, or 0 under eyes lower than that. + pub fn fluid_jump_threshold(&self) -> f64 { + horizon_world::swimming::fluid_jump_threshold(self.dimensions.eye_height) + } +} impl MotionWorld<'_, '_, '_> { + /// `LivingEntity.aiStep`'s jump phase: rise in water or lava, else jump + /// from the ground (or from shallow fluid); nothing while flying. + pub(super) fn jump_phase(&mut self) -> Result<()> { + if !self.player.jumping || self.player.flying { + self.player.no_jump_delay = 0; + return Ok(()); + } + let in_lava = self.player.is_in_lava(); + let height = self.player.fluid_height(if in_lava { LAVA } else { WATER }); + let in_water = self.player.fluids.was_touching_water && height > 0.0; + let threshold = self.player.fluid_jump_threshold(); + let on_ground = self.player.ground.on_ground; + if in_water && !(on_ground && height <= threshold) { + // jumpInLiquid(WATER) + self.player.velocity.y += f64::from(0.04f32); + } else if in_lava && !(on_ground && self.player.fluid_height(LAVA) <= threshold) { + // jumpInLiquid(LAVA) + self.player.velocity.y += f64::from(0.04f32); + } else if (on_ground || in_water && height <= threshold) && self.player.no_jump_delay == 0 { + self.jump_from_ground()?; + self.player.no_jump_delay = 10; + } + Ok(()) + } + /// `BubbleColumnBlock.entityInside` with `Player.onAboveBubbleColumn` / + /// `onInsideBubbleColumn`: pushed up (or dragged down), faster at the + /// surface, never while flying. + pub(super) fn bubble_column_inside( + &mut self, + state: BlockStateId, + p: BlockPos, + precise: bool, + ) -> Result<()> { + if !precise { + return Ok(()); + } + let drag = self + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("drag")) + .is_some_and(|d| d == "true"); + let above = self.block(p.offset(0, 1, 0)); + // stateAbove.getCollisionShape(level, pos): the shape is asked at the + // column's own position. + let binding = self.collision_binding; + let context = CollisionContext::empty(false); + let empty = binding + .collision_shape_with_context(&mut self.collisions(), above, p, &context)? + .is_empty() + && self.resources.fluids.fluid(above).kind() == FluidKind::Empty; + if self.player.flying { + return Ok(()); + } + let v = self.player.velocity; + let y = match (empty, drag) { + (true, true) => (-0.9_f64).max(v.y - 0.03), + (true, false) => 1.8_f64.min(v.y + 0.1), + (false, true) => (-0.3_f64).max(v.y - 0.03), + (false, false) => 0.7_f64.min(v.y + 0.06), + }; + self.player.velocity = Vec3::new(v.x, y, v.z); + if empty { + // Entity.sendBubbleColumnParticles: two splashes and two bubbles + // over the column's top, from the level random. + let random = &mut self.scene.random; + for bubble in [false, true, false, true] { + let x = f64::from(p.x) + random.next_double(); + let z = f64::from(p.z) + random.next_double(); + self.player.events.push(MotionEvent::BubbleColumnParticle { + bubble, + position: Vec3::new(x, f64::from(p.y + 1), z), + }); + } + } else { + self.player.fall_distance = 0.0; + } + Ok(()) + } fn has_liquid(&self, b: Aabb) -> Result { for x in b.min_position().x.floor() as i32..=b.max_position().x.floor() as i32 { for y in b.min_position().y.floor() as i32..=b.max_position().y.floor() as i32 { diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index f8afca24e..f85f755a9 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -109,9 +109,11 @@ impl PlayerMotion { pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool { self.fluids.interaction.is_eye_in_fluid(&Membership, tag) } - /// `Player.isUnderWater`: the eye sample from the start of the base tick. + /// `LocalPlayer.isUnderWater`: `wasUnderwater`, the eye sample `Player.tick` + /// takes before the base tick (`Entity.isUnderWater` also needs the body + /// still in water). pub fn is_under_water(&self) -> bool { - self.fluids.was_eye_in_water && self.fluids.was_touching_water + self.fluids.was_eye_in_water } /// `Entity.isInLava`. pub fn is_in_lava(&self) -> bool { diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index a296546cc..9c8124b0e 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -98,16 +98,17 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - let desired = if self.player.fall_flying { - Pose::FallFlying - } else if self.player.swimming { + // Player.getDesiredPose: swimming before gliding. + let desired = if self.player.swimming { Pose::Swimming + } else if self.player.fall_flying { + Pose::FallFlying } else if self.player.shift_key_down && !self.player.flying { Pose::Crouching } else { Pose::Standing }; - let pose = if self.can_fit_pose(desired)? { + let pose = if self.player.spectator || self.can_fit_pose(desired)? { desired } else if self.can_fit_pose(Pose::Crouching)? { Pose::Crouching diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java index 9f1ea2af3..5fb2443d8 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSceneMotionOracle.java @@ -71,11 +71,12 @@ public final class VanillaSceneMotionOracle { static String vectorBits(Vec3 p){return String.format("%016x,%016x,%016x",Double.doubleToLongBits(p.x),Double.doubleToLongBits(p.y),Double.doubleToLongBits(p.z));} static String soundName(SoundEvent s){ if(s==SoundEvents.PLAYER_SMALL_FALL)return "small";if(s==SoundEvents.PLAYER_BIG_FALL)return "big"; - if(s==SoundEvents.PLAYER_SPLASH)return "splash";if(s==SoundEvents.PLAYER_SPLASH_HIGH_SPEED)return "splash-high"; + if(s==SoundEvents.PLAYER_SPLASH)return "splash";if(s==SoundEvents.PLAYER_SPLASH_HIGH_SPEED)return "splash-high";if(s==SoundEvents.PLAYER_SWIM)return "swim"; return VanillaBlockLandingOracle.sound(s); } static final class Sources extends DamageSources { - DamageSource fall,stalagmite,starve,freeze,sweetBerryBush;Sources(){super(null);} + DamageSource fall,stalagmite,starve,freeze,sweetBerryBush,drown;Sources(){super(null);} + @Override public DamageSource drown(){return drown;} @Override public DamageSource freeze(){return freeze;} @Override public DamageSource sweetBerryBush(){return sweetBerryBush;} @Override public DamageSource starve(){return starve;} @@ -104,6 +105,13 @@ public final class VanillaSceneMotionOracle { @Override public long getGameTime(){return time;} @Override public void broadcastDamageEvent(Entity actor,DamageSource source){this.actor.events.add("broadcast-damage");} Level(){super(null,null,null,null,null,null,false,0L,List.of(),false);} + // LevelReader.containsAnyLiquid over the scene chunks (its section scan + // needs level chunks): any fluid from the box's minimum block to its + // maximum block, both included. + @Override public boolean containsAnyLiquid(AABB b){ + for(var p:BlockPos.betweenClosed(BlockPos.containing(b.minX,b.minY,b.minZ),BlockPos.containing(b.maxX,b.maxY,b.maxZ)))if(!getBlockState(p).getFluidState().isEmpty())return true; + return false; + } @Override public boolean isClientSide(){return false;} @Override public BlockGetter getChunkForCollisions(int x,int z){return chunks.get(key(x,z));} @Override public BlockState getBlockState(BlockPos p){var c=chunks.get(key(p.getX()>>4,p.getZ()>>4));return c==null?Blocks.AIR.defaultBlockState():c.getBlockState(p);} @@ -132,6 +140,10 @@ public final class VanillaSceneMotionOracle { actor.events.add("snowflake "+vectorBits(new Vec3(x,y,z))+" "+vectorBits(new Vec3(xs,ys,zs)));return 0; } @Override public int sendParticles(T particle,double x,double y,double z,int count,double dx,double dy,double dz,double speed){ + // Entity.sendBubbleColumnParticles. + if(particle==net.minecraft.core.particles.ParticleTypes.SPLASH||particle==net.minecraft.core.particles.ParticleTypes.BUBBLE){ + actor.events.add(String.format("column-particle %s %s %d %s %016x",particle==net.minecraft.core.particles.ParticleTypes.BUBBLE?"bubble":"splash",vectorBits(new Vec3(x,y,z)),count,vectorBits(new Vec3(dx,dy,dz)),Double.doubleToLongBits(speed)));return 0; + } var b=(net.minecraft.core.particles.BlockParticleOption)particle;if(dx!=0||dy!=0||dz!=0)throw new AssertionError(); actor.events.add(String.format("particles %d %s %d %016x",Block.getId(b.getState()),vectorBits(new Vec3(x,y,z)),count,Double.doubleToLongBits(speed)));return 0; } @@ -186,7 +198,14 @@ public final class VanillaSceneMotionOracle { @Override public BlockState getInBlockState(){return level().getBlockState(blockPosition());} @Override public ItemStack getMainHandItem(){return ItemStack.EMPTY;} @Override public boolean isPassenger(){return statisticsFlags!=null&&statFlag(0);} - @Override public boolean isSwimming(){return statisticsFlags!=null&&statFlag(1);} + @Override public boolean isSwimming(){return statisticsFlags!=null?statFlag(1):super.isSwimming();} + // LocalPlayer.isUnderWater: the resident player is the local one. + @Override public boolean isUnderWater(){return wasUnderwater;} + // The synchronized air supply as a plain field (no data item here). + int air; + @Override public int getAirSupply(){return air;} + @Override public void setAirSupply(int value){air=value;} + String swimState(){return "swim "+getSharedFlag(4)+" "+wasUnderwater+" air "+air;} @Override public boolean isEyeInFluid(net.minecraft.tags.TagKey tag){return statisticsFlags!=null?statFlag(2):super.isEyeInFluid(tag);} @Override public boolean isInWater(){return statisticsFlags!=null?statFlag(3):super.isInWater();} @Override public boolean onClimbable(){return statisticsFlags!=null?statFlag(4):super.onClimbable();} @@ -197,14 +216,15 @@ public final class VanillaSceneMotionOracle { @Override public boolean isAutoSpinAttack(){return false;} @Override public boolean isSpectator(){return false;} @Override public boolean isNoGravity(){return false;} - // No effects but Weaving (WebBlock.entityInside), set without the effect's callbacks. - boolean weaving; - @Override public boolean hasEffect(Holder effect){return weaving&&effect==net.minecraft.world.effect.MobEffects.WEAVING;} + // Effects as flags (Weaving for WebBlock.entityInside, water effects for + // travel and breathing), set without the effects' callbacks. + boolean weaving;Set> effectFlags; + @Override public boolean hasEffect(Holder effect){return weaving&&effect==net.minecraft.world.effect.MobEffects.WEAVING||effectFlags.contains(effect);} @Override public MobEffectInstance getEffect(Holder effect){return null;} @Override public MoveSimulationType getMoveSimulationType(){return MoveSimulationType.SERVER_AND_CLIENT;} @Override public boolean isClientAuthoritative(){return false;} @Override public void recordMovement(MoverType mover,Vec3 movement){} - @Override public void playSound(SoundEvent sound,float volume,float pitch){events.add(String.format("sound %s entity %08x %08x",soundName(sound),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));} + @Override public void playSound(SoundEvent sound,float volume,float pitch){if(stepping!=null&&sound!=SoundEvents.PLAYER_SWIM){events.add("muffled-step "+Block.getId(stepping));return;}events.add(String.format("sound %s entity %08x %08x",soundName(sound),Float.floatToIntBits(volume),Float.floatToIntBits(pitch)));} @Override protected void playBlockFallSound(){events.add("block-fall-sound");} @Override public void awardStat(net.minecraft.stats.Stat stat,int value){ if(stat.getValue()!=net.minecraft.stats.Stats.JUMP)throw new AssertionError(stat); @@ -215,12 +235,14 @@ public final class VanillaSceneMotionOracle { String name=stat==net.minecraft.stats.Stats.DAMAGE_ABSORBED?"absorbed":stat==net.minecraft.stats.Stats.DAMAGE_TAKEN?"taken":stat==net.minecraft.stats.Stats.DAMAGE_RESISTED?"resisted":null; if(name==null){name=stat.getPath();if(!Set.of("swim_one_cm","walk_under_water_one_cm","walk_on_water_one_cm","climb_one_cm","sprint_one_cm","crouch_one_cm","walk_one_cm","aviate_one_cm","fly_one_cm").contains(name))throw new AssertionError(stat);}events.add("health-stat "+name+" "+value); } - @Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":source==sources.freeze?"freeze":source==sources.sweetBerryBush?"sweet_berry_bush":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);} + @Override public boolean hurtServer(net.minecraft.server.level.ServerLevel level,DamageSource source,float damage){var sources=((Level)level).sources;events.add(String.format("damage %s %08x",source==sources.fall?"fall":source==sources.stalagmite?"stalagmite":source==sources.starve?"starve":source==sources.freeze?"freeze":source==sources.sweetBerryBush?"sweet_berry_bush":source==sources.drown?"drown":"unknown",Float.floatToIntBits(damage)));return super.hurtServer(level,source,damage);} @Override public void teleportRelative(double x,double y,double z){setPos(getX()+x,getY()+y,getZ()+z);} - @Override protected void playStepSound(BlockPos p,BlockState state){} + // Footsteps stay a controlled consumer; in water Player.playStepSound + // swims (its sound is compared) and muffles the step (marked here). + BlockState stepping; + @Override protected void playStepSound(BlockPos p,BlockState state){if(isInWater()){stepping=state;try{super.playStepSound(p,state);}finally{stepping=null;}}} @Override public void gameEvent(Holder event,Entity source){} @Override public LivingEntity getControllingPassenger(){return null;} - @Override public double getFluidJumpThreshold(){return .4;} // Block-inside effects and frozen ticks run only in "snow_tick" operations. boolean effects;int frozen;Vec3 tickStart; @Override public int getTicksFrozen(){return frozen;} @@ -251,10 +273,28 @@ public final class VanillaSceneMotionOracle { void clock()throws Exception{sceneLevel.time++;tickCount++;if(cooldown.getInt(this)>0)cooldown.setInt(this,cooldown.getInt(this)-1);if(hurtTime>0)hurtTime--;} // Entity.baseTick's fluid phase: wasEyeInWater, the real // updateFluidInteraction, lava's fall halving and the first tick's end. - void fluidTick(){wasEyeInWater=isEyeInFluid(net.minecraft.tags.FluidTags.WATER);updateFluidInteraction();if(isInLava())fallDistance*=0.5;firstTick=false;} + // Player.tick's updateIsUnderwater, then Entity.baseTick's fluid phase: + // wasEyeInWater, the real updateFluidInteraction and updateSwimming, + // lava's fall halving and the first tick's end. + void fluidTick(){updateIsUnderwater();wasEyeInWater=isEyeInFluid(net.minecraft.tags.FluidTags.WATER);updateFluidInteraction();updateSwimming();if(isInLava())fallDistance*=0.5;firstTick=false;} + // LivingEntity.baseTick's air supply (server): the real decrease / + // increase / drowning methods in its order. + void airTick(){ + if(!isAlive())return; + if(isEyeInFluid(net.minecraft.tags.FluidTags.WATER)&&!level().getBlockState(BlockPos.containing(getX(),getEyeY(),getZ())).is(Blocks.BUBBLE_COLUMN)){ + boolean canDrown=!canBreatheUnderwater()&&!MobEffectUtil.hasWaterBreathing(this)&&!getAbilities().invulnerable; + if(canDrown){ + setAirSupply(decreaseAirSupply(getAirSupply())); + if(shouldTakeDrowningDamage()){setAirSupply(0);level().broadcastEntityEvent(this,(byte)67);hurtServer((net.minecraft.server.level.ServerLevel)level(),damageSources().drown(),2.0F);} + }else if(getAirSupply())lines::iterator){ - var row=JsonParser.parseString(line).getAsJsonObject();var p=(Actor)allocate.invoke(unsafe,Actor.class);p.configure(level);p.events=new ArrayList<>();level.actor=p; + var row=JsonParser.parseString(line).getAsJsonObject();var p=(Actor)allocate.invoke(unsafe,Actor.class);p.configure(level);p.events=new ArrayList<>();level.actor=p;p.effectFlags=new HashSet<>();p.air=300; + // Entity.nextStep's initializer (allocation skips it): the first footstep or swim sound after a metre. + field(Entity.class,"nextStep").setFloat(p,1.0F); write(field(Entity.class,"type"),p,EntityTypes.PLAYER); p.scenePose=Pose.STANDING; write(field(Entity.class,"passengers"),p,com.google.common.collect.ImmutableList.of());write(field(Entity.class,"dimensions"),p,p.getDefaultDimensions(Pose.STANDING));write(field(Entity.class,"eyeHeight"),p,1.62f); @@ -357,9 +399,12 @@ public final class VanillaSceneMotionOracle { case "refresh_attributes"->p.attributeTick(); case "pose"->p.setPose(Pose.valueOf(op.get("value").getAsString())); case "controlled_tick"->{ + // Player.tick: the base tick (fluids, swimming, air supply), + // then LocalPlayer.aiStep's prefix and the actor's aiStep. if(p.sprintController==null)p.sprintController=Class.forName("dev.horizonlab.parity.VanillaSprintInputOracle$Controller").getConstructor(ServerPlayer.class).newInstance(p); + p.clock();var before=p.position();p.fluidTick();p.airTick(); int mask=op.get("value").getAsInt();var direction=(net.minecraft.world.phys.Vec2)p.sprintController.getClass().getMethod("step",int.class).invoke(p.sprintController,mask); - p.clock();var before=p.position();p.playerMovementTick(new Vec3(direction.x,0,direction.y),(mask&16)!=0);p.attributeTick();p.poseTick();p.checkMovementStatistics(p.getX()-before.x,p.getY()-before.y,p.getZ()-before.z);p.getFoodData().tick(p); + p.aiStepWith(new Vec3(direction.x,0,direction.y),(mask&16)!=0);p.attributeTick();p.poseTick();p.checkMovementStatistics(p.getX()-before.x,p.getY()-before.y,p.getZ()-before.z);p.getFoodData().tick(p); } case "health"->p.setHealth(single(op.get("value"))); case "absorption"->p.setAbsorptionAmount(single(op.get("value"))); @@ -372,7 +417,7 @@ public final class VanillaSceneMotionOracle { case "eat"->p.getFoodData().eat(op.get("nutrition").getAsInt(),single(op.get("value"))); case "food_tick"->p.getFoodData().tick(p); case "peaceful"->p.peaceful(); - case "simulation_tick"->{p.clock();var before=p.position();p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());p.attributeTick();p.poseTick();p.checkMovementStatistics(p.getX()-before.x,p.getY()-before.y,p.getZ()-before.z);p.getFoodData().tick(p);} + case "simulation_tick"->{p.clock();var before=p.position();p.fluidTick();p.airTick();p.aiStepWith(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean());p.attributeTick();p.poseTick();p.checkMovementStatistics(p.getX()-before.x,p.getY()-before.y,p.getZ()-before.z);p.getFoodData().tick(p);} case "movement_statistics"->{var delta=VanillaSceneCollisionOracle.vector(op.get("value"));p.checkMovementStatistics(delta.x,delta.y,delta.z);} case "statistics_context"->{ p.statisticsFlags=op.get("flags").getAsInt();p.getAbilities().invulnerable=op.get("invulnerable").getAsBoolean(); @@ -381,9 +426,15 @@ public final class VanillaSceneMotionOracle { } case "seed"->level.rng.setSeed(op.get("value").getAsLong()); case "impulse"->p.setIgnoreFallDamageFromCurrentImpulse(op.get("ignore").getAsBoolean(),op.get("value").isJsonNull()?null:VanillaSceneCollisionOracle.vector(op.get("value"))); - case "block"->{var v=op.getAsJsonArray("position");var pos=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt());var state=VanillaSceneCollisionOracle.state(op.get("name").getAsString());if(op.has("properties"))for(var property:op.getAsJsonObject("properties").entrySet())state=VanillaSceneCollisionOracle.property(state,state.getBlock().getStateDefinition().getProperty(property.getKey()),property.getValue().getAsString());level.chunks.get(key(pos.getX()>>4,pos.getZ()>>4)).write(pos,Block.getId(state));} + case "block","fill"->{var v=op.getAsJsonArray("position");var to=op.has("to")?op.getAsJsonArray("to"):v;var state=VanillaSceneCollisionOracle.state(op.get("name").getAsString());if(op.has("properties"))for(var property:op.getAsJsonObject("properties").entrySet())state=VanillaSceneCollisionOracle.property(state,state.getBlock().getStateDefinition().getProperty(property.getKey()),property.getValue().getAsString()); + for(int x=v.get(0).getAsInt();x<=to.get(0).getAsInt();x++)for(int y=v.get(1).getAsInt();y<=to.get(1).getAsInt();y++)for(int z=v.get(2).getAsInt();z<=to.get(2).getAsInt();z++){var pos=new BlockPos(x,y,z);level.chunks.get(key(pos.getX()>>4,pos.getZ()>>4)).write(pos,Block.getId(state));}} case "landing"->{var v=op.getAsJsonArray("position");p.land(number(op.get("value")),op.get("ground").getAsBoolean(),new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()));} case "fluid_tick"->p.fluidTick(); + case "air_tick"->p.airTick(); + case "air"->p.air=op.get("value").getAsInt(); + case "pitch"->p.setXRot(single(op.get("value"))); + case "swimming"->p.setSwimming(op.get("value").getAsBoolean()); + case "effect"->{var e=BuiltInRegistries.MOB_EFFECT.wrapAsHolder(BuiltInRegistries.MOB_EFFECT.getValue(Identifier.parse(op.get("name").getAsString())));if(op.get("value").getAsBoolean())p.effectFlags.add(e);else p.effectFlags.remove(e);} case "travel"->p.travel(VanillaSceneCollisionOracle.vector(op.get("value"))); case "tick"->p.movementTick(VanillaSceneCollisionOracle.vector(op.get("value"))); case "player_tick"->p.playerMovementTick(VanillaSceneCollisionOracle.vector(op.get("value")),op.get("jumping").getAsBoolean()); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java index 43ca12714..636a6a038 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaSprintInputOracle.java @@ -66,7 +66,11 @@ public final class VanillaSprintInputOracle { @Override public boolean isEyeInFluid(TagKey tag){return false;} @Override public boolean onClimbable(){return false;} @Override public boolean tryToStartFallFlying(){return false;} - @Override protected void goDownInWater(){} + // The controlled actor sinks (LivingEntity.goDownInWater on it). + @Override protected void goDownInWater(){ + if(controlled==null)return; + try{var method=LivingEntity.class.getDeclaredMethod("goDownInWater");method.setAccessible(true);method.invoke(controlled);}catch(ReflectiveOperationException e){throw new AssertionError(e);} + } @Override protected boolean isControlledCamera(){return false;} @Override public void onUpdateAbilities(){} @Override public void jumpFromGround(){} // post-sprint ability-flight callback @@ -95,7 +99,8 @@ public final class VanillaSprintInputOracle { modify=LocalPlayer.class.getDeclaredMethod("modifyInput",net.minecraft.world.phys.Vec2.class);modify.setAccessible(true); } public net.minecraft.world.phys.Vec2 step(int mask)throws Exception{ - p.flags=(p.controlled.onGround()?1<<14:0)|(p.controlled.horizontalCollision?1<<15:0)|(p.controlled.minorHorizontalCollision?1<<16:0); + p.flags=(p.controlled.onGround()?1<<14:0)|(p.controlled.horizontalCollision?1<<15:0)|(p.controlled.minorHorizontalCollision?1<<16:0) + |(p.controlled.isInShallowWater()?1<<6:0)|(p.controlled.isUnderWater()?1<<10:0)|(p.controlled.isSwimming()?1<<12:0)|(p.controlled.isInWater()?1<<13:0); p.horizontalCollision=p.controlled.horizontalCollision;p.minorHorizontalCollision=p.controlled.minorHorizontalCollision; p.calls.clear();for(int i=0;i