From 52d8ed6721be9b7db334284f14b0fb271ba13f86 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 17:57:34 +0200 Subject: [PATCH] Signs open their editor on a server's players, and what they write reaches the server A sign a server's player placed (a LAN guest, or single player's window on its server thread) opened no editor: its turn's editor was dropped with the rest of the guest's screens (#1380). The server now does as ServerPlayer.openTextEdit: the block, then ClientboundOpenSignEditorPacket, and the player may write on that sign. The client opens its editor on the sign it has and sends ServerboundSignUpdatePacket when it closes; the server takes the lines (formatting codes stripped) unless the sign is waxed, the player was not the one allowed or went out of reach, and sends the sign to everyone. The window's own sign now reaches its guests too (sendBlockUpdated, not only a save). horizon-protocol: OpenSignEditor and SignUpdate, with SignTextSlot as a VarInt and the lines as a fixed list of four (26.3's stream codecs). horizon-ctl: type and key reach an open sign editor; block shows a sign's lines. lan_e2e signs: host and guest each place, write and see, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/agent.rs | 6 ++ crates/horizon-client/src/game/control.rs | 13 ++- crates/horizon-client/src/game/lan_actions.rs | 9 +- .../horizon-client/src/game/lan_stations.rs | 27 +++--- crates/horizon-client/src/game/remote.rs | 1 + crates/horizon-client/src/game/sign_edit.rs | 90 ++++++++++++++++++- crates/horizon-protocol/src/packets/play.rs | 63 +++++++++++++ tools/lan_e2e.py | 44 ++++++++- 8 files changed, 234 insertions(+), 19 deletions(-) diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 868a8d046..0c1954891 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 { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..271f9b116 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/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8e07dfb05..ac557e2dd 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)>, @@ -510,7 +512,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 { @@ -649,6 +652,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); } @@ -1025,6 +1031,7 @@ impl Game<'_> { 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::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); } 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 156fbe13b..67e30d7c1 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -2573,6 +2573,7 @@ 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), // handleSetSpawn: ClientLevel.setRespawnData, which spawn compasses point at. C::SetDefaultSpawnPosition(p) => { let [x, y, z] = p.pos.pos; 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-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..cfbc3d78b 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -461,6 +461,10 @@ 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!(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; @@ -1507,6 +1511,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, MountScreenOpen(MountScreenOpen) = MOUNT_SCREEN_OPEN, OpenScreen(OpenScreen) = OPEN_SCREEN, + OpenSignEditor(OpenSignEditor) = OPEN_SIGN_EDITOR, Ping(Ping) = PING, PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, @@ -1805,6 +1810,38 @@ 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 } +); +/// 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. @@ -1912,6 +1949,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, }); @@ -2608,4 +2646,29 @@ 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); + } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 479feaf4e..f5127fa0c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -179,6 +179,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - 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). 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). @@ -4120,8 +4123,45 @@ def check_keep_inventory(host, guest, out): return seen -CHECKS += ['totem', 'keepinv'] -CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory) +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 + + +CHECKS += ['totem', 'keepinv', 'signs'] +CHECK_FNS.update(totem=check_totem, keepinv=check_keep_inventory, signs=check_signs) if __name__ == '__main__':