diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 442c37237..70a4009b8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -47,6 +47,8 @@ pub(super) struct Creatures { pub pearl_cooldown: u32, /// The wind charge's use cooldown (ticks). pub wind_cooldown: u32, + /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). + pub wind_bursts: Vec, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -1778,7 +1780,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } - Ok(()) + self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; /// as the host's when they have left. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 00c5c3433..bab304569 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -1011,6 +1011,8 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); + // A mace's wind burst from a guest's attack. + let _ = self.flush_wind_bursts(); } fn lan_guest_joined( diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index cabddcf39..2c2c25e93 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -258,6 +258,7 @@ impl Game<'_> { motion.pitch = g.pitch; motion.sprinting = g.sprinting; motion.may_fly = g.creative() || g.game_mode == SPECTATOR; + motion.flying = g.flying; motion.invulnerable = motion.may_fly; let _ = motion.set_health(g.health, false); motion.health.food.food = g.food; diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 2cacfabdb..1efb4ac58 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -3,7 +3,7 @@ //! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). use super::Game; use horizon_client::particles::{ParticleOptions, ParticleType}; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ entity_data::{Particle, ParticleData}, packets::play::{self, Clientbound as C}, @@ -154,7 +154,7 @@ impl Game<'_> { } /// `ClientPacketListener.handleExplosion`: the blast's particles (and its - /// sound, when the packet carries it). + /// sound, when the packet carries it), then the player's push. pub(super) fn remote_explode(&mut self, p: &play::Explode) { if p.play_sound { let pitch = (1.0 @@ -168,37 +168,88 @@ impl Game<'_> { pitch, ); } - let (world, facts) = (&self.world, self.res.facts()); - self.particles - .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { - facts.is_air(world.block(b[0], b[1], b[2])) - }); + if let Some(options) = self.received_particle(&p.particle, p.center) { + self.particles.add(&options, p.center, [1.0, 0.0, 0.0]); + } + // A wind charge's burst throws none. + if !p.block_particles.is_empty() { + let (world, facts) = (&self.world, self.res.facts()); + self.particles.explosion_blocks( + p.center, + p.radius, + p.block_count.max(0) as usize, + &|b| facts.is_air(world.block(b[0], b[1], b[2])), + ); + } + // Entity.pushFromExplosion. + if let (Some(push), Some(player)) = (p.knockback, self.player.as_mut()) { + player.velocity = Vec3::new( + player.velocity.x + push[0], + player.velocity.y + push[1], + player.velocity.z + push[2], + ); + } } /// `ServerLevel.explode`'s packet to each player within 64 blocks. The /// sound and the push reach them on their own (the level's sounds, the - /// players' motion), so the packet carries neither. + /// motion a hurt player is sent), so the packet carries neither. pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { - let Some(host) = self.lan.as_ref() else { - return; - }; - let particle = |name: &str| { - Some(Particle { - id: host.hub.registry_id("minecraft:particle_type", name)?, - data: None, - }) - }; let emitter = if radius < 2.0 { "minecraft:explosion" } else { "minecraft:explosion_emitter" }; - let (Some(at_center), Some(poof), Some(smoke)) = ( - particle(emitter), - particle("minecraft:poof"), - particle("minecraft:smoke"), - ) else { - return; + let sound = "minecraft:entity.generic.explode"; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, true) + { + self.send_explosion(packet, &[]); + } + } + + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, + /// no block particles, and for each player it pushed the push + /// (`ServerExplosion.hitPlayers`), which only that client applies, as + /// nothing hurt them. + pub(super) fn lan_wind_burst( + &self, + center: [f64; 3], + radius: f32, + sound: &str, + block_count: usize, + pushed: &[(u32, [f64; 3])], + ) { + let emitter = if radius < 2.0 { + "minecraft:gust_emitter_small" + } else { + "minecraft:gust_emitter_large" + }; + if let Some(packet) = + self.explosion_packet(center, radius, block_count, emitter, sound, false) + { + self.send_explosion(packet, pushed); + } + } + + /// `ClientboundExplodePacket` without a push, or None while not serving. + /// The sound is the level's, which the players hear already, so it isn't + /// played from the packet. + fn explosion_packet( + &self, + center: [f64; 3], + radius: f32, + block_count: usize, + emitter: &str, + sound: &str, + block_particles: bool, + ) -> Option { + let hub = &self.lan.as_ref()?.hub; + let particle = |name: &str| { + Some(Particle { + id: hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) }; // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. let info = |particle, scaling| play::ExplosionParticle { @@ -207,22 +258,49 @@ impl Game<'_> { speed: 1.0, weight: 1, }; - let packet = C::Explode(play::Explode { + let block_particles = if block_particles { + vec![ + info(particle("minecraft:poof")?, 0.5), + info(particle("minecraft:smoke")?, 1.0), + ] + } else { + Vec::new() + }; + Some(play::Explode { center, radius, block_count: block_count as i32, knockback: None, - particle: at_center, - sound: match host - .hub - .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") - { + particle: particle(emitter)?, + sound: match hub.registry_id("minecraft:sound_event", sound) { Some(id) => (id, None), - None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + None => (-1, Some((sound.into(), None))), }, - block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + block_particles, play_sound: false, - }); - host.hub.broadcast_near(center, 64.0, &packet, None); + }) + } + + /// `packet` to each player within 64 blocks of its centre, with the push + /// `pushed` holds for them. + fn send_explosion(&self, mut packet: play::Explode, pushed: &[(u32, [f64; 3])]) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let center = packet.center; + let plain = C::Explode(packet.clone()).encode(); + for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) { + let d: f64 = (0..3).map(|k| (g.position[k] - center[k]).powi(2)).sum(); + if d >= 4096.0 { + continue; + } + match pushed.iter().find(|(conn, _)| *conn == g.conn) { + Some((_, push)) => { + packet.knockback = Some(*push); + g.send(&C::Explode(packet.clone())); + } + None => g.sender.send(plain.clone()), + } + } } } diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 72e6ee0e8..0754bca8b 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -22,6 +22,14 @@ const PLAYER_KNOCKBACK: f32 = 1.22; /// `BreezeWindCharge.RADIUS`. const BREEZE_RADIUS: f32 = 3.0; +/// A burst `wind_burst` puts off until a guest's turn is over. +pub(super) struct Burst { + center: [f64; 3], + radius: f32, + multiplier: f32, + breeze: bool, + wind_charge: bool, +} /// `Projectile.deflect` with `ProjectileDeflection.REVERSE`. pub(super) fn reverse(p: &mut Projectile, jitter: f32) { p.velocity = Vec3::new( @@ -196,7 +204,9 @@ impl Game<'_> { set.into_iter().collect() } /// `ServerExplosion.hurtEntities` for a calculator that damages nothing: - /// knockback scaled by distance, exposure and the multiplier. + /// knockback scaled by distance, exposure and the multiplier. Returns the + /// guests it pushed and by how much (`hitPlayers`), which their clients + /// apply from the burst's packet. fn wind_knockback( &mut self, center: [f64; 3], @@ -204,7 +214,7 @@ impl Game<'_> { multiplier: f32, wind_charge: bool, blocklike: bool, - ) { + ) -> Vec<(u32, [f64; 3])> { let diameter = f64::from(radius * 2.0); let distance = |p: [f64; 3]| { ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) @@ -223,42 +233,30 @@ impl Game<'_> { [d[0] / l, d[1] / l, d[2] / l] } }; - let multiplier = f64::from(multiplier); - // The player (not a spectator; a flying creative player takes none). - if let Some(p) = self.player.as_ref() - && !self.spectator() - { - let feet = [p.position.x, p.position.y, p.position.z]; - let dist = distance(feet) / diameter; - let flying = self.creative && p.flying; - if dist <= 1.0 && !flying { - 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 power = (1.0 - dist) * f64::from(exposure) * multiplier; - let dir = direction(eye); - if let Some(p) = self.player.as_mut() { - p.velocity = Vec3::new( - p.velocity.x + dir[0] * power, - p.velocity.y + dir[1] * power, - p.velocity.z + dir[2] * power, - ); - // ServerPlayer.onExplosionHit: a wind charge's burst cancels the - // fall; any other burst ends the grace of the last impulse. - let at = p.position; - p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + // The player, then every other player in the level (LAN guests), + // each swapped in as the player. In a guest's turn (a mace's wind + // burst) the player is that guest. + let own = self.wind_push_player(center, radius, multiplier, wind_charge); + let mut pushed: Vec<_> = self.lan_acting.zip(own).into_iter().collect(); + 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 { + let push = self.as_guest(&mut host, conn, |g| { + g.wind_push_player(center, radius, multiplier, wind_charge) + }); + if let Some(Some(push)) = push { + pushed.push((conn, push)); } } + self.lan = Some(host); } + let multiplier = f64::from(multiplier); let mut mobs = std::mem::take(&mut self.mobs); for m in mobs.iter_mut().filter(|m| m.alive()) { let feet = [m.position.x, m.position.y, m.position.z]; @@ -351,6 +349,67 @@ impl Game<'_> { push(t.position, &mut t.velocity, self); } self.tnts = tnts; + pushed + } + /// `ServerExplosion.hurtEntities` for the player (not a spectator, nor a + /// creative player flying): the push, less with explosion knockback + /// resistance, and `ServerPlayer.onExplosionHit`. Returns the push. + fn wind_push_player( + &mut self, + center: [f64; 3], + radius: f32, + multiplier: f32, + wind_charge: bool, + ) -> Option<[f64; 3]> { + if self.spectator() { + return None; + } + let resistance = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:explosion_knockback_resistance").ok()) + .unwrap_or(0.0); + let creative = self.creative; + let p = self.player.as_ref()?; + 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() + / f64::from(radius * 2.0); + if dist > 1.0 || creative && p.flying { + return None; + } + let w = f64::from(p.dimensions.width) / 2.0; + let h = f64::from(p.dimensions.height); + let eye = [ + feet[0] - center[0], + feet[1] + f64::from(p.dimensions.eye_height) - center[1], + feet[2] - center[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 power = (1.0 - dist) * f64::from(exposure) * f64::from(multiplier) * (1.0 - resistance); + let l = (eye[0] * eye[0] + eye[1] * eye[1] + eye[2] * eye[2]).sqrt(); + let push = if l < 1.0e-5 { + [0.0; 3] + } else { + eye.map(|d| d / l * power) + }; + let p = self.player.as_mut()?; + p.velocity = Vec3::new( + p.velocity.x + push[0], + p.velocity.y + push[1], + p.velocity.z + push[2], + ); + // ServerPlayer.onExplosionHit: a wind charge's burst cancels the + // fall; any other burst ends the grace of the last impulse. + let at = p.position; + p.impulse.set_ignore_fall_damage(wind_charge, Some(at)); + Some(push) } /// The burst: knockback, the blocks that react, the gust and the sound. pub(super) fn wind_burst( @@ -361,13 +420,27 @@ impl Game<'_> { breeze: bool, wind_charge: bool, ) -> Result<()> { + // In a guest's turn (their charge landing, their mace's burst) the + // host holds the other players (`as_guest`): the burst waits for the + // turn to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures.wind_bursts.push(Burst { + center, + radius, + multiplier, + breeze, + wind_charge, + }); + return Ok(()); + } // ServerExplosion.explode: the blast is heard first. let ctx = horizon_client::sculk::Context::default(); self.post_game_event("minecraft:explode", center, ctx); let mut targets = self.wind_positions(center, radius); // ServerExplosion.shouldAffectBlocklikeEntities let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing"); - self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let pushed = self.wind_knockback(center, radius, multiplier, wind_charge, blocklike); + let block_count = targets.len(); // Explosion.canTriggerBlocks: a breeze's charge needs mob griefing. if !breeze || self.ui.rules.bool("mob_griefing") { // Util.shuffle(list, level.random) @@ -396,6 +469,14 @@ impl Game<'_> { }; self.particles .add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.lan_wind_burst(center, radius, sound, block_count, &pushed); + Ok(()) + } + /// The bursts guests' turns put off. + pub(super) fn flush_wind_bursts(&mut self) -> Result<()> { + for b in std::mem::take(&mut self.creatures.wind_bursts) { + self.wind_burst(b.center, b.radius, b.multiplier, b.breeze, b.wind_charge)?; + } Ok(()) } /// `BlockBehaviour.onExplosionHit` for `TRIGGER_BLOCK`: doors, gates, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index a5df97258..c4df7d147 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1336,6 +1336,16 @@ impl ParticleEngine { ParticleType::ExplosionEmitter }; self.add(&ParticleOptions::simple(ty), center, [1.0, 0.0, 0.0]); + self.explosion_blocks(center, radius, block_count, is_air); + } + /// `ClientExplosionTracker` with `Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES`. + pub fn explosion_blocks( + &mut self, + center: [f64; 3], + radius: f32, + block_count: usize, + is_air: &dyn Fn([i32; 3]) -> bool, + ) { for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 9b86a4934..41d39f37b 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -199,6 +199,9 @@ address. The script then checks, from both sides, what a guest's game used to ge and scope with a spyglass: each use starts on their own client and on the server, and letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). +- wind: the host and the guest each throw a wind charge at their feet: the server's burst + launches them about six blocks up (the push in ClientboundExplodePacket) and they land + unhurt (#1386). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4673,5 +4676,55 @@ CHECKS += ['helduse'] CHECK_FNS.update(helduse=check_held_use) +def check_wind(host, guest, out): + """A wind charge each player throws at its own feet (ServerExplosion with TRIGGER_BLOCK): the + server's burst pushes the thrower through its ClientboundExplodePacket (hitPlayers), which + launches it about six blocks up, and onExplosionHit spares it the fall damage where it lands + (#1386).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='gamerule natural_health_regeneration false') + seen = {} + try: + for game, dz in ((host, -4), (guest, 4)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 2} {x + 2} {hy - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 2} {x + 2} {hy + 10} {z + 2} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect clear @s') + game('command', command='effect give @s minecraft:instant_health 1 5 true') + game('command', command='give @s minecraft:wind_charge 2') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} 0 90') + game.wait(20) + start = pos_of(game)[1] + game.raw('use-item') + peak = start + for _ in range(30): + game.wait(2) + peak = max(peak, pos_of(game)[1]) + game.wait(40) + game.shot(out, 'wind') + me = own(game) + seen[game.name] = {'rose': round(peak - start, 1), + 'landed': round(me['position'][1] - start, 1), + 'health': me['health'], + 'server_health': server_player(host, game)['health'], + 'charges': server_count(game, 'wind_charge')} + finally: + host('command', command='gamerule natural_health_regeneration true') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + # Vanilla rises about 6 blocks from a charge at the feet. + assert 4 < s['rose'] < 8 and s['landed'] == 0, f'{name}: {seen}' + assert s['health'] == 20 and s['server_health'] == 20 and s['charges'] == 1, f'{name}: {seen}' + return seen + + +CHECKS += ['wind'] +CHECK_FNS.update(wind=check_wind) + + if __name__ == '__main__': main()