diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 39d45073f..de7f16cbd 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1817,6 +1817,16 @@ impl Game<'_> { self.stack_in_mut(self.held_slot()) } /// The slot of the hand that acts: the selected one, or `OFFHAND_SLOT`. + /// `LivingEntity.canGlideUsing`: a glider in the chest slot that will + /// not break with its next point of wear. + fn glider_worn(&self) -> bool { + self.armor[1].as_ref().is_some_and(|s| { + self.res + .items() + .get(&s.item) + .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) + }) + } fn held_slot(&self) -> usize { match self.hand { Hand::Main => self.selected, @@ -1994,6 +2004,28 @@ impl Game<'_> { particle.scale(0.6); self.particles.push(particle); } + /// `Player.dropEquipment` for the player who died: unless keep_inventory + /// is on, `destroyVanishingCursedItems`, then `Inventory.dropAll` from + /// `at` (the eyes less 0.3): slots 0..36, armor feet to head (36..39), + /// the off hand (40), each thrown in a random direction. + fn drop_inventory(&mut self, at: [f64; 3]) { + if self.ui.rules.bool("keep_inventory") { + return; + } + let mut stacks: Vec = + self.inventory.iter_mut().filter_map(Option::take).collect(); + stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); + stacks.extend(self.offhand.take()); + stacks.retain(|s| s.enchantment_level("minecraft:vanishing_curse") == 0); + self.apply_equipment(); + for stack in stacks { + let r = &mut self.world.random; + let strength = f64::from(r.next_float()) * 0.5; + let angle = f64::from(r.next_float()) * std::f64::consts::TAU; + let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; + self.spawn_item(stack, at, v, 40); + } + } fn spawn_item( &mut self, stack: ItemStack, @@ -3649,16 +3681,8 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && !hand_changed { - self.release_bow(ticks); - } - if &*stack.item == "minecraft:spyglass" { - self.stop_spyglass(); - } - if &*stack.item == "minecraft:trident" && !hand_changed { - self.release_trident(ticks); - } self.using = None; + self.release_used_item(&stack, ticks, hand_changed); return; } let Some(info) = self.res.items().get(&stack.item).cloned() else { @@ -3714,6 +3738,17 @@ impl Game<'_> { self.using = Some((slot, ticks)); } } + /// `LivingEntity.releaseUsingItem` (`Item.releaseUsing`) for `stack`, + /// used for `ticks`, its hand acting: a bow or a trident lets go (not + /// when its hand changed), a spyglass stops scoping. + pub(super) fn release_used_item(&mut self, stack: &ItemStack, ticks: u32, hand_changed: bool) { + match &*stack.item { + "minecraft:bow" if !hand_changed => self.release_bow(ticks), + "minecraft:trident" if !hand_changed => self.release_trident(ticks), + "minecraft:spyglass" => self.stop_spyglass(), + _ => {} + } + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; @@ -3803,7 +3838,12 @@ impl Game<'_> { } self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; - if m.progress >= 1.0 { + // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's + // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK + // (`guest_stop_digging`), never breaking it on its own count. Breaking it here would + // take the block from under the player's crack before the player's client predicts the + // break, so it gets neither particles nor sound. + if m.progress >= 1.0 && (self.lan_acting.is_none() || m.ticks == 1) { let pos = m.pos; self.mining = None; self.break_block(pos)?; @@ -3937,13 +3977,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = self.glider_worn(); // A saved death already dropped inventory/XP and counted the death. if player.health.dead_or_dying() { self.screen = Screen::Dead; @@ -4021,6 +4055,7 @@ impl Game<'_> { let riding = self.riding.is_some(); let ghast_collisions = self.happy_ghast_player_collisions(); let spin_targets = self.spin_targets(); + let glider = self.glider_worn(); let Some(player) = self.player.as_mut() else { // A dedicated server has no local player: the world still runs. if self.options.dedicated.is_some() { @@ -4063,13 +4098,7 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.pitch = self.pitch; - // LivingEntity.canGlideUsing: a glider in its slot that will not break next. - player.glider = self.armor[1].as_ref().is_some_and(|s| { - self.res - .items() - .get(&s.item) - .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) - }); + player.glider = glider; // LocalPlayer.modifyInput: walking while using an item. player.item_use_speed = self .using @@ -4306,20 +4335,8 @@ impl Game<'_> { .experience .death_reward(self.ui.rules.bool("keep_inventory") || self.spectator()); self.spawn_orbs(feet, reward); - if !self.creative && !self.ui.rules.bool("keep_inventory") { - // Inventory.dropAll: slots 0..36, armor feet to head (36..39), off hand (40). - let mut stacks: Vec = - self.inventory.iter_mut().filter_map(Option::take).collect(); - stacks.extend(self.armor.iter_mut().rev().filter_map(Option::take)); - stacks.extend(self.offhand.take()); - self.apply_equipment(); - for stack in stacks { - let r = &mut self.world.random; - let strength = f64::from(r.next_float()) * 0.5; - let angle = f64::from(r.next_float()) * std::f64::consts::TAU; - let v = [-angle.sin() * strength, 0.2, angle.cos() * strength]; - self.spawn_item(stack, at, v, 40); - } + if !self.spectator() { + self.drop_inventory(at); } self.audio .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 41d2276f5..9305f88ad 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -335,6 +335,12 @@ impl Game<'_> { Some(Ticker::Shulker { .. }) => v["lid"] = json!(self.block_anim(pos, 1.0).shulker.0), _ => {} } + // The lines of a sign, as this client has them. + if let Some(horizon_client::containers::BlockEntity::Sign(sign)) = + self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + { + v["sign"] = json!({ "front": sign.front.lines, "back": sign.back.lines }); + } v } pub(super) fn stack_value(&self, s: &ItemStack) -> Value { @@ -457,6 +463,7 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "flying": p.flying, + "fall_flying": p.fall_flying, "sneaking": self.keys.contains(&KeyCode::ShiftLeft), "sprinting": self.keys.contains(&KeyCode::ControlLeft), "health": p.health.health(), diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index ccc1c6e19..9af1da70c 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -3,9 +3,10 @@ //! pixels, 1024 characters, 100 pages), signing it into a written book, //! reading written books, and lecterns (placing a book, turning its pages //! with a redstone pulse, the comparator output and taking the book). -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::{BlockEntity, Lectern}, + first_person::Hand, hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, @@ -14,6 +15,7 @@ use horizon_client::{ ui, }; use horizon_core::position::BlockPos; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use horizon_world::level::flags as level_flags; use std::time::Instant; use winit::{ @@ -48,9 +50,32 @@ impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { self.gui.atlas.font.split(&Text::literal(page), 114.0) } - /// `WritableBookItem.use` / `WrittenBookItem.use`. + /// `WritableBookItem.use` / `WrittenBookItem.use` (`Player.openItemGui`). + /// A server's player writes in its own client's editor + /// (`LocalPlayer.openItemGui`), and reads on its own client once told to + /// (`ServerPlayer.openItemGui`'s ClientboundOpenBookPacket). pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { - let screen = match &*stack.item { + let written = match &*stack.item { + "minecraft:writable_book" => false, + "minecraft:written_book" => true, + _ => return false, + }; + if self.lan_acting.is_some() { + if written { + let hand = i32::from(self.hand == Hand::Off); + self.guest_packets + .push(C::OpenBook(play::OpenBook { hand })); + } + } else if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } + self.swing_arm(); + true + } + /// The screen a book in hand opens: `BookEditScreen` for a book and + /// quill, `BookViewScreen` for a written book. + fn book_screen(&self, stack: &ItemStack) -> Option { + Some(match &*stack.item { "minecraft:writable_book" => { let mut pages = stack .data() @@ -77,12 +102,31 @@ impl Game<'_> { page: 0, lectern: None, }, - _ => return false, - }; - self.open_book(screen); - self.swing_arm(); + _ => return None, + }) + } + /// `MultiPlayerGameMode.useItem`'s own use of a book and quill on a + /// server's client: its editor opens here at once. + pub(super) fn remote_use_book(&mut self, stack: &ItemStack) -> bool { + if &*stack.item != "minecraft:writable_book" { + return false; + } + if let Some(screen) = self.book_screen(stack) { + self.open_book(screen); + } true } + /// `ClientPacketListener.handleOpenBook`: the written book in that hand. + pub(super) fn remote_open_book(&mut self, hand: i32) { + let hand = if hand == 1 { Hand::Off } else { Hand::Main }; + let screen = self.with_hand(hand, |g| { + let stack = g.held().filter(|s| &*s.item == "minecraft:written_book")?; + g.book_screen(&stack.clone()) + }); + if let Some(screen) = screen { + self.open_book(screen); + } + } fn open_book(&mut self, screen: BookScreen) { self.book = Some(screen); self.keys.clear(); @@ -104,7 +148,9 @@ impl Game<'_> { self.book = None; self.capture(true); } - /// `BookEditScreen.saveChanges`: trailing empty pages dropped. + /// `BookEditScreen.saveChanges` and `BookSignScreen`'s Sign and Close: + /// trailing empty pages dropped, the book in hand updated here and, on a + /// server's client, sent (ServerboundEditBookPacket). fn save_book(&mut self, sign: bool) { let Some(BookScreen::Edit { slot, pages, title, .. @@ -116,29 +162,59 @@ impl Game<'_> { while pages.len() > 1 && pages.last().is_some_and(String::is_empty) { pages.pop(); } - if let Some(stack) = self.stack_in_mut(slot).as_mut() - && &*stack.item == "minecraft:writable_book" - { - if sign { - let mut written = ItemStack::new("minecraft:written_book", 1); - written.data_mut().written = Some(WrittenBook { - title: title.trim().to_owned(), - author: super::chat::PLAYER_NAME.to_owned(), - generation: 0, - pages, - }); - *stack = written; - } else { - stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { - Vec::new() - } else { - pages - }; - stack.tidy(); - } + let title = sign.then(|| title.trim().to_owned()); + if self.remote.is_some() { + self.send(S::EditBook(play::EditBook { + slot: slot as i32, + pages: pages.clone(), + title: title.clone(), + })); } + self.write_book(slot, pages, title); self.capture(true); } + /// The book and quill at `slot` takes the pages, or with a title becomes + /// the written book its writer signed. + fn write_book(&mut self, slot: usize, pages: Vec, title: Option) { + let author = self + .lan_acting_name + .clone() + .unwrap_or_else(|| super::chat::PLAYER_NAME.to_owned()); + let Some(stack) = self + .stack_in_mut(slot) + .as_mut() + .filter(|s| &*s.item == "minecraft:writable_book") + else { + return; + }; + if let Some(title) = title { + let mut written = ItemStack::new("minecraft:written_book", 1); + written.data_mut().written = Some(WrittenBook { + title, + author, + generation: 0, + pages, + }); + *stack = written; + } else { + stack.data_mut().writable_pages = if pages.iter().all(String::is_empty) { + Vec::new() + } else { + pages + }; + stack.tidy(); + } + } + /// `ServerGamePacketListenerImpl.handleEditBook`: a guest's book in a + /// hotbar slot or its off hand (`updateBookContents`, `signBook`). + pub(super) fn lan_edit_book(&mut self, host: &mut LanHost, conn: u32, p: play::EditBook) { + if !((0..9).contains(&p.slot) || p.slot == super::shield::OFFHAND_SLOT as i32) { + return; + } + self.as_guest(host, conn, |g| { + g.write_book(p.slot as usize, p.pages, p.title) + }); + } pub(super) fn book_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; @@ -519,7 +595,26 @@ impl Game<'_> { Some(key) => self.lectern_button(key, 3), None => return Err("not a lectern".into()), }, - Some("done") => self.close_book(), + // The book and quill's buttons: Sign, then Sign and Close; Done + // (which saves), then Cancel. + Some("sign") => match self.book.as_mut() { + Some(BookScreen::Edit { + signing: true, + title, + .. + }) if !title.trim().is_empty() => self.save_book(true), + Some(BookScreen::Edit { signing, .. }) => *signing = true, + _ => return Err("not a book and quill".into()), + }, + Some("done") => match self.book.as_mut() { + Some(BookScreen::Edit { signing: true, .. }) => { + if let Some(BookScreen::Edit { signing, .. }) = self.book.as_mut() { + *signing = false; + } + } + Some(BookScreen::Edit { .. }) => self.save_book(false), + _ => self.close_book(), + }, Some(other) => return Err(format!("unknown book button {other}").into()), } Ok(match &self.book { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f7e4c6b36..38f71dcff 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -232,6 +232,13 @@ impl Game<'_> { "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; + // The sign editor takes raw presses (Enter, arrows, Backspace, Escape). + if self.sign_edit.is_some() { + if arg(2)? != "up" { + self.sign_input(Some(key), None); + } + return ok(); + } // A held edit modifier (`key super down`) and A/C/V/X: the // open book's Select All, Copy, Paste or Cut. if self.book.is_some() && arg(2)? != "up" { @@ -524,6 +531,10 @@ impl Game<'_> { self.book_type(text); return ok(); } + if self.sign_edit.is_some() { + self.sign_input(None, Some(text)); + return ok(); + } match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), @@ -549,7 +560,7 @@ impl Game<'_> { } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), + "type needs the chat screen (key t tap), a sign or book, the language search, the creative search, the anvil or World Options".into(), ); } } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 7d872a574..6f47fd632 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 e7d2cb95e..bab304569 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -411,7 +411,12 @@ impl Game<'_> { "game_mode": g.game_mode, // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), + // The item the server has this guest using: its slot and ticks. + "using": h.play.get(&g.conn).and_then(|p| p.using()) + .map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "sneaking": g.sneaking, + // The server's Elytra glide (shared flag 7). + "fall_flying": g.fall_flying, "sleeping": g.bed, "health": g.health, // The server's body: its air supply and golden hearts. @@ -1006,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 a2b23c8c6..5c4a43a61 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -30,6 +30,8 @@ use winit::keyboard::KeyCode; /// Per-guest state of the gameplay code that lives outside `Guest`. #[derive(Default)] pub(super) struct GuestPlay { + /// The sign this guest may write on (`SignBlockEntity.playerWhoMayEdit`). + pub(super) sign_editing: Option<[i32; 3]>, mining: Option, destroy_delay: u32, using: Option<(usize, u32)>, @@ -259,6 +261,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; @@ -513,7 +516,8 @@ impl Game<'_> { std::mem::swap(&mut self.mount, &mut play.mount); self.container = container; self.screen = screen; - self.sign_edit = host_sign; + // A sign the guest's placement opened (SignBlock.openTextEdit). + let guest_sign = std::mem::replace(&mut self.sign_edit, host_sign); // A lectern the guest's use opened (LecternBlock.openScreen). let guest_lectern = match std::mem::replace(&mut self.book, host_book) { Some(super::books::BookScreen::View { @@ -652,6 +656,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(edit) = guest_sign { + self.lan_open_sign_editor(host, conn, edit); + } if let Some(key) = guest_lectern { self.lan_open_lectern(host, conn, key); } @@ -865,14 +872,20 @@ impl Game<'_> { self.as_guest(host, conn, |g| g.drop_held(a.action == 4)); } } + // RELEASE_USE_ITEM: ServerPlayer.releaseUsingItem, with the + // hand of the item in use acting. 6 => { self.as_guest(host, conn, |g| { - if let Some((slot, ticks)) = g.using.take() - && g.stack_in(slot) - .is_some_and(|s| &*s.item == "minecraft:bow") - { - g.release_bow(ticks); - } + let Some(hand) = g.used_hand() else { + return; + }; + g.with_hand(hand, |g| { + if let Some((slot, ticks)) = g.using.take() + && let Some(stack) = g.stack_in(slot).cloned() + { + g.release_used_item(&stack, ticks, false); + } + }); }); } // SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops @@ -1029,10 +1042,13 @@ impl Game<'_> { g.open_ridden_mount_menu(); }); } + S::PlayerCommand(p) if p.action == 6 => self.lan_start_gliding(host, conn), S::ContainerButtonClick(p) => { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::SignUpdate(p) => self.lan_sign_update(host, conn, p), + S::EditBook(p) => self.lan_edit_book(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } @@ -1727,6 +1743,9 @@ impl Game<'_> { } .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); let (name, uuid) = (g.name.clone(), g.uuid); + // ServerPlayer.die: dropAllDeathLoot unless a spectator, from the eyes less 0.3. + let drops = (g.game_mode != SPECTATOR) + .then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]); let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); let message = match cause { // ServerPlayer.die: the death message, to everyone unless @@ -1760,6 +1779,9 @@ impl Game<'_> { ); // LivingEntity.die: the death animation, the dying player included. host.hub.entity_event(id, 3, at); + if let Some(eyes) = drops { + self.as_guest(host, conn, |game| game.drop_inventory(eyes)); + } self.spawn_orbs(at, reward); } } @@ -1846,6 +1868,13 @@ impl Game<'_> { /// sounds are heard at the guest. fn guest_server_tick(&mut self, host: &mut LanHost, conn: u32) { self.guest_vehicle_tick(host, conn); + // The last move's fall stands in for the server's delta movement. + let fell = host + .hub + .guest_mut(conn) + .and_then(|g| g.moves.last().map(|m| m.0[1])) + .unwrap_or(0.0); + self.guest_glide_tick(host, conn, fell); let Some(g) = host.hub.guest_mut(conn) else { return; }; @@ -1963,6 +1992,87 @@ impl Game<'_> { } } + /// ServerGamePacketListenerImpl.handlePlayerCommand START_FALL_FLYING: + /// `Player.tryToStartFallFlying`, or else `stopFallFlying` (a second + /// start while gliding ends the glide, as in vanilla). + fn lan_start_gliding(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + let start = !g.fall_flying && self.guest_can_glide(host, conn) == Some(true); + let in_liquid = self + .as_guest(host, conn, |game| { + game.player + .as_ref() + .is_some_and(|p| p.fluids.was_touching_water || p.is_in_lava()) + }) + .unwrap_or(true); + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = start && !in_liquid; + } + } + + /// `Player.canGlide`: not flying, airborne, not riding, no levitation, and + /// a glider that its next point of wear won't break. + fn guest_can_glide(&mut self, host: &mut LanHost, conn: u32) -> Option { + let g = host.hub.guest_mut(conn)?; + if g.flying || g.on_ground || g.vehicle.is_some() { + return Some(false); + } + self.as_guest(host, conn, |game| { + game.glider_worn() && game.potions.effects.get("levitation").is_none() + }) + } + + /// `LivingEntity.updateFallFlying` on the server, once a tick for a + /// gliding guest: the glide ends once `canGlide` fails; otherwise every + /// 20th tick wears the glider by one, and every 10th is an + /// `elytra_glide` game event. Entity.checkFallDistanceAccumulation runs + /// first: a glide that isn't diving keeps the fall distance at 1. + fn guest_glide_tick(&mut self, host: &mut LanHost, conn: u32, fell: f64) { + let Some(g) = host.hub.guest_mut(conn) else { + return; + }; + if !g.fall_flying { + if let Some(m) = g.motion.as_mut() { + m.fall_fly_ticks = 0; + } + return; + } + let creative = g.creative(); + if let Some(m) = g.motion.as_mut() + && fell > -0.5 + && m.fall_distance > 1.0 + { + m.fall_distance = 1.0; + } + if self.guest_can_glide(host, conn) != Some(true) { + if let Some(g) = host.hub.guest_mut(conn) { + g.fall_flying = false; + } + return; + } + self.as_guest(host, conn, |game| { + let Some(p) = game.player.as_mut() else { + return; + }; + p.fall_fly_ticks += 1; + let next = p.fall_fly_ticks + 1; + let at = [p.position.x, p.position.y, p.position.z]; + if next % 10 != 0 { + return; + } + if (next / 10) % 2 == 0 + && !creative + && let Some(elytra) = game.armor[1].as_mut() + { + elytra.damage += 1; + } + let ctx = game.player_context(None); + game.post_game_event("minecraft:elytra_glide", at, ctx); + }); + } + /// `Player.isInWall`: a suffocating block in the 0.48-wide box at the /// eyes. Suffocating is a full collision box that is also a full render /// cube (`BlockBehaviour.isSuffocating`'s default; glass and the like 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/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 25921f936..2efcfc705 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -588,17 +588,7 @@ impl Game<'_> { let [x, y, z] = gs.pos; let name = &self.res.facts().get(self.world.block(x, y, z)).name; let block = StationKind::from_block(name) == Some(gs.kind); - let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; - // The block interaction range (4.5, creative 5) and the buffer. - let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; - let near = (0..3) - .map(|k| { - let lo = f64::from(gs.pos[k]); - (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) - }) - .sum::() - < reach * reach; - if !(block && near) { + if !(block && within_reach(g, gs.pos)) { let window = gs.window; self.lan_station_closed(host, conn, Some(window)); host.hub.send_to( @@ -670,3 +660,18 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec { .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) .unwrap_or_default() } + +/// `Player.isWithinBlockInteractionRange(pos, 4)`: the guest's eyes within +/// its block interaction range (4.5, creative 5) and a 4-block buffer of the +/// block's box. +pub(super) fn within_reach(g: &horizon_client::lan::guest::Guest, pos: [i32; 3]) -> bool { + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach +} diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d7418975c..03727acd3 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -641,6 +641,22 @@ impl Game<'_> { ("mob_factor", Tag::Float(v[5].to_bits())), ]), Component::Profile(p) => profile_tag(p), + // ItemStackTemplate.CODEC: id, count and components. + Component::Stacks(stacks) => Tag::List( + stacks + .iter() + .map(|t| { + let mut entries = vec![ + ("id", Tag::String(self.item_name(t.item).as_ref().into())), + ("count", Tag::Int(t.count)), + ]; + if let Some(c) = self.protocol_components(t) { + entries.push(("components", c)); + } + Tag::compound(entries) + }) + .collect(), + ), Component::CustomModelData { floats, flags, @@ -2557,6 +2573,8 @@ impl Game<'_> { self.drop_remote_chunks_out_of_range(); } C::BlockEntityData(p) => self.remote_block_entity_data(p.pos, p.kind, &p.tag), + C::OpenSignEditor(p) => self.remote_open_sign_editor(p), + C::OpenBook(p) => self.remote_open_book(p.hand), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; @@ -3129,6 +3147,12 @@ impl Game<'_> { .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); player.fluids.fast_lava = self.dim == Dim::Nether; + let glider = self.glider_worn(); + let Some(player) = self.player.as_mut() else { + return Ok(()); + }; + player.glider = glider; + let was_gliding = player.fall_flying; let dead = self.screen == Screen::Dead; // LivingEntity.isImmobile: a sleeper lies still in the bed. if let Some(head) = self.sleeping { @@ -3153,6 +3177,9 @@ impl Game<'_> { // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. let flying = player.flying; + // LocalPlayer.aiStep: a glide this client started is sent to the + // server (ServerboundPlayerCommandPacket START_FALL_FLYING). + let started_gliding = player.fall_flying && !was_gliding; let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; @@ -3192,6 +3219,14 @@ impl Game<'_> { flags: if flying { 2 } else { 0 }, })); } + if started_gliding { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 6, + data: 0, + })); + } self.remote_send_state(input); Ok(()) } @@ -4010,21 +4045,60 @@ impl Game<'_> { return false; }; // MultiPlayerGameMode.useItem runs the use here too: food starts - // being eaten (Consumable.startConsuming). + // being eaten (Consumable.startConsuming), a book and quill opens. self.with_hand(hand, |g| g.start_eating(&info)); - // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting - // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. - if &*held.item == "minecraft:bow" { - self.with_hand(hand, |g| { - if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) - { - g.using = Some((g.held_slot(), 0)); - } - }); + if self.with_hand(hand, |g| g.remote_use_book(&held)) { + return true; } + self.with_hand(hand, |g| g.remote_start_held_use(&held)); item_has_use(&info) } + /// `Item.use` runs on the client too (MultiPlayerGameMode.useItem): an + /// item held in use until the button lets go starts being used here, so + /// that letting go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and + /// the server ends the use: a bow or a trident is let go, a crossbow's + /// charge ends, a shield is lowered, a spyglass stops scoping. Their + /// sounds, loaded arrows and thrown tridents come from the server. + fn remote_start_held_use(&mut self, held: &ItemStack) { + if self.using.is_some() { + return; + } + let start = match &*held.item { + // BowItem.use: with an arrow, or in creative. + "minecraft:bow" => self.creative || self.projectile_slot("minecraft:bow").is_some(), + // CrossbowItem.use: charging when not charged and with ammunition; + // a charged one shoots on the server. + "minecraft:crossbow" => { + held.data().is_none_or(|d| d.charged.is_empty()) + && (self.creative || self.projectile_slot("minecraft:crossbow").is_some()) + } + // TridentItem.use: not about to break, Riptide only in water or rain. + "minecraft:trident" => { + self.use_trident(held); + return; + } + // SpyglassItem.use (its sound is the server's). + "minecraft:spyglass" => true, + // ShieldItem.use: anything that blocks attacks, off cooldown. + _ => { + self.raise_shield(self.held_slot()); + return; + } + }; + if start { + self.using = Some((self.held_slot(), 0)); + } + } + /// Whether `stack` stays in use until the button lets go (bows, + /// crossbows, tridents, spyglasses, shields): its use only counts ticks here. + fn held_until_released(&self, stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" + ) || self.blocks_attacks(stack).is_some() + } + /// The rest of Minecraft.startUseItem once the main hand's target passed: /// the main hand's item, then the off hand's turn (its block, its item). /// The server does each packet's part with that packet's hand only. @@ -4043,7 +4117,8 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// `LivingEntity.updatingUsingItem` on a server client: an item held in + /// use (`held_until_released`), and a /// consumable's eating animation and its crumbs. The server eats it and /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { @@ -4051,8 +4126,9 @@ impl Game<'_> { return; }; let stack = self.stack_in(slot).cloned(); - // A drawn bow: held until the button lets go (or another slot is picked). - if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + // A drawn bow, a charging crossbow, a raised shield...: held until + // the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) .then_some((slot, ticks + 1)); return; diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c679bad69..5a26e3e69 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -1,12 +1,13 @@ //! The sign editing screen (`SignEditScreen` / `HangingSignEditScreen`): //! opened when a sign is placed, four lines limited to the sign's line //! width, Up/Down/Enter move between lines, Escape or Done closes. -use super::Game; +use super::{Game, lan::LanHost}; use horizon_client::{ containers::BlockEntity, hud::{HudBatch, rgba}, signs::wood_type, }; +use horizon_protocol::packets::play::{self, Clientbound as C, Serverbound as S}; use std::time::Instant; use winit::{ event::{ElementState, KeyEvent}, @@ -33,14 +34,95 @@ impl Game<'_> { self.right = false; self.capture(false); } + /// `AbstractSignEditScreen.removed`: a server's client sends what it + /// wrote (ServerboundSignUpdatePacket); the window's own world keeps it + /// and sends it to its guests (`sendBlockUpdated`). pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { - self.world - .modified - .insert((edit.pos.0 >> 4, edit.pos.2 >> 4)); + if self.remote.is_some() { + if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { + let side = if edit.front { &sign.front } else { &sign.back }; + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines: side.lines.clone(), + front: edit.front, + })); + } + } else { + self.mark_block_entity_updated(edit.pos); + } } self.capture(true); } + /// `ServerPlayer.openTextEdit` for the guest whose action opened a sign: + /// the block, then the editor, on its client, and the guest may write on it. + pub(super) fn lan_open_sign_editor(&mut self, host: &mut LanHost, conn: u32, edit: SignEditor) { + let pos = [edit.pos.0, edit.pos.1, edit.pos.2]; + let state = self.world.block(pos[0], pos[1], pos[2]).0 as i32; + host.hub + .send_to(conn, &C::BlockUpdate(play::BlockUpdate { pos, state })); + host.hub.send_to( + conn, + &C::OpenSignEditor(play::OpenSignEditor { + pos, + front: edit.front, + }), + ); + host.play.entry(conn).or_default().sign_editing = Some(pos); + } + /// `ServerGamePacketListenerImpl.handleSignUpdate`: the lines, formatting + /// codes stripped, go on the sign the guest may write on unless it is + /// waxed (`SignBlockEntity.updateSignText`); a guest gone out of reach + /// may no longer write (`playerIsTooFarAwayToEdit`). + pub(super) fn lan_sign_update(&mut self, host: &mut LanHost, conn: u32, p: play::SignUpdate) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let near = super::lan_stations::within_reach(g, p.pos); + let Some(play) = host.play.get_mut(&conn) else { + return; + }; + if !near { + play.sign_editing = None; + } + if play.sign_editing != Some(p.pos) { + log::warn!("{} just tried to change non-editable sign", g.name); + return; + } + let key = (p.pos[0], p.pos[1], p.pos[2]); + let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&key) else { + return; + }; + if sign.waxed { + return; + } + let side = if p.front { + &mut sign.front + } else { + &mut sign.back + }; + for (line, new) in side.lines.iter_mut().zip(&p.lines) { + *line = horizon_client::clipboard::strip_formatting(new); + } + play.sign_editing = None; + self.mark_block_entity_updated(key); + } + /// `ClientPacketListener.handleOpenSignEditor`: the editor on a sign this + /// client has. + pub(super) fn remote_open_sign_editor(&mut self, p: play::OpenSignEditor) { + let key = (p.pos[0], p.pos[1], p.pos[2]); + if matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Sign(_)) + ) { + self.open_sign_editor(key, p.front); + } else { + log::warn!( + "ignoring openTextEdit on a block that is no sign at {:?}", + p.pos + ); + } + } pub(super) fn sign_edit_key(&mut self, event: &KeyEvent) { if event.state != ElementState::Pressed { return; diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index ecbbad0b8..7530b4278 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,7 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", - "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", + "book [next|back|take|sign|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", 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/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 84e768879..7d1b10eaa 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -432,6 +432,13 @@ pub fn stack_to_network( item_id: impl Fn(&str) -> i32, enchantment_id: impl Fn(&str) -> Option, s: &Option, +) -> Option { + network_stack(&item_id, &enchantment_id, s) +} +fn network_stack( + item_id: &dyn Fn(&str) -> i32, + enchantment_id: &dyn Fn(&str) -> Option, + s: &Option, ) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(item_id(&s.item), s.count as i32); @@ -488,6 +495,18 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(i32::from(mode)), )); } + // A loaded crossbow's ammunition. + if !d.charged.is_empty() { + let charged = d + .charged + .iter() + .filter_map(|c| network_stack(item_id, enchantment_id, &Some(c.clone()))) + .collect(); + stack.added.push(( + horizon_protocol::item::component::CHARGED_PROJECTILES, + horizon_protocol::item::Component::Stacks(charged), + )); + } // The books a lectern shows and a guest reads. if !d.writable_pages.is_empty() { stack.added.push(( diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 640d6616c..406f2f872 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1981,14 +1981,15 @@ impl Hub { self.guests[i].sneaking = p.flags & 32 != 0; self.guests[i].sprinting = p.flags & 64 != 0 && p.flags & 1 != 0; } - // OPEN_INVENTORY is the game's: the ridden mount's inventory. - S::PlayerCommand(p) if p.action == 5 => { + // OPEN_INVENTORY (the ridden mount's inventory) and + // START_FALL_FLYING (checked against the guest's chest slot + // and effects) are the game's. + S::PlayerCommand(p) if matches!(p.action, 5 | 6) => { events.push(HostEvent::Packet(conn, Box::new(S::PlayerCommand(p)))); } S::PlayerCommand(p) => match p.action { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, - 6 => self.guests[i].fall_flying = true, // STOP_SLEEPING. 0 => self.wake(i), _ => {} diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 76f622d9c..a61ea2a11 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -2277,7 +2277,7 @@ mod sensor_scan_tests { use horizon_core::geometry::Vec3; use serde_json::json; - fn kind() -> Arc { + pub(super) fn kind() -> Arc { Arc::new(MobType { id: "minecraft:cow".into(), species: Species::Cow, @@ -2481,56 +2481,9 @@ mod sensor_scan_tests { } #[cfg(test)] mod push_tests { + use super::sensor_scan_tests::kind; use super::*; use horizon_core::geometry::Vec3; - use serde_json::json; - - fn kind() -> Arc { - Arc::new(MobType { - id: "minecraft:cow".into(), - species: Species::Cow, - width: 0.9, - height: 1.4, - eye_height: 1.3, - category: "creature".into(), - max_health: 10.0, - speed: 0.2, - flying_speed: 0.4, - attack_damage: 0.0, - attack_knockback: 0.0, - follow_range: 16.0, - step_height: 0.6, - armor: 0.0, - armor_toughness: 0.0, - knockback_resistance: 0.0, - jump_strength: 0.42, - attributes: Arc::default(), - gravity: 0.08, - safe_fall_distance: 3.0, - fall_damage_multiplier: 1.0, - water_efficiency: 0.0, - water_slowdown: 0.8, - air_speed: 0.02, - baby_scale: 0.5, - head_rot_speed: 10.0, - max_head_x_rot: 40.0, - max_head_y_rot: 75.0, - ambient_interval: 120, - flags: Flags { - animal: true, - ..Default::default() - }, - model: Arc::new(Part::parse("root", &json!({}))), - layers: HashMap::new(), - texture: String::new(), - brain: Brain::Passive, - anim: Anim::Rabbit, - sounds: [""; 3], - step_sound: None, - food: Arc::default(), - tempt: Arc::default(), - }) - } /// The pending pushes as one list, scanned for each mob, as before. fn take_old(events: &mut Vec, from: usize, pending: &mut Vec<(u32, Vec3)>) { diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index 331870b4a..bd0eb9c90 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -9,7 +9,12 @@ //! own random drives positions, sounds and jumps. `RunOne` shuffles with a //! random of its own, seeded with the brain's `shuffle_seed` when it is //! built. -use super::{Mob, MobEvent, MobWorld, Species, Who, path::Path, sniffer}; +use super::{ + Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, + path::Path, + sniffer, +}; use horizon_core::{ geometry::Vec3, random::{LegacyRandom, RandomSource}, @@ -603,22 +608,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -794,37 +784,6 @@ fn followable_friendly(s: Species) -> bool { // ---- Behaviours ------------------------------------------------------------ -/// `Behavior`'s running state and end time. -#[derive(Clone, Copy, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } - fn timed_out(&self, now: i64) -> bool { - now > self.end - } -} - /// `RunOne`: shuffles its children by weight and starts the first that can. #[derive(Clone, Debug)] struct Gate { @@ -1076,7 +1035,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).walk_target.clear(); mem(m).look_target.clear(); m.add_effect("minecraft:regeneration", 200, 0); @@ -1086,7 +1045,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AnimalPanic { t, .. } => { @@ -1094,7 +1053,7 @@ impl B { if !(mm.hurt_by.get() == Some(&true) || mm.is_panicking.present()) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1123,7 +1082,7 @@ impl B { let reached = reached(m, cx.w, &walk); if !reached && compute_path(m, cx, &walk, path, speed) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); return true; @@ -1139,21 +1098,21 @@ impl B { if !mem(m).temptation_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownGaze(t) => { if !mem(m).gaze_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::CountDownTransport(t) => { if !mem(m).transport_items_cooldown_ticks.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::Transport(x) => x.try_start(m, cx), @@ -1171,7 +1130,7 @@ impl B { let Some(partner) = breed_partner(m, cx.w) else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1200,7 +1159,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if brain_mut(m).kind == Kind::Sniffer { reset_sniffing(m, cx); } @@ -1210,14 +1169,14 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::FeelingHappy(t) => { if !mem(m).sniffer_happy.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::FEELING_HAPPY); true } @@ -1233,7 +1192,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::DIGGING); true } @@ -1246,7 +1205,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::RISING); true } @@ -1261,7 +1220,7 @@ impl B { if !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SEARCHING); true } @@ -1278,7 +1237,7 @@ impl B { if is_tempted(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SCENTING); true } @@ -1293,12 +1252,12 @@ impl B { if m.is_baby() || !can_sniff(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); transition(m, cx, sniffer::SNIFFING); true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::AxolotlAction { .. } diff --git a/crates/horizon-client/src/mobs/brain.rs b/crates/horizon-client/src/mobs/brain.rs index da83ee93d..67bb6a2a6 100644 --- a/crates/horizon-client/src/mobs/brain.rs +++ b/crates/horizon-client/src/mobs/brain.rs @@ -1,8 +1,11 @@ //! Pieces of vanilla's `Brain` that species implemented as brains share: //! memories that expire, behaviour durations, walk targets and //! `MoveToTargetSink`. -use super::{Mob, goals::Cx}; -use horizon_core::random::RandomSource; +use super::{Mob, MobWorld, Who, goals::Cx}; +use horizon_core::{ + geometry::Vec3, + random::{LegacyRandom, RandomSource}, +}; /// A memory with an expiry (`Brain.setMemoryWithExpiry`): present for the /// tick it was set and `ttl` more ticks. `Ttl::default()` is absent. @@ -25,6 +28,57 @@ impl Ttl { } } } +/// `Behavior`'s bookkeeping in the brains ported behaviour for behaviour +/// (villager, animal, monster, warden): running, and until when. +#[derive(Clone, Copy, Debug)] +pub struct Timed { + pub running: bool, + pub end: i64, + pub min: i32, + pub max: i32, +} +impl Timed { + pub fn new(min: i32, max: i32) -> Self { + Self { + running: false, + end: 0, + min, + max, + } + } + /// `Behavior.tryStart`'s duration draw from the level random, in Java's + /// int arithmetic (made even when it cannot vary). + pub fn begin(&mut self, lr: &mut LegacyRandom, now: i64) { + self.running = true; + let bound = self.max.wrapping_add(1).wrapping_sub(self.min); + let d = self.min.wrapping_add(lr.next_int_bound(bound).unwrap_or(0)); + self.end = now + i64::from(d); + } + /// `Behavior.timedOut`. + pub fn timed_out(&self, now: i64) -> bool { + now > self.end + } +} +/// `NearestLivingEntitySensor`'s scan: the living entities (the player +/// among them) whose boxes meet the follow range around `m`, nearest first. +pub fn living_near(m: &Mob, w: &MobWorld) -> Vec { + let r = m.attrs.follow_range; + let area = m.bounds().inflate(Vec3::new(r, r, r)); + let mut found: Vec<(Who, f64)> = Vec::new(); + for o in w.others_near(area) { + if o.id != m.id && o.alive && o.bounds.intersects(area) { + found.push((Who::Mob(o.id), m.distance_sqr(o.position))); + } + } + if let Some(p) = &w.player + && p.alive + && p.bounds.intersects(area) + { + found.push((Who::Player, m.distance_sqr(p.position))); + } + found.sort_by(|a, b| a.1.total_cmp(&b.1)); + found.into_iter().map(|(w, _)| w).collect() +} /// A random duration in `min..=max` (`Behavior`'s end time). pub fn duration(m: &mut Mob, min: i32, max: i32) -> i32 { if max <= min { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 1099e0bc3..bc1d6ed10 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -11,9 +11,10 @@ //! seeded when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, goals::Cx, path::Path, - villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget}, + villager_brain::{NEVER, Slot, Tracker, Visible, WalkTarget, compute_path, reached}, }; use crate::projectiles::{Projectile, ProjectileKind}; use horizon_core::{ @@ -129,6 +130,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> &Memories { &brain(m).expect("brain").mem } @@ -292,22 +297,7 @@ fn tick_sensors(m: &mut Mob, w: &MobWorld) { /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -456,31 +446,6 @@ fn sense_breeze_attack(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw from the level random. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `StartAttacking`'s target finders. #[derive(Clone, Copy, Debug)] enum Finder { @@ -607,14 +572,14 @@ impl B { if *creaking && !super::creaking::can_move(m) || !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -636,9 +601,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -719,7 +684,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::RandomStroll(running, speed) => { @@ -848,7 +813,7 @@ impl B { mem(m).breeze_shoot.clear(); return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start super::breeze::set_pose(m, super::breeze::SHOOTING); mem(m).breeze_shoot_charging.set_ttl((), 15); @@ -867,7 +832,7 @@ impl B { if !long_jump_can_run(m, cx) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if !mem(m).breeze_jump_inhaling.present() { mem(m).breeze_jump_inhaling.set_ttl((), 10); @@ -905,7 +870,7 @@ impl B { if !stuck { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); mem(m).breeze_shoot.set_ttl((), 60); true } @@ -924,7 +889,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); slide_start(m, cx); true } @@ -989,7 +954,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1122,53 +1087,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target.block(w).is_some_and(|p| { - let h = block_of(m.position); - (p[0] - h[0]).abs() + (p[1] - h[1]).abs() + (p[2] - h[2]).abs() <= walk.close - }) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - *path = m.create_path_to(cx.w, block_of(Vec3::new(step[0], step[1], step[2])), 0); - return path.is_some(); - } - } - false -} /// `BehaviorUtils.isWithinAttackRange(body, target, 1)` for a mob without a /// ranged weapon: `Mob.isWithinMeleeAttackRange`. fn within_attack_range(m: &Mob, w: &MobWorld, target: Who) -> bool { diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 194bd75ff..df19d8fed 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -11,6 +11,7 @@ //! `Brain::shuffle_seed` when the brain is built. use super::{ Mob, MobEvent, MobWorld, Species, Who, + brain::{Timed, living_near}, path::{Path, PathNode}, }; use horizon_core::{ @@ -341,6 +342,10 @@ fn brain_mut(m: &mut Mob) -> &mut Brain { fn mem(m: &mut Mob) -> &mut Memories { &mut brain_mut(m).mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -565,22 +570,7 @@ const FOLLOW_RANGE: f64 = 16.0; /// `NearestLivingEntitySensor`: everything alive within the follow range, /// nearest first. fn sense_living(m: &mut Mob, w: &MobWorld) { - let r = m.attrs.follow_range; - let area = m.bounds().inflate(Vec3::new(r, r, r)); - let mut found: Vec<(Who, f64)> = Vec::new(); - for o in w.others_near(area) { - if o.id != m.id && o.alive && o.bounds.intersects(area) { - found.push((Who::Mob(o.id), m.distance_sqr(o.position))); - } - } - if let Some(p) = &w.player - && p.alive - && p.bounds.intersects(area) - { - found.push((Who::Player, m.distance_sqr(p.position))); - } - found.sort_by(|a, b| a.1.total_cmp(&b.1)); - let list: Vec = found.into_iter().map(|(w, _)| w).collect(); + let list = living_near(m, w); let mm = mem(m); mm.mobs.set_list(list.clone()); mm.visible_mobs.set(Visible { @@ -791,34 +781,6 @@ fn sense_golem(m: &mut Mob, w: &MobWorld) { // ---- Behaviours --------------------------------------------------------- -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw. - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let bound = self.max.wrapping_add(1).wrapping_sub(self.min); - let d = self - .min - .wrapping_add(cx.lr.next_int_bound(bound).unwrap_or(0)); - self.end = cx.now + i64::from(d); - } -} - /// The POI types villagers use. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Poi { @@ -1498,18 +1460,18 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LookAtTargetSink(t) => { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::PanicTrigger(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); // VillagerPanicTrigger.start if panic_condition(m) { if !brain_mut(m).is_active(Act::Panic) { @@ -1542,9 +1504,9 @@ impl B { } let walk = mm.walk_target.value().unwrap(); let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -1561,7 +1523,7 @@ impl B { if !follow_trading_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); follow_trading_player(m); true } @@ -1573,7 +1535,7 @@ impl B { if !matches!(a, Act::Idle | Act::Work | Act::Play) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::JumpOnBed { @@ -1590,7 +1552,7 @@ impl B { if mm.walk_target.present() || !m.is_baby() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *bed = Some(nearest); *time_left = 100; *jumps = 3 + cx.lr.next_int_bound(4).unwrap_or(0); @@ -1599,7 +1561,7 @@ impl B { true } B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GiveGiftToHero { @@ -1618,7 +1580,7 @@ impl B { *until_next -= 1; return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); *given = false; *started = now; let mm = mem(m); @@ -1630,7 +1592,7 @@ impl B { if !mem(m).interaction_target.present() || !show_trades_condition(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start if let Some(target) = mem(m).interaction_target.value() { mem(m).look_target.set(Tracker::Entity(target, true)); @@ -1646,7 +1608,7 @@ impl B { if !villager_target_valid(m, cx.w, Mem::InteractionTarget) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).interaction_target.value().unwrap(); lock_gaze(m, target, cx); true @@ -1659,7 +1621,7 @@ impl B { if !breeding_possible(m, cx.w) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let target = mem(m).breed_target.value().unwrap(); lock_gaze(m, target, cx); *birth = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0)); @@ -1680,7 +1642,7 @@ impl B { if !closer_to_center(site, m.position, 1.73) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); // start let mm = mem(m); mm.last_worked_at_poi.set(now); @@ -1709,7 +1671,7 @@ impl B { *valid = farmland_around(m, cx.w); *target = pick_farmland(valid, cx); let Some(p) = *target else { return false }; - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { let mm = mem(m); mm.look_target.set(Tracker::Block(p)); @@ -2288,7 +2250,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if now > *next_ok { if super::villager::start_sleeping(m, home, w) { mem(m).last_slept.set(now); @@ -2609,7 +2571,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::LocateHidingPlace { @@ -2769,7 +2731,7 @@ impl B { && let Some(now_target) = walk.target.block(cx.w) { let d = manhattan_sq(now_target, last); - if d > 4 && compute_path(m, cx, &walk, path, speed) { + if d > 4 && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -3141,33 +3103,37 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { } } /// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { +pub(super) fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { walk.target .block(w) .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) } -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( +/// `MoveToTargetSink.tryComputePath`, for the brains on these memories +/// (villager, monster, warden): `cant_reach` is the brain's +/// `CANT_REACH_WALK_TARGET_SINCE`. +pub(super) fn compute_path( m: &mut Mob, - cx: &mut Bx, + w: &MobWorld, + now: i64, walk: &WalkTarget, path: &mut Option, speed: &mut f32, + cant_reach: fn(&mut Mob) -> &mut Slot, ) -> bool { - let Some(target) = walk.target.block(cx.w) else { + let Some(target) = walk.target.block(w) else { return false; }; - *path = m.create_path_to(cx.w, target, 0); + *path = m.create_path_to(w, target, 0); *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); + if reached(m, w, walk) { + cant_reach(m).clear(); } else { let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); + let since = cant_reach(m); if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); + since.clear(); + } else if !since.present() { + since.set(now); } if path.is_some() { return true; @@ -3178,14 +3144,14 @@ fn compute_path( f64::from(target[2]) + 0.5, ]; if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) + m.default_random_pos_towards(w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) { let p = [ step[0].floor() as i32, step[1].floor() as i32, step[2].floor() as i32, ]; - *path = m.create_path_to(cx.w, p, 0); + *path = m.create_path_to(w, p, 0); return path.is_some(); } } diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 518347e77..8caafefc9 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -14,9 +14,10 @@ //! shuffle seed. use super::{ Mob, MobEvent, MobWorld, Who, + brain::Timed, goals::Cx, path::Path, - villager_brain::{Slot, Tracker, Visible, WalkTarget}, + villager_brain::{Slot, Tracker, Visible, WalkTarget, compute_path, reached}, warden::{self, Pose}, }; use horizon_core::{ @@ -145,31 +146,6 @@ impl Memories { } } -/// `Behavior`'s bookkeeping: running, and until when. -#[derive(Clone, Debug)] -struct Timed { - running: bool, - end: i64, - min: i32, - max: i32, -} -impl Timed { - fn new(min: i32, max: i32) -> Self { - Self { - running: false, - end: 0, - min, - max, - } - } - /// `Behavior.tryStart`'s duration draw (made even when it cannot vary). - fn begin(&mut self, cx: &mut Bx) { - self.running = true; - let d = self.min + cx.lr.next_int_bound(self.max + 1 - self.min).unwrap_or(0); - self.end = cx.now + i64::from(d); - } -} - /// `RunOne`'s `ShufflingList` over a stroll (weight 2) and `DoNothing` (1). #[derive(Clone, Debug)] struct Gate { @@ -383,6 +359,10 @@ fn brain(m: &Mob) -> Option<&Brain> { pub(super) fn mem(m: &mut Mob) -> &mut Memories { &mut m.extra.warden.as_mut().expect("a warden").brain.mem } +/// `CANT_REACH_WALK_TARGET_SINCE`, for `compute_path`. +fn cant_reach(m: &mut Mob) -> &mut Slot { + &mut mem(m).cant_reach_walk_target_since +} pub(super) fn mem_ref(m: &Mob) -> Option<&Memories> { brain(m).map(|b| &b.mem) } @@ -558,9 +538,6 @@ fn find_closest(m: &mut Mob, w: &MobWorld, filter: impl Fn(&Mob, Who) -> bool) - fn block_of(p: Vec3) -> [i32; 3] { [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32] } -fn manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { - (a[0] - b[0]).abs() + (a[1] - b[1]).abs() + (a[2] - b[2]).abs() -} fn dist_sqr(a: [i32; 3], b: [i32; 3]) -> i64 { (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum() } @@ -607,57 +584,6 @@ fn tracker_visible(m: &mut Mob, w: &MobWorld, t: Tracker) -> bool { _ => true, } } -/// `MoveToTargetSink.reachedTarget`. -fn reached(m: &Mob, w: &MobWorld, walk: &WalkTarget) -> bool { - walk.target - .block(w) - .is_some_and(|p| manhattan(p, block_of(m.position)) <= walk.close) -} -/// `MoveToTargetSink.tryComputePath`. -fn compute_path( - m: &mut Mob, - cx: &mut Bx, - walk: &WalkTarget, - path: &mut Option, - speed: &mut f32, -) -> bool { - let Some(target) = walk.target.block(cx.w) else { - return false; - }; - *path = m.create_path_to(cx.w, target, 0); - *speed = walk.speed; - if reached(m, cx.w, walk) { - mem(m).cant_reach_walk_target_since.clear(); - } else { - let can_reach = path.as_ref().is_some_and(|p| p.reached); - let mm = mem(m); - if can_reach { - mm.cant_reach_walk_target_since.clear(); - } else if !mm.cant_reach_walk_target_since.present() { - mm.cant_reach_walk_target_since.set(cx.now); - } - if path.is_some() { - return true; - } - let to = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]), - f64::from(target[2]) + 0.5, - ]; - if let Some(step) = - m.default_random_pos_towards(cx.w, 10, 7, to, f64::from(std::f32::consts::FRAC_PI_2)) - { - let p = [ - step[0].floor() as i32, - step[1].floor() as i32, - step[2].floor() as i32, - ]; - *path = m.create_path_to(cx.w, p, 0); - return path.is_some(); - } - } - false -} fn same_path(a: Option<&Path>, b: Option<&Path>) -> bool { match (a, b) { (None, None) => true, @@ -710,7 +636,7 @@ impl B { if !swim_condition(m) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::SetWardenLookTarget(r) => one(r, || { @@ -732,7 +658,7 @@ impl B { if !mem(m).look_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::MoveToTargetSink { @@ -755,9 +681,9 @@ impl B { return false; }; let reached = reached(m, cx.w, &walk); - if !reached && compute_path(m, cx, &walk, path, speed) { + if !reached && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = walk.target.block(cx.w); - t.begin(cx); + t.begin(cx.lr, cx.now); // start mem(m).path.set_opt(path.clone()); m.nav_move_to_path(path.clone(), f64::from(*speed)); @@ -775,7 +701,7 @@ impl B { if !mm.is_emerging.present() || mm.walk_target.present() { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); warden::set_pose(m, Pose::Emerging); sound(m, "entity.warden.emerge", 5.0, 1.0, cx.events); true @@ -791,7 +717,7 @@ impl B { if !(m.on_ground || liquid) { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); if m.on_ground { warden::set_pose(m, Pose::Digging); sound(m, "entity.warden.dig", 5.0, 1.0, cx.events); @@ -872,7 +798,7 @@ impl B { true }), B::DoNothing(t) => { - t.begin(cx); + t.begin(cx.lr, cx.now); true } B::GoToDisturbance(r) => one(r, || { @@ -907,7 +833,7 @@ impl B { { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); sound(m, "entity.warden.sniff", 5.0, 1.0, cx.events); true } @@ -919,7 +845,7 @@ impl B { let Some(target) = mm.roar_target.value() else { return false; }; - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.roar_sound_delay.set_ttl((), ROAR_SOUND_DELAY); mm.walk_target.clear(); @@ -1004,7 +930,7 @@ impl B { if !close { return false; } - t.begin(cx); + t.begin(cx.lr, cx.now); let mm = mem(m); mm.attack_cooling_down .set_ttl(true, i64::from(SONIC_DURATION)); @@ -1092,7 +1018,7 @@ impl B { && let Some(walk) = mem(m).walk_target.value() && let Some(now_target) = walk.target.block(cx.w) && dist_sqr(now_target, last) > 4 - && compute_path(m, cx, &walk, path, speed) + && compute_path(m, cx.w, cx.now, &walk, path, speed, cant_reach) { *last_target = Some(now_target); mem(m).path.set_opt(path.clone()); 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/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 6f59228b5..650fa4baa 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -32,6 +32,7 @@ pub mod component { pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; + pub const CHARGED_PROJECTILES: i32 = 51; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; } @@ -75,6 +76,8 @@ pub enum Component { /// `WritableBookContent`: the pages (raw text). WritableBook(Vec), WrittenBook(WrittenBook), + /// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates. + Stacks(Vec), } /// `Filterable.streamCodec`: the raw value, then an optional filtered one @@ -125,6 +128,10 @@ impl Component { resolved: r.bool()?, }) } + CHARGED_PROJECTILES => { + let n = r.count(1024)?; + Self::Stacks((0..n).map(|_| Template::read(r)).collect::>()?) + } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), @@ -283,6 +290,10 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::Stacks(stacks) => { + w.varint(stacks.len() as i32); + stacks.iter().for_each(|s| Template::write(s, w)); + } Self::WritableBook(pages) => { w.varint(pages.len() as i32); for page in pages { @@ -533,6 +544,21 @@ mod tests { round::, HashedSlot>(None); } + #[test] + fn charged_projectiles_are_item_stack_templates() { + // A crossbow (id 7) loaded with one arrow (id 9): ChargedProjectiles + // is a list of ItemStackTemplate, the item before the count. + let bytes = [1, 7, 1, 0, 51, 1, 9, 1, 0, 0]; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::CHARGED_PROJECTILES), + Some(&Component::Stacks(vec![Stack::new(9, 1)])) + ); + let mut w = Writer::new(); + Slot::write(&Some(stack), &mut w); + assert_eq!(w.data, bytes); + } + #[test] fn filtered_book_pages_are_read_and_dropped() { // A writable book with one page "hi" and its filtered "**". diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index be3c4eb07..206ed9aff 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -461,6 +461,15 @@ packet!(OpenScreen { container: i32 => VarInt, menu: i32 => VarInt, title: Tag = // ClientboundMountScreenOpenPacket: a horse's or llama's inventory, with its // chest's columns (`getInventoryColumns`). packet!(MountScreenOpen { container: i32 => VarInt, columns: i32 => VarInt, entity: i32 => Int }); +packet!( + /// ClientboundOpenSignEditorPacket: the sign whose side the player edits. + OpenSignEditor { pos: [i32; 3] => Pos, front: bool => SignSide } +); +packet!( + /// ClientboundOpenBookPacket: the hand (InteractionHand, 0 main, 1 off) + /// whose written book the player reads. + OpenBook { hand: i32 => VarInt } +); packet!(PlayerAbilities { flags: i8 => Byte, flying_speed: f32 => Float, walking_speed: f32 => Float }); /// MessageSignature.Packed: an index into the last-seen cache or a full signature. pub struct PackedSignature; @@ -1617,6 +1626,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenBook(OpenBook) = OPEN_BOOK, + OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, @@ -1917,6 +1928,61 @@ packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } ); +packet!( + /// ServerboundSignUpdatePacket: the four lines the player wrote on a side. + SignUpdate { pos: [i32; 3] => Pos, lines: [String; 4] => SignLines, front: bool => SignSide } +); +packet!( + /// ServerboundEditBookPacket: the book's slot (a hotbar slot, or 40 for + /// the off hand), its pages and, to sign it, its title. + EditBook { + slot: i32 => VarInt, + pages: Vec => BookPages, + title: Option => Opt>, + } +); +/// `stringUtf8(1024)` in `list(100)`: a book's pages. +pub struct BookPages; +impl Codec> for BookPages { + fn read(r: &mut Reader) -> Result> { + let n = r.varint()?; + if !(0..=100).contains(&n) { + return Err(Error::new(format!("{n} book pages, at most 100"))); + } + (0..n).map(|_| r.string(1024)).collect() + } + fn write(v: &Vec, w: &mut Writer) { + List::>::write(v, w); + } +} +/// SignTextSlot.STREAM_CODEC: VarInt 0 for the back, 1 for the front (any +/// other id reads as the back, ByIdMap's ZERO strategy). +pub struct SignSide; +impl Codec for SignSide { + fn read(r: &mut Reader) -> Result { + Ok(r.varint()? == 1) + } + fn write(v: &bool, w: &mut Writer) { + w.varint(i32::from(*v)); + } +} +/// `stringUtf8(384)` in `fixedSizeList(4)`: four lines, no count. +pub struct SignLines; +impl Codec<[String; 4]> for SignLines { + fn read(r: &mut Reader) -> Result<[String; 4]> { + Ok([ + r.string(384)?, + r.string(384)?, + r.string(384)?, + r.string(384)?, + ]) + } + fn write(v: &[String; 4], w: &mut Writer) { + for line in v { + w.string(line); + } + } +} packet!( /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an /// optional `mob_effect` id. @@ -2000,6 +2066,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, + EditBook(EditBook) = EDIT_BOOK, Interact(Interact) = INTERACT, KeepAlive(KeepAlive) = KEEP_ALIVE, MovePlayerPos(MovePlayerPos) = MOVE_PLAYER_POS, @@ -2024,6 +2091,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, + SignUpdate(SignUpdate) = SIGN_UPDATE, UseItem(UseItem) = USE_ITEM, UseItemOn(UseItemOn) = USE_ITEM_ON, }); @@ -2748,4 +2816,48 @@ mod tests { }); round_trip(p, Clientbound::encode, Clientbound::decode); } + + #[test] + fn sign_packets_match_vanilla_stream_codecs() { + // ClientboundOpenSignEditorPacket: BlockPos, then SignTextSlot as a VarInt (FRONT is 1). + let open = Clientbound::OpenSignEditor(OpenSignEditor { + pos: [1, 2, 3], + front: true, + }); + let body = open.encode(); + assert_eq!( + body[1..9], + crate::buf::pack_block_pos([1, 2, 3]).to_be_bytes() + ); + assert_eq!(body[9..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundSignUpdatePacket: BlockPos, four strings with no count, then the slot. + let update = Serverbound::SignUpdate(SignUpdate { + pos: [-4, 70, 9], + lines: ["Hi".into(), String::new(), "x".into(), String::new()], + front: false, + }); + let body = update.encode(); + assert_eq!(body[9..], [2, b'H', b'i', 0, 1, b'x', 0, 0]); + round_trip(update, Serverbound::encode, Serverbound::decode); + } + + #[test] + fn book_packets_match_vanilla_stream_codecs() { + // ClientboundOpenBookPacket: InteractionHand as a VarInt. + let open = Clientbound::OpenBook(OpenBook { hand: 1 }); + assert_eq!(open.encode()[1..], [1]); + round_trip(open, Clientbound::encode, Clientbound::decode); + // ServerboundEditBookPacket: the slot, the pages (a counted list), then an optional title. + let sign = Serverbound::EditBook(EditBook { + slot: 40, + pages: vec!["a".into(), String::new()], + title: Some("T".into()), + }); + assert_eq!(sign.encode()[1..], [40, 2, 1, b'a', 0, 1, 1, b'T']); + round_trip(sign, Serverbound::encode, Serverbound::decode); + let mut w = Writer::new(); + w.varint(101); + assert!(BookPages::read(&mut Reader::new(&w.data)).is_err()); + } } diff --git a/crates/horizon-world/src/datafix/chunk_flatten.rs b/crates/horizon-world/src/datafix/chunk_flatten.rs index e3c116d93..671fc9f73 100644 --- a/crates/horizon-world/src/datafix/chunk_flatten.rs +++ b/crates/horizon-world/src/datafix/chunk_flatten.rs @@ -266,8 +266,8 @@ fn is_virtual(block: usize) -> bool { VIRTUAL.contains(&block) } -/// `getSideMask`. -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { +/// `getSideMask` (LeavesFix has the same copy). +pub(super) fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { let mut s = 0; if north { if east { diff --git a/crates/horizon-world/src/datafix/chunk_leaves.rs b/crates/horizon-world/src/datafix/chunk_leaves.rs index 9cd2fd3d9..07d59cbdf 100644 --- a/crates/horizon-world/src/datafix/chunk_leaves.rs +++ b/crates/horizon-world/src/datafix/chunk_leaves.rs @@ -6,6 +6,7 @@ //! emulated here (`IntOpenHashSet` and the key order of an `Int2ObjectOpenHashMap`). use std::collections::{HashMap, HashSet}; +use super::chunk_flatten::side_mask; use super::dynamic::{as_int, as_long_stream, as_str, ceillog2, set}; use crate::nbt::Tag; @@ -355,32 +356,6 @@ fn get_index(x: i32, y: i32, z: i32) -> i32 { y << 8 | z << 4 | x } -fn side_mask(west: bool, east: bool, north: bool, south: bool) -> i32 { - let mut s = 0; - if north { - if east { - s |= 2; - } else if west { - s |= 128; - } else { - s |= 1; - } - } else if south { - if west { - s |= 32; - } else if east { - s |= 8; - } else { - s |= 16; - } - } else if east { - s |= 4; - } else if west { - s |= 64; - } - s -} - /// `LeavesFix` over a chunk (`{Level: ...}`). pub(super) fn leaves_fix(chunk: &mut Tag) { let Some(level) = chunk.get_mut("Level") else { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 994636066..bb01134c5 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -189,6 +189,27 @@ address. The script then checks, from both sides, what a guest's game used to ge - totem: the host and the guest each take a lethal hit holding a totem of undying in the off hand, then the main hand: the server uses it up and keeps them alive at 1 health with its effects, and each side hears the totem once (entity event 35) (#1292). +- keepinv: the host and the guest each die holding diamonds and wearing a helmet: with keep_inventory + off both drop where they died and the player respawns without them; with it on nothing + drops and the player keeps them (#1284). +- signs: the host and the guest each place an oak sign: the editor opens on their own screen + (ClientboundOpenSignEditorPacket), the two lines they write reach the server + (ServerboundSignUpdatePacket) and both sides show them (#1380). +- books: the host and the guest each write in a book and quill on their own screen, sign it + (ServerboundEditBookPacket), read the written book the server gave them + (ClientboundOpenBookPacket), then drop it: the other side sees its title, author and + page (#1366). +- elytra: the host and the guest, high up with an Elytra on, jump in the air and glide + (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server + have them gliding, they go forward far more than down, and the glide ends on both once + they land (#1288). +- helduse: the host and the guest raise a shield, charge and fire a crossbow, throw a trident + 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). @@ -4517,8 +4538,413 @@ def check_totem(host, guest, out): return seen -CHECKS += ['totem'] -CHECK_FNS.update(totem=check_totem) +def check_keep_inventory(host, guest, out): + """ServerPlayer.die's dropAllDeathLoot for each player (Player.dropEquipment): with keep_inventory + off, the diamonds and the helmet a player dies with lie where it died and it respawns with + neither; with it on, nothing drops and it respawns with both (#1284).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + host('command', command=f'setworldspawn {hx} {hy} {hz}') + host('command', command='gamerule respawn_radius 0') + try: + for keep in ('false', 'true'): + host('command', command=f'gamerule keep_inventory {keep}') + for game, dz in ((host, -3), (guest, 3)): + # 14 blocks from the world spawn: nothing dropped is picked up on respawning. + x, z = hx + 14, hz + dz + host('command', command=f'fill {x - 2} {hy - 1} {z - 1} {x + 2} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 2} {hy} {z - 1} {x + 2} {hy + 2} {z + 1} minecraft:air') + host('command', command='kill @e[type=minecraft:item]') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:diamond 7') + game('command', command='item replace entity @s armor.head with minecraft:iron_helmet') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5}') + game.wait(20) + game('command', command='kill @s') + game.wait(30) + dropped = sorted((e['item']['item'], e['item']['count']) + for e in game.raw('entities', 8, 'minecraft:item')['entities']) + game.shot(out, f'keepinv-{keep}') + respawn_when_ready(game) + game.wait(40) + back_to_game(game) + seen[f'{game.name}-keep-{keep}'] = { + 'dropped': dropped, + 'kept': {item: server_count(game, item) for item in ('diamond', 'iron_helmet')}} + finally: + host('command', command='gamerule keep_inventory false') + host('command', command='gamerule respawn_radius 10') + host('command', command='kill @e[type=minecraft:item]') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for case, s in seen.items(): + want = ({'dropped': [], 'kept': {'diamond': 7, 'iron_helmet': 1}} if case.endswith('true') else + {'dropped': [('minecraft:diamond', 7), ('minecraft:iron_helmet', 1)], + 'kept': {'diamond': 0, 'iron_helmet': 0}}) + assert s == want, f'{case}: {seen}' + return seen + + +def check_signs(host, guest, out): + """SignBlock.openTextEdit on the placing player's client, for the host and the guest: placing + an oak sign opens its editor there and nowhere else, the lines typed into it go to the server + when it closes, and both sides then show them (#1380).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + for game, other, dz in ((host, guest, -2), (guest, host, 2)): + spot = (hx + 2, hy, hz + dz) + game('command', command=f'setblock {spot[0]} {spot[1] - 1} {spot[2]} minecraft:stone') + game('command', command=f'setblock {spot[0]} {spot[1]} {spot[2]} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='give @s minecraft:oak_sign 1') + game.wait(10) + game.raw('place', *spot, '--item', 'minecraft:oak_sign') + game.wait(10) + opened = {g.name: g('state').get('screen') for g in (game, other)} + game.shot(out, 'signs-editor') + lines = [f'{game.name} wrote', 'line two'] + game.raw('type', lines[0]) + game.raw('key', 'enter', 'tap') + game.raw('type', lines[1]) + game.raw('key', 'esc', 'tap') + game.wait(20) + back_to_game(other) + seen[game.name] = {'opened': opened, + 'shown': {g.name: (g.raw('block', *spot).get('sign') or {}).get('front') + for g in (game, other)}} + other.shot(out, 'signs-shown') + for name, s in seen.items(): + other = 'guest' if name == 'host' else 'host' + want = [f'{name} wrote', 'line two', '', ''] + assert s['opened'] == {name: 'sign', other: 'playing'}, f'{name}: {seen}' + assert s['shown'] == {name: want, other: want}, f'{name}: {seen}' + return seen + + +def book_screen(game): + """The open book (`book`'s page and page count), once `game` shows it.""" + game.raw('wait-for', 'screen', 'book', '--timeout', 10) + return game.raw('book') + + +def check_books(host, guest, out): + """Books in hand for the host and the guest: a book and quill opens its editor on the player's + own client (LocalPlayer.openItemGui), what it writes and signs reaches the server + (ServerboundEditBookPacket), and the written book opens on the player's client when the server + says so (ServerPlayer.openItemGui's ClientboundOpenBookPacket); dropped, the other side sees the + server's book (#1366).""" + seen = {} + for game, other in ((host, guest), (guest, host)): + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:writable_book') + x, y, z = pos_of(game) + game.raw('look-at', f'{x + 0.5:.2f}', f'{y + 30:.2f}', f'{z:.2f}') + game.wait(10) + case = seen[game.name] = {} + game.raw('use-item') + case['edit'] = book_screen(game) + case['other_screen'] = other('state').get('screen') + game.raw('type', f'{game.name} page one') + game.shot(out, 'books-edit') + game.raw('book', 'sign') + game.raw('type', f'{game.name} book') + game.raw('book', 'sign') + game.wait(20) + case['signed'] = {item: server_count(game, item) for item in ('writable_book', 'written_book')} + game.raw('use-item') + case['view'] = book_screen(game) + game.shot(out, 'books-view') + game.raw('book', 'done') + game.wait(5) + game.raw('key', 'q', 'tap') + game.wait(30) + books = [e['item'].get('components', '') for e in other.raw('entities', 16, 'minecraft:item')['entities'] + if e['item']['item'] == 'minecraft:written_book'] + case['dropped'] = [all(f'{game.name} {t}' in c for t in ('page one', 'book')) for c in books] + host('command', command='kill @e[type=minecraft:item]') + for name, case in seen.items(): + assert case['edit'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['other_screen'] == 'playing', f'{name}: {seen}' + assert case['signed'] == {'writable_book': 0, 'written_book': 1}, f'{name}: {seen}' + assert case['view'] == {'page': 0, 'pages': 1, 'lectern': None}, f'{name}: {seen}' + assert case['dropped'] == [True], f'{name}: {seen}' + return seen + + +CHECKS += ['totem', 'keepinv', 'signs', 'books'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs, books=check_books) + + +def check_elytra(host, guest, out): + """LivingEntity.updateFallFlying for each player: a jump while falling with an Elytra on starts a + glide that the server takes too (Player.tryToStartFallFlying), the glide carries the player + forward rather than down, and landing ends it on both sides (canGlide fails on the ground).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dx in ((host, -2), (guest, 2)): + x, z = hx + dx, hz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 1} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 1} {hy + 3} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='effect give @s minecraft:resistance 60 4 true') + game('command', command='item replace entity @s armor.chest with minecraft:elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 60} {z + 0.5} 0 0') + game.wait(6) + start = pos_of(game) + game.raw('key', 'space', 'down') + game.wait(1) + game.raw('key', 'space', 'up') + game.wait(30) + end = pos_of(game) + glide = {'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying'), + 'forward': round(math.hypot(end[0] - start[0], end[2] - start[2]), 1), + 'down': round(start[1] - end[1], 1)} + game.shot(out, 'elytra') + game('command', command=f'tp @s {x + 0.5} {hy + 1} {z + 0.5}') + game.wait(30) + landed = {'on_ground': own(game).get('on_ground'), + 'client': own(game).get('fall_flying'), + 'server': server_player(host, game).get('fall_flying')} + seen[game.name] = {'glide': glide, 'landed': landed} + finally: + for game in (host, guest): + game('command', command='clear @s') + game('command', command='effect clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + g, l = s['glide'], s['landed'] + # Falling alone covers about 25 blocks in those 30 ticks and goes nowhere. + assert g['client'] and g['server'] and g['forward'] > 8 and g['down'] < 20, f'{name} glide: {seen}' + assert l['on_ground'] and not l['client'] and not l['server'], f'{name} landed: {seen}' + return seen + + +CHECKS += ['elytra'] +CHECK_FNS.update(elytra=check_elytra) + + +def server_using(host, game): + """The item the server has the player using ({slot, ticks}), or None.""" + if game is host and not SERVER_THREAD: + return host('state').get('using') + return server_player(host, game).get('using') + + +def flying(game, kind): + """How many of the projectiles this side draws are of `kind` (a trident, an arrow).""" + return sum(kind in q['kind'].lower() for q in game('status')['projectiles']) + + +def check_held_use(host, guest, out): + """Items used until the button lets go, for each player: the client starts the use too + (Item.use runs on both sides), so letting go sends RELEASE_USE_ITEM and the server ends it.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 12} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x + 12} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:stone') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + s = {} + # ShieldItem: raised while held, lowered once let go. + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['shield'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['shield']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + # SpyglassItem: scoping while held. + game('command', command='item replace entity @s weapon.mainhand with minecraft:spyglass') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['spyglass'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['spyglass']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + # TridentItem.releaseUsing after 10 ticks: thrown. + host('command', command='kill @e[type=minecraft:trident]') + game('command', command='item replace entity @s weapon.mainhand with minecraft:trident') + game.wait(5) + # /kill finds no thrown trident (Horizon's selectors miss them): count what's new. + before = flying(game, 'trident') + game.raw('use-item', '--hold', 1.2) + game.wait(10) + s['trident'] = {'kept': server_count(game, 'trident'), + 'thrown': flying(game, 'trident') - before} + host('command', command='kill @e[type=minecraft:trident]') + # CrossbowItem: charged by holding (25 ticks), fired by the next use. + host('command', command='kill @e[type=minecraft:arrow]') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:crossbow') + game('command', command='give @s minecraft:arrow 16') + game.wait(5) + before = flying(game, 'arrow') + game.raw('use-item', '--hold', 1.6) + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'] = {'loaded': 'charged_projectiles' in str(held.get('components', '')), + 'arrows': server_count(game, 'arrow')} + game.raw('use-item') + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'].update( + fired=flying(game, 'arrow') - before, + emptied='charged_projectiles' not in str(held.get('components', ''))) + game.shot(out, 'helduse') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:arrow]') + host('command', command='kill @e[type=minecraft:trident]') + for game in (host, guest): + back_to_game(game) + game.raw('mouse', 'right', 'up') + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + for item in ('shield', 'spyglass'): + assert s[item] == {'held': (True, True), 'let_go': (False, False)}, f'{name} {item}: {seen}' + assert s['trident'] == {'kept': 0, 'thrown': 1}, f'{name} trident: {seen}' + assert s['crossbow'] == {'loaded': True, 'arrows': 15, 'fired': 1, 'emptied': True}, \ + f'{name} crossbow: {seen}' + return seen + + +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) + + +def check_digging(host, guest, out): + """The server breaks a block a player digs only once that player's client is done + (ServerPlayerGameMode: STOP_DESTROY_BLOCK, or the delayed destroy), never on its own count, so + the player's client always breaks it first, with its particles and sound. The guest holds + attack across a wall of six oak logs with a copper axe and hears each one break; then it digs + stone with a wooden pickaxe and its game stalls for a second halfway: the stone is still there + on both sides when it resumes, and the guest's own crack finishes it.""" + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + x, y, z = gx + 3, gy, gz + 4 + heard = lambda sound: guest('status')['heard'].get(sound, 0) + at = lambda b: (f'{b[0] + 0.02:.2f}', f'{b[1] + 0.5:.2f}', f'{b[2] + 0.5:.2f}') + guest('command', command='gamemode survival') + guest('command', command='item replace entity @s weapon.mainhand with minecraft:copper_axe') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y + 3} {z + 2} minecraft:air') + host('command', command=f'fill {x - 2} {y - 1} {z - 2} {x + 4} {y - 1} {z + 2} minecraft:stone') + host('command', command=f'fill {x + 2} {y} {z - 1} {x + 2} {y + 1} {z + 1} minecraft:oak_log') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + guest.wait(30) + logs = [(x + 2, y + dy, z + dz) for dz in (-1, 0, 1) for dy in (0, 1)] + before = heard('minecraft:block.wood.break') + guest.raw('look-at', *at(logs[0])) + guest.raw('mouse', 'left', 'down') + left = list(logs) + deadline = time.time() + 20 + while left and time.time() < deadline: + if guest.raw('block', *left[0]).get('block') != 'minecraft:oak_log': + left.pop(0) + if left: + guest.raw('look-at', *at(left[0])) + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen = {'logs_left': left, 'log_breaks_heard': heard('minecraft:block.wood.break') - before} + + # Stone with a wooden pickaxe: 23 ticks. The guest stalls for a second after about 8. + stone = (x + 2, y, z) + guest('command', command='item replace entity @s weapon.mainhand with minecraft:wooden_pickaxe') + host('command', command=f'setblock {stone[0]} {stone[1]} {stone[2]} minecraft:stone') + guest.wait(10) + before = heard('minecraft:block.stone.break') + guest.raw('look-at', *at(stone)) + guest.raw('mouse', 'left', 'down') + time.sleep(0.4) + os.kill(guest.pid, signal.SIGSTOP) + try: + time.sleep(1.0) + finally: + os.kill(guest.pid, signal.SIGCONT) + resumed = {'guest': guest.raw('block', *stone).get('block'), 'server': host.raw('block', *stone).get('block'), + 'mining': guest('state').get('mining')} + # Let go once it breaks: past it the crosshair reaches the floor. + deadline = time.time() + 5 + while guest.raw('block', *stone).get('block') == 'minecraft:stone' and time.time() < deadline: + pass + guest.raw('mouse', 'left', 'up') + guest.wait(10) + seen.update(resumed=resumed, stone_after=host.raw('block', *stone).get('block'), + stone_breaks_heard=heard('minecraft:block.stone.break') - before) + guest.shot(out, 'digging') + assert not left and seen['log_breaks_heard'] == 6, f'the server broke logs before the guest did: {seen}' + assert resumed['guest'] == resumed['server'] == 'minecraft:stone', f'the server broke the stone while the guest stalled: {seen}' + assert seen['stone_after'] == 'minecraft:air' and seen['stone_breaks_heard'] == 1, f'the guest did not break the stone: {seen}' + return seen + + +CHECKS += ['digging'] +CHECK_FNS.update(digging=check_digging) if __name__ == '__main__':