Respawn on a server in vanilla's order, so vanilla clients leave the loading screen

A vanilla 26.3 client that died on a Horizon server stayed on its loading
screen after pressing Respawn (#566): ClientPacketListener.handleRespawn
starts a LevelLoadTracker that waits for the level info's "level chunks
load start" game event and the chunk under the player, and Horizon's
respawn sent neither the level info nor the chunk cache centre.

The hub's respawn now follows PlayerList.respawn: the entities paired with
the dead player are removed (one packet each), its chunks are dropped
without ForgetLevelChunk (as PlayerChunkSender does for a dead player) and
sent again, the abilities, then Respawn (with the last death location),
the teleport to the spawn facing its direction, the default spawn,
difficulty, experience, post effects, the level info, the permission
level, the chunk cache centre and the inventory. A dying guest also gets
the death animation event and no health update while dead, as vanilla's
ServerPlayer.die does.

Guests' commands also ran at the host's permission level: an operator on
a dedicated server could not run operator commands (and LAN guests ran
the host's level). They now run at the guest's own level, as the command
tree they are sent says.

The dedicated server harness covers it: after trading, the vanilla-codec
client is made an operator by the console, runs /kill, respawns, and the
packets from the death screen to the respawned inventory are compared
with vanilla's, then the level must load where it respawned. The client
also stops sending a movement packet beside each teleport acceptance
during the respawn: the 26.3 client sends the acceptance alone, and
vanilla's server kicks a second position in the same tick.

Fixes #566

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 02:12:08 +02:00
parent ad5f05a8c7
commit 66d187ed06
5 changed files with 250 additions and 34 deletions
+28 -5
View File
@@ -13,6 +13,7 @@ use horizon_client::{
items::ItemStack,
lan::{
guest::SPECTATOR,
hub::TickCtx,
menu::{Rules, Slots},
},
motion::{MotionEvent, MotionWorld, PlayerMotion},
@@ -683,9 +684,14 @@ impl Game<'_> {
return;
}
let command = command.trim_start_matches('/').to_owned();
// The guest's own level (Commands.performCommand with the player's source): an
// operator's on a dedicated server, never the host's.
let permission = host.hub.guest(conn).map_or(0, |g| g.permission);
let lines = self.as_guest(host, conn, |g| {
g.chat_capture = Some(Vec::new());
let level = std::mem::replace(&mut g.ui.registries.permission, permission);
g.run_command(&command);
g.ui.registries.permission = level;
g.chat_capture
.take()
.unwrap_or_default()
@@ -759,7 +765,23 @@ impl Game<'_> {
g.saturation = 5.0;
g.sent_health = None;
g.motion = None;
host.hub.respawn(i, spawn);
let ctx = TickCtx {
world: &mut self.world,
host: None,
entities: &[],
next_entity: &mut self.next_entity,
spawn,
difficulty: i32::from(self.ui.difficulty),
difficulty_locked: self.level.difficulty_locked,
clock_rate: if self.ui.rules.bool("advance_time") {
self.ui.clock.rate
} else {
0.0
},
tick_rate: self.clock.rate(),
tick_frozen: self.clock.frozen(),
};
host.hub.respawn(i, spawn, &ctx);
}
/// Per tick, for every guest: dig, use items, pick up drops, die.
@@ -812,14 +834,15 @@ impl Game<'_> {
let g = &mut host.hub.guests[gi];
if g.health <= 0.0 && !g.dead {
g.dead = true;
g.last_death = Some(g.position.map(|v| v.floor() as i32));
let (id, at) = (g.entity_id, g.position);
let message = literal(&format!("{} died", g.name));
host.hub.send_to(
conn,
&C::PlayerCombatKill(play::PlayerCombatKill {
id: host.hub.guests[gi].entity_id,
message,
}),
&C::PlayerCombatKill(play::PlayerCombatKill { id, message }),
);
// LivingEntity.die: the death animation, the dying player included.
host.hub.entity_event(id, 3, at);
}
}
}
+3
View File
@@ -97,6 +97,8 @@ pub struct Guest {
pub menu_state: i32,
pub sent_health: Option<(f32, i32, f32)>,
pub sent_xp: Option<(f32, i32, i32)>,
/// Where the player last died (Player.lastDeathLocation), sent with the respawn.
pub last_death: Option<[i32; 3]>,
pub sent_selected: usize,
pub inbox: VecDeque<play::Serverbound>,
pub joined_tick: u64,
@@ -178,6 +180,7 @@ impl Guest {
menu_state: 0,
sent_health: None,
sent_xp: None,
last_death: None,
sent_selected: 0,
inbox: VecDeque::new(),
joined_tick: 0,
+76 -20
View File
@@ -621,6 +621,22 @@ impl Hub {
}));
}
/// ClientboundSetDefaultSpawnPositionPacket for the level's respawn data.
fn default_spawn(&self, spawn: [f64; 3]) -> C {
C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition {
pos: play::GlobalPos {
dimension: self.config.dimension.clone(),
pos: [
spawn[0].floor() as i32,
spawn[1].floor() as i32,
spawn[2].floor() as i32,
],
},
yaw: 0.0,
pitch: 0.0,
})
}
/// PlayerList.sendLevelInfo.
fn send_level_info(&mut self, i: usize, ctx: &TickCtx) {
let spawn = ctx.spawn;
@@ -637,18 +653,7 @@ impl Hub {
warning_time: 300,
}));
g.send(&self.time_packet(ctx.world, ctx.clock_rate));
g.send(&C::SetDefaultSpawnPosition(play::SetDefaultSpawnPosition {
pos: play::GlobalPos {
dimension: self.config.dimension.clone(),
pos: [
spawn[0].floor() as i32,
spawn[1].floor() as i32,
spawn[2].floor() as i32,
],
},
yaw: 0.0,
pitch: 0.0,
}));
g.send(&self.default_spawn(spawn));
let w = &ctx.world.weather;
if w.raining {
g.send(&C::GameEvent(play::GameEvent {
@@ -1297,7 +1302,8 @@ impl Hub {
let g = &self.guests[i];
(g.health, g.food, g.saturation)
};
if self.guests[i].sent_health != Some(health) {
// A dead player's health isn't sent (the death screen shows from the combat kill).
if self.guests[i].sent_health != Some(health) && !self.guests[i].dead {
let g = &mut self.guests[i];
g.send(&C::SetHealth(play::SetHealth {
health: health.0,
@@ -1547,23 +1553,73 @@ impl Hub {
.map(str::to_owned)
}
/// ServerPlayer.respawn: back to `at` with a fresh start.
pub fn respawn(&mut self, i: usize, at: [f64; 3]) {
/// PlayerList.respawn: back to `at` with a fresh start. The vanilla client waits on its
/// level loading screen from the Respawn packet until the level info's "level chunks load
/// start" event and the chunk under the player, so the packets follow vanilla's order.
pub fn respawn(&mut self, i: usize, at: [f64; 3], ctx: &TickCtx) {
let mode = self.guests[i].game_mode;
let info = self.spawn_info(mode);
let mut info = self.spawn_info(mode);
// Player.getLastDeathLocation, set where the player died.
info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos {
dimension: self.config.dimension.clone(),
pos,
});
self.close_container_for(i);
let g = &mut self.guests[i];
// ServerLevel.removePlayerImmediately: every entity paired with the dead player is
// removed (ServerEntity.removePairing, one packet each). Its chunks are dropped
// without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the
// client keeps them and they are all sent again.
for id in g.tracker.ids() {
g.send(&C::RemoveEntities(play::RemoveEntities { ids: vec![id] }));
}
g.tracker.clear();
g.sent_chunks.clear();
g.chunk_queue.clear();
// ServerPlayer.restoreFrom: the game mode again (onUpdateAbilities).
g.send(&C::PlayerAbilities(play::PlayerAbilities {
flags: g.ability_flags(),
flying_speed: 0.05,
walking_speed: 0.1,
}));
// The new player faces the level's respawn direction (snapTo).
g.yaw = 0.0;
g.pitch = 0.0;
g.position = at;
g.previous_position = at;
g.send(&C::Respawn(play::Respawn {
spawn: info,
keep: 0,
}));
g.center = None;
g.sent_chunks.clear();
g.chunk_queue.clear();
g.tracker.clear();
self.teleport(i, None);
let spawn = self.default_spawn(ctx.spawn);
let g = &mut self.guests[i];
g.send(&spawn);
g.send(&C::ChangeDifficulty(play::ChangeDifficulty {
difficulty: ctx.difficulty,
locked: ctx.difficulty_locked,
}));
let xp = (g.xp_progress, g.xp_level, g.xp_total);
g.send(&C::SetExperience(play::SetExperience {
progress: xp.0,
level: xp.1,
total: xp.2,
}));
g.sent_xp = Some(xp);
// ServerPlayer.sendPostEffects.
g.send(&raw(ids::POST_EFFECTS, vec![0]));
self.send_level_info(i, ctx);
self.send_permission_level(i);
// ServerLevel.addRespawnedPlayer: the chunk tracking starts again at the player.
let g = &mut self.guests[i];
let (cx, cz) = g.chunk();
g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter {
x: cx,
z: cz,
}));
g.center = None;
g.center_sent = Some((cx, cz));
// ServerPlayer.initInventoryMenu.
self.send_inventory(i);
}
}
@@ -430,6 +430,16 @@ public final class VanillaProtocolClient {
long deadline = System.currentTimeMillis() + 90_000;
int step = 0;
long stepAt = 0;
// The death the console deals and the respawn after it (PlayerList.respawn): from the
// client's PERFORM_RESPAWN until its level is loaded again (LevelLoadTracker: the level
// info's "level chunks load start" event, then the chunk under the player).
boolean respawning = false;
boolean respawned = false;
boolean loadStart = false;
boolean respawnChunk = false;
String runType = null;
int run = 0;
PositionMoveRotation respawnAt = null;
// The villager the server's console summoned beside the spawn.
int villager = -1;
net.minecraft.world.phys.Vec3 villagerAt = null;
@@ -445,6 +455,22 @@ public final class VanillaProtocolClient {
Packet<?> packet = r.packet;
counts.merge(r.type, 1, Integer::sum);
if (r.type.equals("minecraft:chunk_batch_start")) ordered = false;
if (respawning && !respawned) {
String line = respawnLine(r);
// PlayerList.respawn ends with initInventoryMenu: what follows is the
// next ticks' (health, entity data, chunks), in each server's own order.
respawned = r.type.equals("minecraft:container_set_content") && respawnAt != null;
if (line != null && !line.equals(runType)) {
if (runType != null) record("play-respawn", runLine(runType, run));
runType = line;
run = 0;
}
if (line != null) run++;
if (packet instanceof net.minecraft.network.protocol.game.ClientboundGameEventPacket p
&& p.getEvent() == net.minecraft.network.protocol.game.ClientboundGameEventPacket.LEVEL_CHUNKS_LOAD_START) {
loadStart = true;
}
}
if (packet instanceof ClientboundKeepAlivePacket p) {
send(new ServerboundKeepAlivePacket(p.getId()));
} else if (packet instanceof ClientboundPingPacket p) {
@@ -452,9 +478,14 @@ public final class VanillaProtocolClient {
} else if (packet instanceof ClientboundPlayerPositionPacket p) {
position = PositionMoveRotation.calculateAbsolute(position, p.change(), p.relatives());
record("play-move", text(position.position()) + " " + position.yRot() + " " + position.xRot());
if (respawning) respawnAt = position;
send(new ServerboundAcceptTeleportationPacket(p.id(), position.position().x, position.position().y, position.position().z,
position.yRot(), position.xRot()));
send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false));
// The 26.3 client answers with the acceptance alone; a second position in the
// same tick is an invalid move to vanilla's server once the player is loaded.
if (!respawning) {
send(new ServerboundMovePlayerPacket.PosRot(position.position(), position.yRot(), position.xRot(), false, false));
}
if (!loaded) {
send(new ServerboundPlayerLoadedPacket());
loaded = true;
@@ -467,15 +498,27 @@ public final class VanillaProtocolClient {
lastChunk = now;
int px = (int) Math.floor(position.position().x) >> 4;
int pz = (int) Math.floor(position.position().z) >> 4;
if (p.x() == px && p.z() == pz) chunkParts(p);
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0) {
if (p.x() == px && p.z() == pz && !respawning) chunkParts(p);
if (p.x() == px && p.z() == pz && respawnAt != null) respawnChunk = true;
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p
&& step == 5 + REPLIES.length && (int) (byte) field(p, "eventId") == 28) {
// Operator (level 4, as the console made it): it may run /kill on itself.
send(new ServerboundChatCommandPacket("kill"));
step++;
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket p && step > 0) {
// The death message is left out: guests' death messages aren't Horizon's yet.
record("play-death", "death screen");
send(new net.minecraft.network.protocol.game.ServerboundClientCommandPacket(
net.minecraft.network.protocol.game.ServerboundClientCommandPacket.Action.PERFORM_RESPAWN));
respawning = true;
} else if (packet instanceof ClientboundSystemChatPacket p && step > 0 && step < 5 + REPLIES.length) {
record("play-chat", "system " + p.overlay() + " " + json(p.content()));
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0) {
} else if (packet instanceof ClientboundPlayerChatPacket p && step > 0 && step < 5 + REPLIES.length) {
record("play-chat", "player " + p.sender() + " " + p.index() + " " + p.body().content() + " " + p.signature().isPresent()
+ " " + p.unsignedContent().map(VanillaProtocolClient::json) + " " + text(p.filterMask()) + " "
+ p.chatType().chatType().getRegisteredName() + " " + json(p.chatType().name()) + " "
+ p.chatType().targetName().map(VanillaProtocolClient::json));
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0) {
} else if (packet instanceof ClientboundDisguisedChatPacket p && step > 0 && step < 5 + REPLIES.length) {
record("play-chat", "disguised " + json(p.message()) + " " + p.chatType().chatType().getRegisteredName());
} else if (packet instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket p
&& p.getType() == net.minecraft.world.entity.EntityTypes.VILLAGER) {
@@ -561,12 +604,71 @@ public final class VanillaProtocolClient {
} else if (step == 4 + REPLIES.length && now - stepAt > 1500) {
send(new net.minecraft.network.protocol.game.ServerboundContainerClosePacket(1));
record("play-counts", "chunks " + counts.getOrDefault("minecraft:level_chunk_with_light", 0));
// The harness's console makes the player an operator once it reads this line.
send(new ServerboundChatPacket("ready to respawn", Instant.now(), 0L, Optional.empty(),
new LastSeenMessages.Update(0, new BitSet(), (byte) 0)));
step++;
stepAt = now;
} else if (step == 6 + REPLIES.length && loadStart && respawnChunk) {
// LevelLoadTracker is done: the vanilla client leaves the loading screen.
if (runType != null) record("play-respawn", runLine(runType, run));
record("play-respawn", "level loaded at " + text(respawnAt.position()));
send(new ServerboundPlayerLoadedPacket());
return;
}
}
if (respawning) {
if (runType != null) record("play-respawn", runLine(runType, run));
record("play-respawn", "level never loaded: load start " + loadStart + ", chunk under the player " + respawnChunk);
}
record("error", "timed out in play, step " + step + ", chunks " + chunks.size());
}
/**
* A run of the same packet: counted, but for the entities removed with the dead player
* (which mobs are tracked near the spawn at that moment varies).
*/
private static String runLine(String type, int run) {
return type + (run > 1 && !type.equals("minecraft:remove_entities") ? " x" + run : "");
}
/**
* A packet after the respawn request, as compared: entity ids and periodic or streamed
* packets (time, keep-alive, chunk data and light, whose batching follows each server's
* timing) left out; null to skip it.
*/
private String respawnLine(Received r) {
String t = r.type;
// Entities moving and the dead player's health land in the window between the death
// and the respawn as each server's ticks fall: left out.
if (t.startsWith("minecraft:move_entity") || t.equals("minecraft:rotate_head") || t.equals("minecraft:set_entity_motion")
|| t.equals("minecraft:set_entity_data") || t.equals("minecraft:entity_position_sync") || t.equals("minecraft:set_health")) {
return null;
}
if (t.equals("minecraft:keep_alive") || t.equals("minecraft:ping") || t.equals("minecraft:level_chunk_with_light")
|| t.equals("minecraft:chunk_batch_start") || t.equals("minecraft:chunk_batch_finished")
|| t.equals("minecraft:light_update") || t.equals("minecraft:bundle_delimiter")
// Chat (the death message and /kill's feedback) is compared before the death.
|| t.equals("minecraft:system_chat") || t.equals("minecraft:player_chat") || t.equals("minecraft:disguised_chat")) {
return null;
}
if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundSetTimePacket p && p.clockUpdates().isEmpty()) {
return null;
}
if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundEntityEventPacket p) {
return t + " " + field(p, "eventId");
}
if (r.packet instanceof net.minecraft.network.protocol.game.ClientboundRemoveEntitiesPacket p) {
return t;
}
if (t.equals("minecraft:respawn") || t.equals("minecraft:game_event") || t.equals("minecraft:set_default_spawn_position")
|| t.equals("minecraft:change_difficulty") || t.equals("minecraft:set_experience") || t.equals("minecraft:set_health")
|| t.equals("minecraft:set_chunk_cache_center") || t.equals("minecraft:initialize_border")) {
return t + " " + text(r.packet);
}
return t;
}
/**
* A chunk's blocks, biomes, heightmaps and block entities (its
* ClientboundLevelChunkPacketData bytes). The light is left out: both servers relight around chunks
+36 -4
View File
@@ -10,8 +10,11 @@ read is an error), pings each server, joins it in offline mode through
login, configuration and play, accepts the spawn teleport, receives the
chunks around the spawn (their bytes are compared: the world is loaded from
the same files), chats, runs /list and commands that fail (`/random value
7..7`, `/random value x`, `/trigger nope`) and leaves. The console then
runs `list` and `say` and `stop`. Compared, all of them exactly:
7..7`, `/random value x`, `/trigger nope`), trades, is made an operator by
the console, runs /kill, respawns (as vanilla's LevelLoadTracker waits: until the "level
chunks load start" event and the chunk under the player) and leaves. The
console then runs `list` and `say` and `stop`. Compared, all of them
exactly:
- the status response (MOTD, players, version, favicon) and the ping;
- the legacy (pre-1.7, 0xFE) ping reply;
@@ -22,6 +25,10 @@ runs `list` and `say` and `stop`. Compared, all of them exactly:
advancements, which vanilla keeps in hash maps, sorted); the command tree
node by node; the chunks sent and their bytes; the replies to the chat
message, /list and the failing commands, as text components;
- after /kill, the packets from the death screen to the respawned
inventory (PlayerList.respawn; chat, chunk data, light and keep-alives
left out, runs of a packet counted), then that the level loads where the
player respawned (guests' death messages aren't Horizon's yet: left out);
- the console lines about the player, the chat, `list`, `say` and `stop`;
- the files the servers leave: server.properties (but the date line),
eula.txt, ops.json, whitelist.json, banned-players.json, banned-ips.json.
@@ -197,12 +204,17 @@ CONSOLE_LINE = re.compile(r'^\[\d\d:\d\d:\d\d\] \[([^\]]+)\]: (.*)$')
KEPT = re.compile(r'Tester|\[Server\]|\[Not Secure\]|There are|Stopping|Saving|ThreadedAnvilChunkStorage|All dimensions|Unknown or incomplete')
# Guests' death messages and the op's command feedback broadcast to the console aren't
# Horizon's yet (the client's own transcript leaves the death message out as well).
NOT_YET = re.compile(r'Tester was killed|Killed Tester|^\[Tester: ')
def console_lines(lines):
"""The console lines the comparison covers, timestamps and ports aside."""
out = []
for line in lines:
m = CONSOLE_LINE.match(line)
if not m or not KEPT.search(m.group(2)):
if not m or not KEPT.search(m.group(2)) or NOT_YET.search(m.group(2)):
continue
text = re.sub(r'/127\.0\.0\.1:\d+', '/127.0.0.1:_', m.group(2))
text = re.sub(r'entity id \d+', 'entity id _', text)
@@ -246,7 +258,27 @@ def run_side(label, command, directory, client):
'{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}')
port = int(PROPERTIES_PORTS[label])
legacy = legacy_ping(port)
client(port, directory.parent / f'{label}-client.txt')
# The client asks to be made an operator once it has traded, runs /kill and respawns.
failure = []
def join():
try:
client(port, directory.parent / f'{label}-client.txt')
except BaseException as error: # noqa: BLE001 - reported on the main thread
failure.append(error)
joined = threading.Thread(target=join)
joined.start()
deadline = time.time() + 300
while joined.is_alive() and not any('<Tester> ready to respawn' in l for l in server.lines):
if time.time() > deadline:
break
time.sleep(0.2)
if joined.is_alive():
server.console(f'op {PLAYER}')
joined.join()
if failure:
raise failure[0]
time.sleep(1)
server.console('list')
server.console('say console says hi')