From 5bfc649edd18aaf9738dc428bc24ae9e991cf87d Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Sun, 25 Oct 2026 15:52:29 +0100 Subject: [PATCH] Drop the cursor stack of a dead player A stack held on the inventory cursor at death stayed there through the respawn, even with keep_inventory off. In vanilla the dead player is removed 20 ticks after dying (or when it respawns sooner), and Player.remove's inventoryMenu.removed drops what the cursor held where the player died. Do the same for server players and the in-frame player, and add a harness that dies with a cursor stack on a dedicated server and compares with vanilla. --- crates/horizon-client/src/game.rs | 20 ++- crates/horizon-client/src/game/chat.rs | 2 + crates/horizon-client/src/game/lan_actions.rs | 27 +++- crates/horizon-client/src/lan/guest.rs | 3 + .../horizonlab/parity/LocatorBarClient.java | 10 +- tools/test_cursor_death_parity.py | 143 ++++++++++++++++++ 6 files changed, 202 insertions(+), 3 deletions(-) create mode 100644 tools/test_cursor_death_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 699468651..667eff52a 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2173,6 +2173,11 @@ impl Game<'_> { // Player.drop: the drop statistics. self.stats.add("dropped", &thrown.item, thrown.count as i32); self.stats.custom("drop", 1); + self.throw_from_eyes(thrown, eye); + } + /// `Player.createItemStackToDrop`: an item entity thrown from the eyes + /// along the view direction. + fn throw_from_eyes(&mut self, thrown: ItemStack, eye: [f64; 3]) { let (yaw, pitch) = ( f64::from(self.yaw).to_radians(), f64::from(self.pitch).to_radians(), @@ -4335,7 +4340,8 @@ impl Game<'_> { // Out of the world. let _ = player.set_health(0.0, false); } - if player.health.dead_or_dying() && self.screen != Screen::Dead { + let dead = player.health.dead_or_dying(); + if dead && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. let feet = [player.position.x, player.position.y, player.position.z]; let at = [feet[0], feet[1] + 1.32, feet[2]]; @@ -4369,6 +4375,18 @@ impl Game<'_> { } self.screen = Screen::Dead; self.capture(false); + self.ui.death_time = 0; + } else if dead { + // LivingEntity.tickDeath: 20 ticks after dying the player is + // removed, and Player.remove's inventoryMenu.removed drops what + // the cursor held. + self.ui.death_time += 1; + if self.ui.death_time >= 20 + && let Some(stack) = self.carried.take() + && let Some(eye) = self.eye_position() + { + self.throw_from_eyes(stack, eye); + } } self.tick_world(running) } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index ec85732ae..15e34bbb6 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -99,6 +99,8 @@ pub struct UiState { /// Death screen cause and when the player died (buttons wait 20 ticks). pub death_text: Option, pub died_at: Option, + /// `LivingEntity.deathTime` of the window's player: ticks since it died. + pub death_time: u32, } impl Game<'_> { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c7019c73..de6ae51dc 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -1234,6 +1234,24 @@ impl Game<'_> { Some(out) } + /// `LivingEntity.tickDeath`: 20 ticks after dying the player is removed, + /// and `Player.remove`'s `inventoryMenu.removed` drops what the cursor + /// held (`dropOrPlaceInInventory` for a removed player). Respawning + /// sooner removes it too. + fn guest_tick_death(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.death_time += 1; + if g.death_time >= 20 { + self.guest_drop_carried(host, gi); + } + } + + fn guest_drop_carried(&mut self, host: &mut LanHost, gi: usize) { + if let Some(c) = host.hub.guests[gi].carried.take() { + self.drop_guest_items(host, gi, vec![c]); + } + } + /// `AbstractContainerMenu.removed`: what a closing player held on the /// cursor goes back into their inventory (`placeItemBackInInventory`, /// dropped only if it doesn't fit), and their client's cursor empties @@ -1573,6 +1591,8 @@ impl Game<'_> { if !host.hub.guests[i].dead { return; } + // PlayerList.respawn removes the dead player (Player.remove). + self.guest_drop_carried(host, i); // PlayerList.respawn: a server's player comes back in its respawn // point's level: the Overworld, where the world spawn and beds are, // or another one's anchor or forced point, which its block resolves @@ -1613,6 +1633,7 @@ impl Game<'_> { } let g = &mut host.hub.guests[i]; g.dead = false; + g.death_time = 0; g.health = 20.0; g.food = 20; g.saturation = 5.0; @@ -1694,7 +1715,11 @@ impl Game<'_> { continue; }; self.guest_sleep_tick(host, gi); - if host.hub.guests[gi].dead || self.on_server_trip(conn) { + if host.hub.guests[gi].dead { + self.guest_tick_death(host, gi); + continue; + } + if self.on_server_trip(conn) { continue; } let play = host.play.entry(conn).or_default(); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 440b58284..70510a5b4 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -223,6 +223,8 @@ pub struct Guest { /// Whether the guest was on the ground before the first of `moves`. pub moves_from_ground: bool, pub dead: bool, + /// `LivingEntity.deathTime`: ticks since the guest died. + pub death_time: u32, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, /// The level the player is in (`ServerPlayer.level().dimension()`): the @@ -349,6 +351,7 @@ impl Guest { moves: Vec::new(), moves_from_ground: false, dead: false, + death_time: 0, placed: false, dimension: "minecraft:overworld".into(), menu: None, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index 76a951894..e4aeef25e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -84,7 +84,10 @@ import net.minecraft.world.phys.Vec3; * still), {@code sync NAME} (runs {@code time query gametime}, whose reply is * not recorded, and prints {@code synced NAME} once it is back: the server has * handled everything this player sent before, and everything the server sent - * this player before the reply has been recorded), {@code quit NAME}, {@code + * this player before the reply has been recorded), {@code respawn NAME} (the + * death screen's button, ServerboundClientCommandPacket PERFORM_RESPAWN), + * {@code pickup NAME SLOT} (a left click on that slot of the player's + * inventory menu, claiming nothing), {@code quit NAME}, {@code * players on|off} (whether each player also records the other players added * to and removed from its level, and its own respawns into a dimension), * {@code chat on|off} (whether the system chat each player receives is @@ -130,6 +133,11 @@ public final class LocatorBarClient { players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundPlayerAbilitiesPacket(abilities)); } case "still" -> players.get(w[1]).still(); + case "respawn" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket( + net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN)); + case "pickup" -> players.get(w[1]).send(new net.minecraft.network.protocol.game.ServerboundContainerClickPacket( + 0, 0, Short.parseShort(w[2]), (byte) 0, net.minecraft.world.inventory.ContainerInput.PICKUP, + new it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap<>(), net.minecraft.network.HashedStack.EMPTY)); case "sync" -> { try { players.get(w[1]).sync(); diff --git a/tools/test_cursor_death_parity.py b/tools/test_cursor_death_parity.py new file mode 100644 index 000000000..8da944350 --- /dev/null +++ b/tools/test_cursor_death_parity.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""What a player holds on the cursor when they die, on a dedicated server, against vanilla's, seen by a vanilla client. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world +vanilla generated first, with Alice an operator in survival and keep_inventory off. LocatorBarClient (a player made +of vanilla's protocol code) is given seven diamonds, picks them up onto its inventory menu's cursor (a PICKUP click) +ten blocks from the spawn, runs /kill on itself, waits on the death screen and respawns (PERFORM_RESPAWN). Twenty +ticks after dying vanilla removes the dead player (LivingEntity.tickDeath), and Player.remove's +inventoryMenu.removed drops the cursor's stack where it died. Alice then asks whether an item lies around the death +site; the reply, and the inventory slots, respawns and teleports she is sent from the death on, are compared +exactly. +""" +import json +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time + +try: + from . import lab, test_rust_parity as base, test_locator_bar_parity as locator + from .test_dedicated_server_parity import Server +except ImportError: + import lab + import test_rust_parity as base + import test_locator_bar_parity as locator + from test_dedicated_server_parity import Server + +NAME = 'cursor-death-parity' +# server_dir and generate_world write these server.properties. +locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival') +SCRIPT = [ + ('setup', ['cmd Alice gamerule keep_inventory false', 'cmd Alice clear @s', + 'cmd Alice give @s minecraft:diamond 7', 'cmd Alice tp @s 10.5 -60 0.5']), + # Hotbar slot 0 is the inventory menu's slot 36. + ('pickup', ['pickup Alice 36']), + ('death', ['cmd Alice kill @s']), + ('respawn', ['respawn Alice']), + ('check', ['chat Alice on', + 'cmd Alice execute if entity @e[type=minecraft:item,x=10.5,y=-60,z=0.5,distance=..4]']), +] +STEP_SECONDS = 4.0 +SHOWN = ('slot', 'inventory', 'respawn', 'teleport', 'chat') + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = locator.server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + tell('players on') + tell('state on') + tell('step joins') + tell('join Alice') + server.wait_for(r'Alice joined the game', timeout=120) + time.sleep(STEP_SECONDS) + for step, actions in SCRIPT: + tell(f'step {step}') + for action in actions: + tell(action.replace('chat Alice', 'chat')) + time.sleep(STEP_SECONDS) + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + return out.read_text(encoding='utf-8').splitlines() + + +def shown(lines): + """Alice's slots, respawns, teleports and chat from the death on.""" + steps = {'step=death', 'step=respawn', 'step=check'} + return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 and parts[1] in steps + and parts[2] in SHOWN] + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = locator.generate_world(vanilla_server, build) + vanilla_all = run_side('vanilla', vanilla_server, client, build, world) + horizon_all = run_side('horizon', horizon_server, client, build, world) + errors = [l for l in vanilla_all + horizon_all if ' error ' in f' {l} ' or 'disconnected' in l] + vanilla, horizon = shown(vanilla_all), shown(horizon_all) + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:6000]) + if not any(l.startswith('Alice step=check chat') for l in vanilla): + raise AssertionError(f'vanilla answered no check command: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='A player dying with a stack on the inventory menu cursor (keep_inventory off) and respawning on a ' + 'dedicated server: the stack is dropped where it died, not kept.')) + print(f'cursor death: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}')