diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index ae7b182b4..dc6be85b7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -283,9 +283,11 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, - /// Single player runs on an integrated server thread (game/integrated.rs), - /// as vanilla's does: the default. `--no-server-thread` or - /// `HORIZON_SERVER_THREAD=0` runs the world in the frame instead. + /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on an + /// integrated server thread (game/integrated.rs), as vanilla's does. Off by + /// default again until a server's players reach parity with the in-frame + /// world (signs, books, totems, keep_inventory...); `--no-server-thread` + /// keeps it off. server_thread: bool, /// Set on the integrated server's own options: it draws nothing, so it skips meshing. integrated: bool, @@ -343,7 +345,7 @@ impl Options { dev_mods: Vec::new(), // The command harness (HORIZON_COMMAND_SCRIPT) drives the world // itself, without the event loop: it stays in the frame. - server_thread: std::env::var("HORIZON_SERVER_THREAD").map_or(true, |v| v != "0") + server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1") && std::env::var_os("HORIZON_COMMAND_SCRIPT").is_none(), integrated: false, }; @@ -353,7 +355,7 @@ impl Options { match arg.as_str() { "--help" | "-h" => { println!( - "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --no-server-thread Run single player's world in the frame, not on its server thread\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", + "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --server-thread Run single player's world on its server thread (not at parity yet)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", horizon_core::VANILLA_VERSION ); return Ok(None); @@ -4304,7 +4306,7 @@ impl Game<'_> { /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { self.update_chunk_tickets(); - horizon_client::spans::time("tick_effects", || self.tick_effects()); + horizon_client::spans::time("tick_effects", || self.tick_effects(running)); // Player.tick's ItemCooldowns.tick for the window's player (a // server's players count theirs down in `tick_guests`). self.shield_cooldown = self.shield_cooldown.saturating_sub(1); @@ -7035,10 +7037,16 @@ impl Game<'_> { // Item.getAttackDamageBonus (a mace's smash), before the critical hit. amount += self.smash_damage_bonus(target_kind); let player = self.player.as_ref(); - // Player.canCriticalAttack: falling, off the ground, not sprinting. - let falling = - player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting); - let crit = scale > 0.9 && falling; + // Player.canCriticalAttack: falling, off the ground, not in water, + // not blind (isMobilityRestricted), not riding, not sprinting. + let falling = player.is_some_and(|p| { + !p.ground.on_ground + && p.fall_distance > 0.0 + && !p.fluids.was_touching_water + && !p.sprinting + }); + let restricted = self.potions.effects.get("blindness").is_some() || self.riding.is_some(); + let crit = scale > 0.9 && falling && !restricted; if crit { amount *= 1.5; } @@ -7647,6 +7655,8 @@ impl Game<'_> { world.game_time = self.world.game_time; world.day_time = self.world.day_time; world.weather = self.world.weather; + // The game rules and the difficulty hold in every dimension. + world.health_rules = self.world.health_rules; // An open hub keeps hearing the new level's block changes. world.block_log = self.world.block_log.as_ref().map(|_| Vec::new()); world.light_log = self.world.light_log.as_ref().map(|_| Default::default()); diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index b5c6e63d9..ab2d9000b 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -810,7 +810,10 @@ impl Game<'_> { None => break, }, }; - if self.slot_get(slot) != item && self.slot_set(slot, item) { + // ItemStack.isEmpty: air (or a count of 0) is an empty slot. + // SlotAccess.set counts every slot it sets, the same item too. + let item = item.filter(|s| &*s.item != "minecraft:air" && s.count > 0); + if self.slot_set(slot, item) { changed += 1; } } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index d5cc5d9bf..c6f5d419b 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -2702,6 +2702,7 @@ impl Game<'_> { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, }) } } diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 16bd38904..8593e2b98 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -8,6 +8,15 @@ use super::Game; use horizon_client::{enchant::EffectContext, items::ItemStack}; use horizon_core::random::RandomSource; +/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`). +#[derive(Clone, Copy)] +enum MendSlot { + Main, + Off, + /// An `armor` index (head first). + Armor(usize), +} + impl Game<'_> { /// `Player.getDestroySpeed` after the tool speed: mining efficiency, haste /// and mining fatigue. @@ -314,36 +323,29 @@ impl Game<'_> { pub(super) fn mending(&mut self, amount: u32) -> u32 { let mut amount = amount; loop { - // EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged): held and armor. - let mut candidates: Vec<(bool, usize)> = Vec::new(); - if let Some(s) = &self.inventory[self.selected] - && s.damage > 0 - && s.enchantment_level("minecraft:mending") > 0 - { - candidates.push((false, self.selected)); - } - for (i, s) in self.armor.iter().enumerate() { - if let Some(s) = s - && s.damage > 0 - && s.enchantment_level("minecraft:mending") > 0 - { - candidates.push((true, i)); - } - } + // EnchantmentHelper.getRandomItemWith(REPAIR_WITH_XP, damaged), in + // EquipmentSlot order: the main hand, the off hand, then feet, legs, + // chest and head (`armor` holds head first). + let mending = |s: &Option| { + s.as_ref() + .is_some_and(|s| s.damage > 0 && s.enchantment_level("minecraft:mending") > 0) + }; + let candidates: Vec = [MendSlot::Main, MendSlot::Off] + .into_iter() + .chain((0..self.armor.len()).rev().map(MendSlot::Armor)) + .filter(|&slot| mending(self.mend_slot(slot))) + .collect(); if candidates.is_empty() { return amount; } - let (armor, i) = candidates[self + let slot = candidates[self .world .random .next_int_bound(candidates.len() as i32) .unwrap_or(0) as usize]; - let stack = if armor { - self.armor[i].clone() - } else { - self.inventory[i].clone() + let Some(stack) = self.mend_slot(slot).clone() else { + return amount; }; - let Some(stack) = stack else { return amount }; let ctx = EffectContext { items: Some(self.res.items()), ..Default::default() @@ -356,12 +358,7 @@ impl Game<'_> { amount as f32, ) as u32; let repaired = to_repair_xp.min(stack.damage); - let slot = if armor { - &mut self.armor[i] - } else { - &mut self.inventory[i] - }; - if let Some(s) = slot.as_mut() { + if let Some(s) = self.mend_slot_mut(slot).as_mut() { s.damage -= repaired; } if repaired == 0 || to_repair_xp == 0 { @@ -374,6 +371,20 @@ impl Game<'_> { amount = remaining; } } + fn mend_slot(&self, slot: MendSlot) -> &Option { + match slot { + MendSlot::Main => &self.inventory[self.selected], + MendSlot::Off => &self.offhand, + MendSlot::Armor(i) => &self.armor[i], + } + } + fn mend_slot_mut(&mut self, slot: MendSlot) -> &mut Option { + match slot { + MendSlot::Main => &mut self.inventory[self.selected], + MendSlot::Off => &mut self.offhand, + MendSlot::Armor(i) => &mut self.armor[i], + } + } /// Bow enchantments at release: (extra base damage, infinity keeps the arrow). pub(super) fn bow_enchantments(&mut self) -> (f64, bool) { let Some(bow) = self.inventory[self.selected].clone() else { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index ef5775174..49266a855 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -6,9 +6,12 @@ //! the world's options) with [`Integrated::call`], as vanilla's client calls //! into its `IntegratedServer`. //! -//! On by default. `--no-server-thread` or `HORIZON_SERVER_THREAD=0` runs -//! the world in the frame instead (the escape hatch while the network -//! player's side catches up with the in-frame one). +//! Opt-in again (`--server-thread` or `HORIZON_SERVER_THREAD=1`) until a +//! server's players reach parity with the in-frame world: on the server +//! thread, signs open no editor, books don't open, a totem doesn't save its +//! holder and death keeps the inventory (#1380, #1366, #1292, #1284 and the +//! other `[server-thread]` issues). LAN guests and dedicated servers use the +//! same code either way. use super::{ Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index b5d0db5f1..8467b6d3a 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -14,7 +14,7 @@ use horizon_client::{ hub::{HostEvent, HostState, Hub, HubConfig, TickCtx}, playerdata, }, - mobs::Mob, + mobs::{Mob, leash::Holder}, text::Text, }; use horizon_core::geometry::Vec3; @@ -774,9 +774,27 @@ impl Game<'_> { } /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). - fn lan_entities(&self, host_entity: Option, hub: &mut Hub, out: &mut States) { + /// `mob_players` is the guest each mob sees as its player (game/lan_mobs.rs). + fn lan_entities( + &self, + host_entity: Option, + mob_players: &HashMap, + hub: &mut Hub, + out: &mut States, + ) { out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { + // The lead's holder: the player the mob sees (a guest, else the + // host) or another mob. A fence knot isn't an entity here. + let leash = m.extra.leash.and_then(|h| match h { + Holder::Player => mob_players + .get(&m.id) + .and_then(|conn| hub.guest(*conn)) + .map(|g| g.entity_id) + .or(host_entity), + Holder::Mob(id) => Some(id as i32), + Holder::Knot(_) => None, + }); let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); e.position = [m.position.x, m.position.y, m.position.z]; (e.yaw, e.pitch, e.head_yaw) = (m.yaw, m.head_pitch, m.head_yaw); @@ -786,6 +804,7 @@ impl Game<'_> { mob_meta(m, hub, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); + e.leash = leash; } for d in &self.dropped { let stack = hub.stack(&Some(d.stack.clone())); @@ -847,7 +866,7 @@ impl Game<'_> { .filter_map(|g| Some((g.vehicle?, g.entity_id))) .collect(); self.lan_riding(host_entity, &guests, &mut host.hub.riding); - self.lan_entities(host_entity, &mut host.hub, &mut states); + self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states); } else { states.clear(); } @@ -1035,7 +1054,7 @@ impl Game<'_> { return; } // A dedicated server has no host player. - self.lan_entities(None, &mut host.hub, &mut theirs); + self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs); theirs.as_slice() } else { entities diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 6342e921c..f3098408c 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -41,6 +41,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, } } diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 3b73a2e20..895cda08c 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -232,6 +232,9 @@ impl Game<'_> { p.world.game_time = self.world.game_time; p.world.day_time = self.world.day_time; p.world.weather = self.world.weather; + // The game rules and the difficulty are the server's, not a + // level's: natural regeneration holds in every dimension. + p.world.health_rules = self.world.health_rules; // The sculk tables' watched blocks are built once per game. p.world.watched = std::mem::take(&mut self.world.watched); self.swap_level(&mut p); diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 72c8fe885..7b466b3bb 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -297,10 +297,14 @@ impl Game<'_> { } } /// The local player's effects (`tick_mob_effects`), then the potions - /// in flight, which a server without a local player still has. - pub(super) fn tick_effects(&mut self) { + /// in flight, which a server without a local player still has. A frozen + /// tick (`/tick freeze`) leaves the potions where they are + /// (`TickRateManager.isEntityFrozen`); players' effects still run. + pub(super) fn tick_effects(&mut self, running: bool) { self.tick_mob_effects(); - self.tick_thrown_potions(); + if running { + self.tick_thrown_potions(); + } } /// `LivingEntity.tickEffects` (server side) for `self.player`, the local /// player or a guest acting (`as_guest`), then its attribute modifiers diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 19306efd7..dfde08d7f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1874,6 +1874,19 @@ impl Game<'_> { ); } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), + // ClientPacketListener.handleEntityLinkPacket: who holds a mob's + // lead (this player, another player or a mob), for the rope. + C::SetEntityLink(p) => { + let me = self.remote.as_ref().map(|r| r.entity_id); + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) { + use horizon_client::mobs::leash::Holder; + m.extra.leash = match p.dest { + 0 => None, + d if Some(d) == me => Some(Holder::Player), + d => Some(Holder::Mob(d as u32)), + }; + } + } C::MoveVehicle(p) => self.remote_move_vehicle(p.position, p.yaw), // ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3). C::RotateHead(p) => { diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index 7a97416ca..7f64c6bb2 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -306,9 +306,18 @@ impl Game<'_> { } } /// `PhantomSpawner.tick`: tired players under an open night sky draw - /// phantoms. + /// phantoms. A custom spawner ticks only while `spawn_mobs` is on + /// (`ServerChunkCache.tickChunks`), and this one only spawns enemies + /// (`ServerLevel.isSpawningMonsters`: `spawn_monsters` too). Every + /// player of the level counts: the game's own and the hosted ones (a + /// server thread's players are all hosted). pub(super) fn spawn_phantoms(&mut self) { - if !self.ui.rules.bool("spawn_phantoms") || self.dim != Dim::Overworld { + let rules = &self.ui.rules; + if !rules.bool("spawn_mobs") + || !rules.bool("spawn_monsters") + || !rules.bool("spawn_phantoms") + || self.dim != Dim::Overworld + { return; } self.stats.phantom_tick -= 1; @@ -317,16 +326,42 @@ impl Game<'_> { } let r = &mut self.world.random; self.stats.phantom_tick += (60 + r.next_int_bound(60).unwrap_or(0)) * 20; - if self.sky_darken() < 5 || self.spectator() { + if self.sky_darken() < 5 { return; } - let Some(p) = self.player.as_ref() else { - return; - }; + let rest = |s: &Stats| s.get("custom", "minecraft:time_since_rest"); + // `level.players()`: (block position, time since rest) of each player + // who isn't a spectator. + let mut players = Vec::new(); + if let Some(p) = self.player.as_ref() + && !self.spectator() + { + players.push((p.position, rest(&self.stats))); + } + if let Some(host) = self.lan.as_ref() { + let level = self.dim.id(); + for g in host.hub.guests.iter().filter(|g| { + g.placed + && g.dimension == level + && g.game_mode != horizon_client::lan::guest::SPECTATOR + }) { + let since = host.play.get(&g.conn).map_or(0, |p| rest(&p.stats)); + players.push(( + Vec3::new(g.position[0], g.position[1], g.position[2]), + since, + )); + } + } + for (position, since) in players { + self.spawn_phantoms_near(position, since); + } + } + /// One player's turn of `PhantomSpawner.tick`. + fn spawn_phantoms_near(&mut self, position: Vec3, since_rest: i32) { let pos = [ - p.position.x.floor() as i32, - p.position.y.floor() as i32, - p.position.z.floor() as i32, + position.x.floor() as i32, + position.y.floor() as i32, + position.z.floor() as i32, ]; if pos[1] < 63 || !self.can_see_sky(pos) { return; @@ -336,15 +371,15 @@ impl Game<'_> { if r.next_float() * 3.0 >= 2.0 { return; } - let rest = self.stats.get("custom", "minecraft:time_since_rest").max(1); - if r.next_int_bound(rest).unwrap_or(0) < 72000 { + if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 { return; } - let at = [ - pos[0] - 10 + r.next_int_bound(21).unwrap_or(10), - pos[1] + 20 + r.next_int_bound(15).unwrap_or(0), - pos[2] - 10 + r.next_int_bound(21).unwrap_or(10), - ]; + // `playerPos.above(20 + nextInt(15)).east(-10 + nextInt(21)).south(...)`: + // the height is drawn first. + let up = 20 + r.next_int_bound(15).unwrap_or(0); + let east = -10 + r.next_int_bound(21).unwrap_or(10); + let south = -10 + r.next_int_bound(21).unwrap_or(10); + let at = [pos[0] + east, pos[1] + up, pos[2] + south]; if !self .res .facts() diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 9bdb037f7..676fd0adc 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -12,8 +12,8 @@ use horizon_protocol::{ item::Stack, packets::play::{ self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos, - MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, - SetEquipment, SetPassengers, UpdateAttributes, VecDelta, + MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityLink, + SetEntityMotion, SetEquipment, SetPassengers, UpdateAttributes, VecDelta, }, }; @@ -65,6 +65,8 @@ pub struct EntityState { pub precise: bool, /// `Entity.needsSync`: send its changes this tick, due or not. pub needs_sync: bool, + /// `Leashable.getLeashHolder`: the entity holding its lead. + pub leash: Option, } impl EntityState { @@ -87,6 +89,7 @@ impl EntityState { self.attributes.clear(); self.precise = false; self.needs_sync = false; + self.leash = None; } } @@ -219,6 +222,8 @@ struct ServerEntity { /// and the first update after it dismounts is a full position sync. passengers: Vec, was_riding: bool, + /// The lead's holder the clients were told of. + leash: Option, /// The level tick it was last seen in, its place in that tick's list, and /// whether it was added in it (its first update is the next tick's). seen: u32, @@ -262,6 +267,7 @@ impl ServerEntity { teleport_delay: 0, passengers: riding.passengers(e.id).to_vec(), was_riding: false, + leash: e.leash, seen: 0, index: 0, added: true, @@ -314,6 +320,13 @@ impl ServerEntity { if let Some(&vehicle) = riding.vehicle.get(&e.id) { out.push(riding.set_passengers(vehicle)); } + // A leashed entity: who holds its lead. + if let Some(dest) = e.leash { + out.push(play::Clientbound::SetEntityLink(SetEntityLink { + source: e.id, + dest, + })); + } } /// Changes since the last update (ServerEntity.sendChanges): movement and @@ -327,6 +340,14 @@ impl ServerEntity { self.passengers.clear(); self.passengers.extend_from_slice(passengers); } + // Leashable.setLeashedTo / dropLeash: sendToTrackingPlayers at once. + if e.leash != self.leash { + out.push(play::Clientbound::SetEntityLink(SetEntityLink { + source: e.id, + dest: e.leash.unwrap_or(0), + })); + self.leash = e.leash; + } // SynchedEntityData.isDirty: once for every client. let dirty = e.meta != self.meta; let due = self.interval != 0 && self.tick.is_multiple_of(self.interval); @@ -868,6 +889,7 @@ mod tests { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, } } @@ -1132,6 +1154,24 @@ mod tests { assert_eq!(eq.slots, vec![(0, None)]); } + #[test] + fn a_lead_tied_and_untied_reaches_the_clients() { + let link = |out: &[play::Clientbound]| { + out.iter().find_map(|p| match p { + play::Clientbound::SetEntityLink(l) => Some((l.source, l.dest)), + _ => None, + }) + }; + let mut e = state(0.0); + let mut s = added(&e); + changes(&mut s, &e); + e.leash = Some(7); + assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 7))); + assert_eq!(link(&changes(&mut s, &e)), None); + e.leash = None; + assert_eq!(link(&changes(&mut s, &e)), Some((e.id, 0))); + } + /// Two clients at the origin; the chunks they hold. struct Clients { chunks: crate::fast_hash::FxHashSet<(i32, i32)>, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 1330b0ae4..c8f2e980d 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -1564,6 +1564,7 @@ impl Hub { attributes, precise: false, needs_sync: false, + leash: None, } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 4b8bbc897..fdafcbb68 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -435,6 +435,7 @@ fn guests_see_each_other_and_the_world_entities() { attributes: Vec::new(), precise: false, needs_sync: false, + leash: None, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 24eec6a05..23ba00699 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -671,6 +671,11 @@ packet!(SetCursorItem { item: Option => Slot }); packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +packet!( + /// ClientboundSetEntityLinkPacket: the entity holding a leashed entity's + /// lead, 0 when none (Leashable.setDelayedLeashHolderId). + SetEntityLink { source: i32 => Int, dest: i32 => Int } +); packet!( /// ClientboundSetPassengersPacket: a vehicle and every entity riding it. SetPassengers { vehicle: i32 => VarInt, passengers: Vec => List } @@ -1532,6 +1537,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetDisplayObjective(SetDisplayObjective) = SET_DISPLAY_OBJECTIVE, SetEntityData(SetEntityData) = SET_ENTITY_DATA, SetEntityMotion(SetEntityMotion) = SET_ENTITY_MOTION, + SetEntityLink(SetEntityLink) = SET_ENTITY_LINK, SetEquipment(SetEquipment) = SET_EQUIPMENT, SetExperience(SetExperience) = SET_EXPERIENCE, SetHealth(SetHealth) = SET_HEALTH, @@ -2263,6 +2269,7 @@ mod tests { vehicle: 2, passengers: vec![3, 300], }), + Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }), Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, diff --git a/docs/server-levels.md b/docs/server-levels.md index a44f290c4..cc21a52ab 100644 --- a/docs/server-levels.md +++ b/docs/server-levels.md @@ -26,9 +26,10 @@ the other dimensions' levels as `Parked` values and swaps one into place (`enter The packets of a guest are read in its own level's pass (`Hub::tick_level`), so its actions and commands run with its level in place. -The window's own game (`--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the command harness) keeps -one level, which follows its player (`enter_dimension`). LAN guests of a world run that way stay in the -host's dimension. That mode is the escape hatch now, so it gets no multi-level work. +The window's own game (single player's default, `--no-server-thread`, `HORIZON_SERVER_THREAD=0`, and the +command harness) keeps one level, which follows its player (`enter_dimension`). LAN guests of a world run +that way stay in the host's dimension. It is the default again only until the server thread reaches parity +(`--server-thread` or `HORIZON_SERVER_THREAD=1` opts in), so it gets no multi-level work. ## One code path for both diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index de8c78dc3..b3dae9ef4 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -29,6 +29,8 @@ address. The script then checks, from both sides, what a guest's game used to ge cow on fire burns and goes out; then the wither's health drops when it is hurt, the sheep is dyed blue with its wool back and the calf grows up (#1367, #1368, #1370, #1371, #1385, #1390); +- leads: the host and the guest each tie a cow to a lead and untie it: the rope shows on both + sides, held by the player who tied it, and goes on both (#1360); - respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the respawned player is a new entity to the others); the host dies, and on the server thread the guest too; @@ -206,7 +208,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -1225,6 +1227,43 @@ def check_looks(host, guest, out): return seen['later']['guest'] +def check_leads(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + at = (x + 0.5, y, z + 2.5) + + def cow(game): + found = [m for m in game.raw('mobs', 32).get('near', []) if m['kind'] == 'minecraft:cow' + and abs(m['pos'][0] - at[0]) < 1 and abs(m['pos'][2] - at[2]) < 1] + assert found, f'{game.name} sees no cow at {at}' + return found[0] + player('command', command='gamemode survival') + player('command', command=f'summon minecraft:cow {at[0]} {y} {at[2]} {{NoAI:1b}}') + player('command', command='item replace entity @s weapon.mainhand with minecraft:lead') + player.wait(30) + try: + player.raw('look-at', f'{at[0]:.2f}', f'{y + 0.7:.2f}', f'{at[2]:.2f}') + player.raw('mouse', 'right', 'click') + player.wait(20) + tied = {'own': cow(player)['leash'], 'other': cow(other)['leash']} + player.shot(out, 'leads-' + label) + other.shot(out, f'leads-{label}-seen') + # An empty hand unties it (the lead was used up). + player.raw('mouse', 'right', 'click') + player.wait(20) + untied = {'own': cow(player)['leash'], 'other': cow(other)['leash']} + finally: + player('command', command=f'kill @e[type=!minecraft:player,x={at[0]},y={y},z={at[2]},distance=..6]') + player('command', command='clear @s') + result[label] = {'tied': tied, 'untied': untied} + # The other side draws it held by the player who tied it (another player to it). + assert tied['own'] == 'Player' and tied['other'], f"the {label}'s cow on its lead: {tied}" + assert untied == {'own': None, 'other': None}, f"the {label}'s cow untied: {untied}" + return result + + def container_items(game): """The open container's stacks by slot (Horizon's container slots are 300 and up) and its size.""" slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300] @@ -3905,7 +3944,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'contacts': check_contacts, 'absorption': check_absorption, 'breath': check_breath, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater, - 'looks': check_looks} + 'looks': check_looks, + 'leads': check_leads} def run(ctl, out, resources, checks):