diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 5eadb0626..7ac3d0829 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4102,7 +4102,7 @@ impl Game<'_> { self.tick_riding(keys)?; } let riding = self.riding.is_some(); - let ghast_collisions = self.happy_ghast_player_collisions(); + let entity_collisions = self.player_entity_collisions(); let spin_targets = self.spin_targets(); self.sync_player_body(); let Some(player) = self.player.as_mut() else { @@ -4149,7 +4149,7 @@ impl Game<'_> { ); if !riding { MotionWorld { - entities: &ghast_collisions, + entities: &entity_collisions, player, scene: &mut self.world, assets: &self.pack.assets, diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 719ce8dd2..6765c3df8 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -59,6 +59,30 @@ impl Game<'_> { } /// Block commands; None when `words[0]` is not one of them. pub(super) fn block_command(&mut self, words: &[&str]) -> Result> { + let ours = matches!( + words.first(), + Some(&("setblock" | "fill" | "getblock" | "container")) + ); + // Single player on its server thread: the world is the server's, so + // the command runs there, in the owner's level, and the client hears + // of it like any change. + if ours && let Some(server) = &self.integrated { + let owned: Vec = words.iter().map(|w| (*w).to_owned()).collect(); + return server + .call(move |g| { + let words: Vec<&str> = owned.iter().map(String::as_str).collect(); + g.in_owner_level(|g| g.block_command(&words).map_err(|e| e.to_string())) + }) + .ok_or("the integrated server stopped")? + .map_err(Into::into); + } + // Another server's world changes only through its own commands, which + // it checks as the player's; `getblock` and `container` read what this + // client has of it. + if self.remote.is_some() && matches!(words.first(), Some(&("setblock" | "fill"))) { + self.send_chat(&format!("/{}", words.join(" "))); + return Ok(Some(json!({ "ok": true, "sent": true }))); + } let int = |i: usize| -> Result { Ok(words .get(i) diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 6b24226d9..bc9afd18b 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -183,13 +183,18 @@ impl BoatModels { } impl Game<'_> { fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { + self.fluid_height_of(x, y, z, Some(Fluid::Water)) + } + /// `FluidState.getHeight` and whether it is a source, for `fluid` or, + /// with `None`, any fluid (`ClipContext.Fluid.ANY`). + fn fluid_height_of(&self, x: i32, y: i32, z: i32, fluid: Option) -> Option<(f32, bool)> { let f = self.res.facts().get(self.world.block(x, y, z)); - if f.fluid != Fluid::Water { + if f.fluid == Fluid::None || fluid.is_some_and(|want| f.fluid != want) { return None; } let above = self.res.facts().get(self.world.block(x, y + 1, z)); // FluidState.getHeight: 1 under the same fluid, else amount / 9. - let height = if above.fluid == Fluid::Water { + let height = if above.fluid == f.fluid { 1.0 } else { f32::from(f.fluid_level) / 9.0 @@ -461,6 +466,59 @@ impl Game<'_> { let b = self.boats[i].clone(); self.boats[i] = self.tick_boat(b, false); } + // AbstractBoat.tick's applyEffectsFromBlocks, on the server for every + // boat, the client-driven ones too. + let mut i = 0; + while i < self.boats.len() { + let p = self.boats[i].position; + let skip = Some(self.boats[i].id) == self.riding + || !ticking(p.x.floor() as i32, p.z.floor() as i32); + if skip || !self.boat_lava_tick(i) { + i += 1; + } + } + } + /// `LavaFluid.entityInside` (`lavaHurt`) from the two + /// `applyEffectsFromBlocks` calls in `AbstractBoat.tick`: twice 40 + /// damage, so lava breaks a boat on its first tick inside, and the fire + /// `lavaIgnite` lights never gets to burn it. True when the boat broke. + fn boat_lava_tick(&mut self, i: usize) -> bool { + if !self.in_lava(self.boats[i].bounds()) { + return false; + } + for _ in 0..2 { + let p = self.boats[i].position; + let broke = self.hurt_boat(i, 4.0, false); + self.lava_hurt_sound([p.x, p.y, p.z]); + if broke { + return true; + } + } + false + } + /// `Entity.lavaHurt`'s sound once the hurt went through. + pub(super) fn lava_hurt_sound(&mut self, at: [f64; 3]) { + let pitch = 2.0 + self.world.random.next_float() * 0.4; + self.audio + .play("minecraft:entity.generic.burn", Some(at), 0.4, pitch); + } + /// Whether a vehicle's box, deflated by 1e-5, reaches into lava below its + /// surface (`Entity.collidedWithFluid`). + pub(super) fn in_lava(&self, bb: Aabb) -> bool { + let (lo, hi) = (bb.min_position(), bb.max_position()); + let e = 1.0e-5; + for x in (lo.x + e).floor() as i32..=(hi.x - e).floor() as i32 { + for y in (lo.y + e).floor() as i32..=(hi.y - e).floor() as i32 { + for z in (lo.z + e).floor() as i32..=(hi.z - e).floor() as i32 { + if let Some((height, _)) = self.fluid_height_of(x, y, z, Some(Fluid::Lava)) + && lo.y + e < f64::from(y) + f64::from(height) + { + return true; + } + } + } + } + false } /// The player's tick while riding: steer, tick the boat, sit in it. pub(super) fn tick_riding(&mut self, keys: Keys) -> horizon_client::Result<()> { @@ -489,6 +547,9 @@ impl Game<'_> { p.fall_distance = 0.0; } self.boats[i] = b; + if self.boat_lava_tick(i) { + self.riding = None; + } Ok(()) } /// `getDismountLocationForPassenger`: in front of the player if there is @@ -534,7 +595,8 @@ impl Game<'_> { }; let dir = view_vector(self.yaw, self.pitch); let reach = self.reach(); - // ClipContext.Fluid.ANY: the first water surface or block along the ray. + // ClipContext.Fluid.ANY: the first fluid surface (water or lava) or + // block along the ray. let block = self.pick().map(|h| { ( h.point, @@ -544,7 +606,7 @@ impl Game<'_> { .sqrt(), ) }); - let mut water = None; + let mut fluid = None; let mut t = 0.0; while t < reach { let p: [f64; 3] = std::array::from_fn(|a| eye[a] + dir[a] * t); @@ -553,15 +615,15 @@ impl Game<'_> { p[1].floor() as i32, p[2].floor() as i32, ); - if let Some((h, _)) = self.fluid_height(x, y, z) + if let Some((h, _)) = self.fluid_height_of(x, y, z, None) && p[1] <= f64::from(y) + f64::from(h) { - water = Some(([p[0], f64::from(y) + f64::from(h), p[2]], t)); + fluid = Some(([p[0], f64::from(y) + f64::from(h), p[2]], t)); break; } t += 0.05; } - let hit = match (block, water) { + let hit = match (block, fluid) { (Some(b), Some(w)) => { if w.1 < b.1 { w.0 @@ -682,15 +744,23 @@ impl Game<'_> { return false; } self.vehicle_attack_sounds(); + self.hurt_boat(i, damage, self.creative); + self.swing_arm(); + true + } + /// `VehicleEntity.hurtServer`: wobble, add the damage and break past 40 + /// (`creative`: a creative player's hit removes it without drops). + /// True when the boat was removed. + pub(super) fn hurt_boat(&mut self, i: usize, damage: f32, creative: bool) -> bool { let b = &mut self.boats[i]; b.hurt_dir = -b.hurt_dir; b.hurt_time = 10; b.damage += damage * 10.0; - let destroyed = self.creative || b.damage > 40.0; + let destroyed = creative || b.damage > 40.0; if destroyed { let b = self.boats.remove(i); let at = [b.position.x, b.position.y, b.position.z]; - if !self.creative && self.ui.rules.bool("entity_drops") { + if !creative && self.ui.rules.bool("entity_drops") { // ChestBoat.destroy: chestVehicleDestroyed spills the contents. for stack in b.items.iter().flatten() { self.spawn_item(stack.clone(), at, super::dispenser::new_item_motion(), 10); @@ -709,8 +779,7 @@ impl Game<'_> { ); } } - self.swing_arm(); - true + destroyed } /// AbstractBoatRenderer. pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index 50b1fa814..93d919911 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -128,7 +128,7 @@ impl Game<'_> { if self.state_in_tag(avoid, ground) { return false; } - let entities = self.happy_ghast_player_collisions(); + let entities = self.player_entity_collisions(); let Some(player) = self.player.as_mut() else { return false; }; diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index 8ce0a4231..48cbffa6b 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -10,9 +10,10 @@ use horizon_core::geometry::{Aabb, Vec3}; use horizon_world::registry::BlockStateId; impl Game<'_> { - /// Client `EntityGetter.getEntityCollisions`: only solid happy ghasts, - /// excluding the player's own vehicle. - pub(super) fn happy_ghast_player_collisions(&self) -> Vec { + /// Client `EntityGetter.getEntityCollisions` for the player: the + /// entities that `canBeCollidedWith` it, solid happy ghasts and boats + /// (`AbstractBoat.canBeCollidedWith`), except the player's own vehicle. + pub(super) fn player_entity_collisions(&self) -> Vec { let Some(p) = &self.player else { return Vec::new(); }; @@ -24,6 +25,12 @@ impl Game<'_> { && happy_ghast::collides_with_player(m, p.position.y) }) .map(|m| m.bounds()) + .chain( + self.boats + .iter() + .filter(|b| Some(b.id) != self.riding) + .map(super::boats::Boat::bounds), + ) .collect() } /// `HappyGhast.mobInteract`. Returns whether the click was used. diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ee343c64b..44df5fe20 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -496,6 +496,22 @@ impl Game<'_> { out } + /// Run `f` with the owner's level in place (the server holds one per + /// dimension), then put back the level that was. + pub(super) fn in_owner_level(&mut self, f: impl FnOnce(&mut Self) -> T) -> T { + let owner = self.serving.as_ref().map(|s| s.owner); + let dim = self.lan.as_ref().and_then(|h| { + let g = h.hub.guests.iter().find(|g| Some(g.uuid) == owner)?; + Some(super::Dim::from_id(&g.dimension)) + }); + let back = dim.and_then(|d| self.enter_command_level(d)); + let out = f(self); + if let Some(back) = back { + self.enter_command_level(back); + } + out + } + /// The window's requests, between two ticks. fn run_tasks(&mut self) { let tasks: Vec = match &self.serving { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 500c22097..5bee2af96 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1713,6 +1713,17 @@ impl Game<'_> { g.use_delay -= 1; } }); + // ServerPlayerGameMode.handleBlockBreakAction: a creative + // player's START breaks the block once (destroyAndAck) and + // leaves nothing being destroyed; its client sends no STOP. + // Kept, the dig broke whatever was put there next, every + // destroy delay, for as long as the player broke nothing else. + if digging.is_some() + && host.hub.guests[gi].creative() + && let Some(play) = host.play.get_mut(&conn) + { + play.digging = None; + } } // Player.tick: a different main-hand item resets the attack // strength, and detectEquipmentUpdates gives the guest its modifiers. diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 9173139aa..0b58e4f88 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -686,40 +686,53 @@ impl Game<'_> { } } } - /// `AbstractMinecart.push(player)` when the player walks into a cart. + /// `AbstractMinecart.push` from each player walking into a cart + /// (`LivingEntity.pushEntities`): the window's player and every server + /// player (single player's own on its server thread, LAN guests). A + /// player in a vehicle pushes nothing here. The quarter push the player + /// gets back only moves the server's copy of it (`Entity.push` marks + /// `needsSync`, which `ServerEntity` sends to the other players only), + /// so no player feels it. fn push_carts(&mut self) { - let player = self.player.as_ref().map(|p| p.position); - let riding = self.riding; - for i in 0..self.carts.len() { - if Some(self.carts[i].id) == riding { - continue; + if self.carts.is_empty() { + return; + } + // (feet, box) + let mut pushers: Vec<(Vec3, Aabb)> = Vec::new(); + if self.riding.is_none() + && let Some(p) = self.player.as_ref() + { + pushers.push((p.position, p.bounds())); + } + if let Some(host) = self.lan.as_ref() { + for g in host.hub.guests.iter().filter(|g| { + host.hub.here(g) && g.loaded && !g.dead && !g.spectator() && g.vehicle.is_none() + }) { + let [x, y, z] = g.position; + let height = if g.sneaking { 1.5 } else { 1.8 }; + let bb = Aabb::new( + Vec3::new(x - 0.3, y, z - 0.3), + Vec3::new(x + 0.3, y + height, z + 0.3), + ); + pushers.push((Vec3::new(x, y, z), bb)); } - if let Some(pp) = player { - let bb = self.carts[i].bounds(); - let (lo, hi) = (bb.min_position(), bb.max_position()); - let touching = pp.x + 0.3 > lo.x - && pp.x - 0.3 < hi.x - && pp.z + 0.3 > lo.z - && pp.z - 0.3 < hi.z - && pp.y + 1.8 > lo.y - && pp.y < hi.y; - if touching && riding.is_none() { - let c = &mut self.carts[i]; - let (mut xa, mut za) = (pp.x - c.position.x, pp.z - c.position.z); - let dd = xa * xa + za * za; - if dd >= 1.0e-4 { - let d = dd.sqrt(); - let pow = (1.0 / d).min(1.0); - xa = xa / d * pow * f64::from(0.1f32) * 0.5; - za = za / d * pow * f64::from(0.1f32) * 0.5; - c.velocity.x -= xa; - c.velocity.z -= za; - if let Some(p) = self.player.as_mut() { - p.velocity.x += xa / 4.0; - p.velocity.z += za / 4.0; - } - } + } + for (feet, bb) in pushers { + for c in &mut self.carts { + if !bb.intersects(c.bounds()) { + continue; } + let (mut xa, mut za) = (feet.x - c.position.x, feet.z - c.position.z); + let dd = xa * xa + za * za; + if dd < f64::from(1.0e-4f32) { + continue; + } + let d = dd.sqrt(); + let pow = (1.0 / d).min(1.0); + xa = xa / d * pow * f64::from(0.1f32) * 0.5; + za = za / d * pow * f64::from(0.1f32) * 0.5; + c.velocity.x -= xa; + c.velocity.z -= za; } } } @@ -797,7 +810,7 @@ impl Game<'_> { let ridden = self.guest_vehicles(); // By id: an exploding cart can destroy or prime others mid-loop. let ids: Vec = self.carts.iter().map(|c| c.id).collect(); - for id in ids { + for &id in &ids { let Some(i) = self.carts.iter().position(|c| c.id == id) else { continue; }; @@ -823,6 +836,33 @@ impl Game<'_> { self.carts.remove(i); } } + // On the server for every cart, the ridden ones too. + for id in ids { + if let Some(i) = self.carts.iter().position(|c| c.id == id) { + let p = self.carts[i].position; + if ticking(p.x.floor() as i32, p.z.floor() as i32) { + self.cart_lava_tick(id); + } + } + } + } + /// `lavaHurt` twice a tick in lava: from `LavaFluid.entityInside` in the + /// behaviour's `applyEffectsFromBlocks`, then from `AbstractMinecart.tick`'s + /// own `isInLava`. The second breaks the cart, or primes a TNT minecart + /// (`MinecartTNT.destroy` for a fire source). A cart has no `baseTick`, + /// so the fire `lavaIgnite` lights never burns it. + fn cart_lava_tick(&mut self, id: u32) { + for _ in 0..2 { + let Some(i) = self.carts.iter().position(|c| c.id == id) else { + return; + }; + if !self.in_lava(self.carts[i].bounds()) { + return; + } + let p = self.carts[i].position; + self.hurt_cart(i, 4.0, false, true); + self.lava_hurt_sound([p.x, p.y, p.z]); + } } /// `ClientPacketListener.postAddEntitySoundInstance` for the carts that /// joined the level since the last tick, and `LocalPlayer.startRiding`'s diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 812d6fc15..da0def0fb 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -3081,7 +3081,7 @@ impl Game<'_> { self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); // Gui.tick: the titles, the action bar and the held item's name. self.tick_hud(); - let ghast_collisions = self.happy_ghast_player_collisions(); + let entity_collisions = self.player_entity_collisions(); let pushed = self.remote_pushes(); let Some(player) = self.player.as_mut() else { return Ok(()); @@ -3165,7 +3165,7 @@ impl Game<'_> { } else if !dead && !riding { player.velocity = player.velocity.add_vector(pushed); MotionWorld { - entities: &ghast_collisions, + entities: &entity_collisions, player, scene: &mut self.world, assets: &self.pack.assets, diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index bb527c467..42dd7ec53 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -5296,6 +5296,100 @@ CHECKS += ['digging'] CHECK_FNS.update(digging=check_digging) +def check_vehicles(host, guest, out): + """The host and the guest each (#1551): + - in creative, break a block and have it put back: the server's dig ends with the break + (ServerPlayerGameMode.handleBlockBreakAction), so the block stays; + - land on a boat on the ground and stand on it (AbstractBoat.canBeCollidedWith); + - sit in a boat that lava reaches: lavaHurt twice a tick breaks it at once, and the rider is out; + - see a minecart in lava break, and a TNT minecart in lava prime and go off; + - stand half in a minecart off rails and push it away (AbstractMinecart.push from the server's + player).""" + result = {} + spots = apart(host, guest) + for label, player in (('host', host), ('guest', guest)): + x, y, z = spots[label] + seen = result[label] = {} + near = lambda kind, at: [o for o in host('status')['objects'] if o['kind'].endswith(kind) + and abs(o['position'][0] - at[0]) < 2 and abs(o['position'][2] - at[2]) < 2] + try: + cell = (x, y + 1, z + 2) + player('command', command='gamemode creative') + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(5) + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 1.5:.2f}', f'{z + 2.5:.2f}') + player.raw('mouse', 'left', 'click') + player.wait(5) + seen['broken'] = host.raw('block', *cell).get('block') + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:stone') + player.wait(20) + seen['put_back'] = [g.raw('block', *cell).get('block') for g in (host, player)] + player('command', command=f'setblock {cell[0]} {cell[1]} {cell[2]} minecraft:air') + + player('command', command='gamemode survival') + player('command', command='effect give @s minecraft:fire_resistance 300 0 true') + boat_at = (x + 0.5, y, z + 3.5) + player('command', command=f'summon minecraft:oak_boat {boat_at[0]} {y} {boat_at[2]}') + player.wait(10) + player('command', command=f'tp @s {boat_at[0]} {y + 1.2:.2f} {boat_at[2]}') + player.wait(20) + seen['on_boat'] = [round(pos_of(player)[1] - y, 3), round(server_player(host, player)['position'][1] - y, 3)] + + player('command', command=f'tp @s {x + 0.5} {y} {z + 1.5} 0 0') + player.wait(10) + board(player, 'oak_boat', boat_at) + player('command', command=f'setblock {x} {y} {z + 3} minecraft:lava') + player.wait(10) + seen['rider'] = {'riding': player('status').get('riding'), 'boats': len(near('oak_boat', boat_at))} + + player('command', command='gamemode creative') + player('command', command=f'summon minecraft:minecart {boat_at[0]} {y} {boat_at[2]}') + player.wait(10) + seen['minecart_in_lava'] = len(near('minecart', boat_at)) + booms = player('status')['heard'].get('minecraft:entity.generic.explode', 0) + player('command', command=f'summon minecraft:tnt_minecart {boat_at[0]} {y} {boat_at[2]}') + player.wait(60) + seen['tnt_minecart'] = {'left': len(near('tnt_minecart', boat_at)), + 'booms': player('status')['heard'].get('minecraft:entity.generic.explode', 0) - booms} + + player('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 6} minecraft:air') + player('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 6} minecraft:stone') + player('command', command='gamemode survival') + cart_at = (x + 0.5, y, z + 1.6) + player('command', command=f'summon minecraft:minecart {cart_at[0]} {y} {cart_at[2]}') + player.wait(10) + before = near('minecart', cart_at)[0]['position'] + # Half into the cart from the north: it is pushed south until they are apart. + player('command', command=f'tp @s {x + 0.5} {y} {before[2] - 0.4:.2f} 0 0') + player.wait(20) + after = near('minecart', cart_at)[0]['position'] + seen['cart_pushed'] = round(after[2] - before[2], 3) + player.shot(out, f'vehicles-{label}') + finally: + player('command', command='kill @e[type=minecraft:minecart]') + player('command', command='kill @e[type=minecraft:oak_boat]') + player('command', command='kill @e[type=minecraft:item]') + player('command', command=f'fill {x - 3} {y} {z - 3} {x + 4} {y + 3} {z + 6} minecraft:air') + player('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 4} {y - 1} {z + 6} minecraft:stone') + player('command', command='effect clear @s') + player('command', command='gamemode survival') + player('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + player.wait(5) + for label, seen in result.items(): + assert seen['broken'] == 'minecraft:air', f'{label}: the creative click broke nothing: {seen}' + assert seen['put_back'] == ['minecraft:stone'] * 2, f'{label}: the server kept digging: {seen}' + assert all(0.5 < dy < 0.65 for dy in seen['on_boat']), f'{label}: not standing on the boat: {seen}' + assert seen['rider'] == {'riding': None, 'boats': 0}, f'{label}: lava left the boat or its rider: {seen}' + assert seen['minecart_in_lava'] == 0, f'{label}: a minecart outlived lava: {seen}' + assert seen['tnt_minecart'] == {'left': 0, 'booms': 1}, f'{label}: the TNT minecart in lava: {seen}' + assert seen['cart_pushed'] > 0.1, f'{label}: the minecart stayed in the player: {seen}' + return result + + +CHECKS += ['vehicles'] +CHECK_FNS.update(vehicles=check_vehicles) + + # How far a plain wooden sword hit slides a standing player in vanilla: LivingEntity.knockback(0.4) from # the server copy's (0, -0.0784, 0), then the victim's own client. VANILLA_PUSH = 1.989