Merge origin/main into fix/creative-item-components

Main gained PotionContents on the wire (#1796) in the same two functions
this branch hands to the shared codec. Resolved by keeping the codec and
teaching it the potion: components_tag writes it by its built-in registry
name, and the remote's id lookup asks the built-in registries first, as a
hub's SyncData::id already does. The round-trip test now covers a splash
potion.

Co-Authored-By: Hermes Agent (Nous Research) <noreply@nousresearch.com>
This commit is contained in:
Alexander Krylov
2026-10-25 22:42:28 +03:00
44 changed files with 1380 additions and 167 deletions
+18 -8
View File
@@ -617,9 +617,23 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.head_pitch = pitch;
m.on_ground = flag(tag, "OnGround");
m.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0);
if let Some(h) = float(tag.get("Health")) {
m.health = h as f32;
// LivingEntity.readAdditionalSaveData: the saved attribute bases, then
// the health, the max health when there is none.
if let Some(Tag::List(attrs)) = tag.get("attributes") {
for a in attrs {
let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else {
continue;
};
let v = f64::from_bits(*bits);
match id.as_str() {
"minecraft:max_health" => m.attrs.max_health = v as f32,
"minecraft:movement_speed" => m.attrs.speed = v,
"minecraft:attack_damage" => m.attrs.attack_damage = v as f32,
_ => {}
}
}
}
m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32);
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
// What it holds (equipment.mainhand / offhand), when saved.
if let Some(eq) = tag.get("equipment") {
@@ -735,12 +749,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else {
continue;
};
let v = f64::from_bits(*bits);
match id.as_str() {
"minecraft:max_health" => m.attrs.max_health = v as f32,
"minecraft:movement_speed" => m.attrs.speed = v,
"minecraft:jump_strength" => m.extra.vector[0] = v,
_ => {}
if id == "minecraft:jump_strength" {
m.extra.vector[0] = f64::from_bits(*bits);
}
}
}
+43 -12
View File
@@ -1168,6 +1168,8 @@ struct Game<'a> {
carried: Option<ItemStack>,
craft_grid: Vec<Option<ItemStack>>,
craft_size: usize,
/// The crafting table the 3x3 grid belongs to (`CraftingMenu.access`).
craft_table: Option<[i32; 3]>,
/// A quick craft drag over inventory slots: (button, game slots so far).
inv_drag: Option<(i32, Vec<usize>)>,
/// `AbstractContainerScreen`'s quick craft and skip-release state.
@@ -1837,6 +1839,19 @@ impl Game<'_> {
.is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage))
})
}
/// `LivingEntity.canFreeze`'s armor half: any worn piece in
/// `freeze_immune_wearables`.
pub(crate) fn wears_freeze_immune(&self) -> bool {
let immune = self
.res
.items()
.item_tags
.get("minecraft:freeze_immune_wearables");
self.armor
.iter()
.flatten()
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)))
}
/// What the window decides for its player's body every tick, in frame and
/// on a server alike: the look (Player.travel steers sprint-swimming by
/// the pitch), Auto Jump (LocalPlayer.sendPosition), the slowdown of an
@@ -1863,16 +1878,7 @@ impl Game<'_> {
let leather_boots = self.armor[3]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:leather_boots");
let immune = self
.res
.items()
.item_tags
.get("minecraft:freeze_immune_wearables");
let freeze_immune = self
.armor
.iter()
.flatten()
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
let freeze_immune = self.wears_freeze_immune();
let Some(player) = self.player.as_mut() else {
return;
};
@@ -2173,6 +2179,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(),
@@ -2916,6 +2927,7 @@ impl Game<'_> {
}
if &*name == "minecraft:crafting_table" {
self.craft_size = 3;
self.craft_table = Some(pos);
} else if &*name == "minecraft:ender_chest" {
self.open_ender_chest(key);
self.container_opener_event(key, true);
@@ -4335,7 +4347,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 +4382,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)
}
@@ -5425,6 +5450,7 @@ impl Game<'_> {
}
}
self.craft_size = 2;
self.craft_table = None;
if let Some(key) = self.container.take() {
self.container_opener_event(key, false);
self.post_block_game_event(
@@ -7879,8 +7905,12 @@ impl Game<'_> {
(0..width).all(|i| frame([left[0] + d[0] * i, left[1] + height, left[2] + d[2] * i]));
((3..=21).contains(&height) && top_ok).then_some((left, width, height))
}
/// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal.
/// BaseFireBlock.onPlace: lighting fire inside a frame creates a portal,
/// only in the Overworld and the Nether (`inPortalDimension`).
fn try_light_portal(&mut self, at: [i32; 3]) -> Result<bool> {
if !matches!(self.dim, Dim::Overworld | Dim::Nether) {
return Ok(false);
}
for x_axis in [true, false] {
if let Some((origin, width, height)) = self.portal_shape(at, x_axis) {
let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] };
@@ -11750,6 +11780,7 @@ impl<'a> Game<'a> {
carried: None,
craft_grid: vec![None; 9],
craft_size: 2,
craft_table: None,
inv_drag: None,
tweaks: Default::default(),
inv_clicks: Default::default(),
+6 -2
View File
@@ -1599,8 +1599,12 @@ impl Game<'_> {
if self.screen != Screen::Dead {
return Err("respawn needs the death screen".into());
}
let label =
horizon_client::text::Text::translate("deathScreen.respawn", &[]).plain();
let key = if self.level.hardcore {
"deathScreen.spectate"
} else {
"deathScreen.respawn"
};
let label = horizon_client::text::Text::translate(key, &[]).plain();
let w = widgets::find(&widgets::last(), &label)?;
if !w.enabled {
// DeathScreen enables its buttons after 20 ticks.
@@ -15,6 +15,8 @@ use horizon_world::registry::BlockStateId;
impl Game<'_> {
pub(super) fn tick_block_entities(&mut self) -> Result<()> {
self.tick_mount_menu();
self.tick_craft_table();
self.tick_container_reach();
self.load_entity_types();
if !self.world.block_entities.has_states() {
let states = self.ticking_states();
@@ -13,7 +13,7 @@ use horizon_client::{
use horizon_core::geometry::{Aabb, Vec3};
/// `Entity.boardingCooldown` once a mob leaves its boat.
const BOARDING_COOLDOWN: i32 = 60;
pub(super) const BOARDING_COOLDOWN: i32 = 60;
/// `Player.DEFAULT_VEHICLE_ATTACHMENT`: how far below the seat a player's
/// feet are.
const PLAYER_RIDING_OFFSET: f64 = 0.6;
+3 -1
View File
@@ -99,6 +99,8 @@ pub struct UiState {
/// Death screen cause and when the player died (buttons wait 20 ticks).
pub death_text: Option<Text>,
pub died_at: Option<std::time::Instant>,
/// `LivingEntity.deathTime` of the window's player: ticks since it died.
pub death_time: u32,
}
impl Game<'_> {
@@ -586,7 +588,7 @@ impl Game<'_> {
} else {
let line = Text::translate(
"chat.type.text",
&[Text::literal(PLAYER_NAME), Text::literal(message)],
&[self.player_display_name(), Text::literal(message)],
);
let focused = self.screen == Screen::Chat;
let heard = self.mods.running().then(|| line.plain());
+4 -4
View File
@@ -214,7 +214,7 @@ impl Game<'_> {
}
/// Player.getDisplayName: the name (team-formatted), suggesting a
/// `/tell`, showing the player on hover, inserting the name.
fn player_display_name(&self) -> Text {
pub(super) fn player_display_name(&self) -> Text {
let name = self.acting_player_name().to_owned();
let Some(uuid) = self.lan_acting_uuid else {
return self.target_name(Target::Player);
@@ -2809,7 +2809,7 @@ impl Game<'_> {
let name = match self.command_source.map(|s| s.entity) {
Some(Some(t)) => self.target_name(t),
Some(None) => Text::literal("Server"),
None => Text::literal(self.acting_player_name()),
None => self.player_display_name(),
};
let line = match id {
"say" => Text::translate("chat.type.announcement", &[name, message]),
@@ -2819,14 +2819,14 @@ impl Game<'_> {
// Whispering to yourself: the incoming and outgoing lines.
let out = Text::translate(
"commands.message.display.outgoing",
&[Text::literal(self.acting_player_name()), message.clone()],
&[self.player_display_name(), message.clone()],
)
.with_color(text::GRAY)
.italic();
self.system_message(out);
Text::translate(
"commands.message.display.incoming",
&[Text::literal(self.acting_player_name()), message],
&[self.player_display_name(), message],
)
.with_color(text::GRAY)
.italic()
@@ -606,10 +606,7 @@ impl Game<'_> {
.collect(),
_ => Vec::new(),
},
Some("vehicle") => match entity {
Target::Player => self.riding.map(Target::Mob).into_iter().collect(),
_ => Vec::new(),
},
Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(),
Some("controller") | Some("passengers") => match entity {
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
vec![Target::Player]
@@ -1074,15 +1074,15 @@ impl Game<'_> {
};
let name = self.target_name(target);
if id == "ride.dismount" {
let vehicle = match target {
Target::Player => self.riding.map(Target::Mob),
_ => None,
};
let Some(v) = vehicle else {
let Some(v) = self.ride_vehicle(target) else {
return Err(err("commands.ride.not_riding", &[&name.plain()]));
};
let vehicle_name = self.target_name(v);
self.dismount_mount();
match target {
Target::Player => self.dismount_mount(),
Target::Mob(rider) => self.dismount_mob(rider),
_ => {}
}
self.feedback(Text::translate(
"commands.ride.dismount.success",
&[name, vehicle_name],
@@ -1094,11 +1094,8 @@ impl Game<'_> {
return Ok(0);
};
let vehicle_name = self.target_name(vehicle);
if target == Target::Player && self.riding.is_some() {
let current = self
.riding
.map(Target::Mob)
.map_or_else(Text::empty, |v| self.target_name(v));
if let Some(current) = self.ride_vehicle(target) {
let current = self.target_name(current);
return Err(err(
"commands.ride.already_riding",
&[&name.plain(), &current.plain()],
@@ -1107,22 +1104,42 @@ impl Game<'_> {
if vehicle == Target::Player {
return Err(err("commands.ride.mount.failure.cant_ride_players", &[]));
}
if target == vehicle {
return Err(err("commands.ride.mount.failure.loop", &[]));
// getSelfAndPassengers: the vehicle is the target or rides it.
let mut up = Some(vehicle);
while let Some(v) = up {
if v == target {
return Err(err("commands.ride.mount.failure.loop", &[]));
}
up = self.ride_vehicle(v);
}
// The player can ride mobs that carry a rider.
// Players and mobs can ride mobs.
let Target::Mob(mob_id) = vehicle else {
return Err(err(
"commands.ride.mount.failure.generic",
&[&name.plain(), &vehicle_name.plain()],
));
};
if target != Target::Player || !self.mobs.iter().any(|m| m.id == mob_id && m.alive()) {
let rider = match target {
Target::Mob(id) => Some(id),
_ => None,
};
if !(target == Target::Player || rider.is_some())
|| !self.mobs.iter().any(|m| m.id == mob_id && m.alive())
{
return Err(err(
"commands.ride.mount.failure.generic",
&[&name.plain(), &vehicle_name.plain()],
));
}
if let Some(rider) = rider {
// Entity.startRiding.
self.mount_mob(rider, mob_id);
self.feedback(Text::translate(
"commands.ride.mount.success",
&[name, vehicle_name],
));
return Ok(1);
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) {
m.extra.flag = false;
m.extra.counter = 0;
@@ -1138,6 +1155,47 @@ impl Game<'_> {
Ok(1)
}
/// Entity.getVehicle: the player's mount, or a mob's.
pub(super) fn ride_vehicle(&self, t: Target) -> Option<Target> {
let id = match t {
Target::Player => return self.riding.map(Target::Mob),
Target::Mob(id) => self.mobs.iter().find(|m| m.id == id)?.extra.mount?,
_ => return None,
};
Some(if self.boats.iter().any(|b| b.id == id) {
Target::Boat(id)
} else {
Target::Mob(id)
})
}
/// LivingEntity.stopRiding for a mob: off its vehicle
/// (Entity.removePassenger), then to where the vehicle lets it out
/// (LivingEntity.dismountVehicle).
fn dismount_mob(&mut self, rider: u32) {
let Some(i) = self.mobs.iter().position(|m| m.id == rider) else {
return;
};
let Some(v) = self.mobs[i].extra.mount.take() else {
return;
};
let (width, yaw) = (f64::from(self.mobs[i].width()), self.mobs[i].yaw);
let at = if let Some(b) = self.boats.iter().position(|b| b.id == v) {
self.boat_dismount_target(b, width, yaw)
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == v) {
m.extra.rider = None;
// Entity.getDismountLocationForPassenger: on top of the vehicle.
let p = m.position;
horizon_core::geometry::Vec3::new(p.x, p.y + f64::from(m.height()), p.z)
} else {
self.mobs[i].position
};
let m = &mut self.mobs[i];
m.extra.passenger = false;
m.extra.boarding_cooldown = super::super::boat_passengers::BOARDING_COOLDOWN;
m.position = at;
m.previous = at;
}
// ---- /spreadplayers -----------------------------------------------------------------------
pub(super) fn cmd_spreadplayers(&mut self, ctx: &Context) -> R<i32> {
@@ -1698,7 +1698,26 @@ impl Game<'_> {
targets: targets_guests,
};
let guest_entities = self.lan_guest_entities();
// ThrownEnderpearl.tick: a dead player's pearl is discarded in
// place of its tick while ender_pearls_vanish_on_death is on.
let vanish = self.ui.rules.bool("ender_pearls_vanish_on_death");
let host_dead = self.player_view().is_some_and(|p| !p.alive);
let dead_guests: Vec<u32> = self.lan.as_ref().map_or_else(Vec::new, |h| {
h.hub
.guests
.iter()
.filter(|g| g.dead)
.map(|g| g.conn)
.collect()
});
projectiles.retain_mut(|p| {
if vanish
&& matches!(p.kind, ProjectileKind::EnderPearl)
&& p.owner == Some(Who::Player)
&& p.guest.map_or(host_dead, |c| dead_guests.contains(&c))
{
return false;
}
let mob_shot = !matches!(p.owner, Some(Who::Player));
// A player's arrows, snowballs and eggs meet every player; a
// guest's flies from that guest (Projectile.getOwner), not
+19 -5
View File
@@ -55,8 +55,8 @@ pub(super) struct LanHost {
pub play: HashMap<u32, super::lan_actions::GuestPlay>,
/// Blocks broken this tick (their sound is a level event for the guests).
pub broken: Vec<[f64; 3]>,
/// Hurt and death state of the mobs guests see.
mob_state: HashMap<super::Dim, HashMap<u32, (i32, bool)>>,
/// Hurt time, death and swing time (while swinging) of the mobs guests see.
mob_state: HashMap<super::Dim, HashMap<u32, (i32, bool, Option<i32>)>>,
/// The guest each mob sees as its player, when not the host (game/lan_mobs.rs).
pub mob_players: HashMap<u32, u32>,
/// An integrated server's owner (game/integrated.rs).
@@ -168,11 +168,15 @@ fn mob_meta(
meta.push((9, serializer::FLOAT, Value::Float(health)));
}
defaults.push((9, serializer::FLOAT, Value::Float(1.0)));
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2.
let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1;
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4 (what
// draws a vindicator's axe, a skeleton's drawn bow, a piglin's raised
// weapon).
let flags =
i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1 | i8::from(m.ai.aggressive) << 2;
if flags != 0 {
meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
defaults.push((15, serializer::BYTE, Value::Byte(0)));
// AgeableMob.DATA_BABY_ID (and Zombie's, Piglin's).
if let Some(index) = baby_index(kind) {
if m.is_baby() {
@@ -1193,7 +1197,17 @@ impl Game<'_> {
if dead && !old.is_some_and(|o| o.1) {
host.hub.entity_event(m.id as i32, 3, at);
}
seen.insert(m.id, (m.hurt_time, dead));
// LivingEntity.swing on a server (a melee hit, a thrown potion):
// ClientboundSwingAnimationPacket for the players around. A swing
// started since the last flush, or restarted (its time went back).
let swing = m.ai.swinging.then_some(m.ai.swing_time);
if let Some(time) = swing
&& !dead
&& old.and_then(|o| o.2).is_none_or(|before| time < before)
{
host.hub.swing(m.id as i32, 0, at, None);
}
seen.insert(m.id, (m.hurt_time, dead, swing));
}
host.mob_state.insert(self.dim, seen);
}
+84 -5
View File
@@ -117,6 +117,7 @@ pub(super) struct GuestSwap {
host_command_block: Option<super::command_blocks::CommandBlockScreen>,
host_mount_menu: super::mount_menu::MountMenu,
craft_size: usize,
craft_table: Option<[i32; 3]>,
craft_grid: Vec<Option<ItemStack>>,
container: Option<(i32, i32, i32)>,
mining: Option<Mining>,
@@ -307,6 +308,7 @@ impl Game<'_> {
// The host's crafting grid stays theirs; a crafting table the guest
// opens shows as the 3x3 size.
let craft_size = std::mem::replace(&mut self.craft_size, 2);
let craft_table = self.craft_table.take();
let craft_grid = std::mem::replace(&mut self.craft_grid, vec![None; 9]);
let container = self.container.take();
let mining = std::mem::replace(&mut self.mining, play.mining.take());
@@ -390,6 +392,7 @@ impl Game<'_> {
host_command_block,
host_mount_menu,
craft_size,
craft_table,
craft_grid,
container,
mining,
@@ -445,6 +448,7 @@ impl Game<'_> {
host_command_block,
host_mount_menu,
craft_size,
craft_table,
craft_grid,
container,
mining,
@@ -495,7 +499,10 @@ impl Game<'_> {
// What the action opened: handed to the guest instead of the host.
let opened = self.container.take();
let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3;
let guest_table = std::mem::replace(&mut self.craft_table, craft_table);
let opened_table = (std::mem::replace(&mut self.craft_size, craft_size) == 3)
.then_some(guest_table)
.flatten();
self.craft_grid = craft_grid;
let opened_station = std::mem::replace(&mut self.station, host_station);
let bed = std::mem::replace(&mut self.sleeping, sleeping);
@@ -671,8 +678,8 @@ impl Game<'_> {
if let Some(key) = guest_lectern {
self.lan_open_lectern(host, conn, key);
}
if opened_table {
self.lan_open_crafting(host, conn);
if let Some(pos) = opened_table {
self.lan_open_crafting(host, conn, pos);
}
if let Some(mob) = guest_mount {
self.lan_open_mount(host, conn, mob);
@@ -812,6 +819,31 @@ impl Game<'_> {
}
}
/// `ServerPlayer.tick`'s `stillValid`: a guest's block container closes
/// once the guest is out of reach of its block (a removed block closes it
/// in the hub's `sync_containers`).
fn lan_containers_tick(&mut self, host: &mut LanHost) {
let far: Vec<u32> = host
.hub
.guests
.iter()
.filter(|g| host.hub.here(g))
.filter(|g| {
g.menu.as_ref().is_some_and(|m| {
m.slots.valid(&self.world) && !m.slots.still_valid(&self.world, g, m.pos)
})
})
.map(|g| g.conn)
.collect();
for conn in far {
self.guest_container_closed(host, conn);
host.hub.close_container(conn);
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) {
self.guest_carried_back(host, gi);
}
}
}
/// A packet from a guest that the hub does not handle itself.
pub(super) fn lan_guest_packet(&mut self, host: &mut LanHost, conn: u32, packet: S) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
@@ -1075,7 +1107,20 @@ impl Game<'_> {
}
S::ContainerClick(p) => {
let rules = ItemRules(self.res.items());
let slots = host.hub.guests[gi]
.menu
.as_ref()
.filter(|m| m.window == p.container)
.map(|m| m.slots);
let before = slots.and_then(|s| s.read(&self.world, &host.hub.guests[gi]));
let drops = host.hub.container_click(conn, &p, &mut self.world, &rules);
// A click that changed the container's slots: BlockEntity.setChanged,
// so comparators read it again (a double chest's other half follows).
if let Some(Slots::Block(key) | Slots::Double(key, _)) = slots
&& slots.and_then(|s| s.read(&self.world, &host.hub.guests[gi])) != before
{
self.container_changed(key);
}
self.drop_guest_items(host, gi, drops);
}
S::ContainerClose(p) => {
@@ -1222,11 +1267,29 @@ 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
/// with the inventory it is sent.
fn guest_carried_back(&mut self, host: &mut LanHost, gi: usize) {
pub(super) fn guest_carried_back(&mut self, host: &mut LanHost, gi: usize) {
if let Some(c) = host.hub.guests[gi].carried.take() {
self.lan_place_back(host, gi, vec![c]);
host.hub.send_inventory(gi);
@@ -1561,6 +1624,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
@@ -1601,6 +1666,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;
@@ -1637,6 +1703,11 @@ impl Game<'_> {
border: &self.border,
};
host.hub.respawn(i, spawn, &ctx);
// ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's
// respawned player only watches.
if self.level.hardcore {
host.hub.set_game_mode(conn, SPECTATOR);
}
if let Some(config) = elsewhere {
self.respawn_trip(conn, config);
}
@@ -1668,6 +1739,8 @@ impl Game<'_> {
pub(super) fn tick_guests(&mut self, host: &mut LanHost) {
self.lan_merchant_tick(host);
self.lan_stations_tick(host);
self.lan_tables_tick(host);
self.lan_containers_tick(host);
self.tick_lan_mount_menus(host);
self.announce_guest_advancements(host);
let conns: Vec<u32> = host
@@ -1682,7 +1755,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();
@@ -1930,6 +2007,7 @@ impl Game<'_> {
let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
let freeze_immune = game.wears_freeze_immune();
let Some(player) = game.player.as_mut() else {
return (Vec::new(), None);
};
@@ -1993,6 +2071,7 @@ impl Game<'_> {
// Entity.applyEffectsFromBlocks along those moves: magma, cactus,
// lit campfires and grown sweet berry bushes hurt (#1305).
w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start);
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
+55 -14
View File
@@ -19,8 +19,8 @@ use horizon_protocol::packets::play::{self, Clientbound as C};
pub(super) struct GuestCrafting {
/// The inventory menu; its grid lives in the hub's guest.
inventory: Option<Box<Menu>>,
/// The open crafting table: its window, state id and menu.
table: Option<(i32, i32, Box<Menu>)>,
/// The open crafting table: its window, state id, menu and block.
table: Option<(i32, i32, Box<Menu>, [i32; 3])>,
/// The open furnace's or brewing stand's window and menu (`AbstractFurnaceMenu`,
/// `BrewingStandMenu`); its slots live in the block entity and the hub's
/// container menu keeps the client in sync.
@@ -383,17 +383,17 @@ impl Game<'_> {
host.hub.send_inventory(gi);
placed
} else {
let Some((window, state, mut menu)) = host
let Some((window, state, mut menu, pos)) = host
.play
.get_mut(&conn)
.and_then(|play| play.crafting.table.take_if(|(w, _, _)| *w == p.container))
.and_then(|play| play.crafting.table.take_if(|(w, ..)| *w == p.container))
else {
return;
};
let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| {
menu.place_recipe(env, &id, p.use_max, creative, None)
});
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu, pos));
self.lan_send_table_content(host, conn);
placed
};
@@ -403,7 +403,7 @@ impl Game<'_> {
}
/// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`).
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) {
pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32, pos: [i32; 3]) {
self.lan_crafting_closed(host, conn, None);
self.lan_station_closed(host, conn, None);
// The container it replaces loses its opener.
@@ -413,7 +413,7 @@ impl Game<'_> {
return;
};
let menu = Box::new(Menu::new(Kind::Crafting));
host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu));
host.play.entry(conn).or_default().crafting.table = Some((window, 0, menu, pos));
self.lan_send_table_content(host, conn);
}
@@ -427,31 +427,72 @@ impl Game<'_> {
let Some(play) = host.play.get_mut(&conn) else {
return false;
};
let Some((window, state, mut menu)) = play
let Some((window, state, mut menu, pos)) = play
.crafting
.table
.take_if(|(window, _, _)| *window == p.container)
.take_if(|(window, ..)| *window == p.container)
else {
return false;
};
// A table that is no longer valid takes no clicks (handleContainerClick).
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn)
&& !host.hub.guests[gi].spectator()
&& self.lan_table_valid(&host.hub.guests[gi], pos)
{
self.guest_menu_op(host, gi, &mut menu, |menu, env| {
let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input));
});
}
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu));
host.play.entry(conn).or_default().crafting.table = Some((window, state, menu, pos));
self.lan_send_table_content(host, conn);
true
}
/// `CraftingMenu.stillValid`: the block is still a crafting table and the
/// guest is within reach of it.
fn lan_table_valid(&self, g: &Guest, pos: [i32; 3]) -> bool {
let name = &self
.res
.facts()
.get(self.world.block(pos[0], pos[1], pos[2]))
.name;
&**name == "minecraft:crafting_table" && g.within_block_range(pos, 4.0)
}
/// `ServerPlayer.tick`'s `stillValid`: a guest's crafting table closes
/// once it is gone or out of reach, giving its grid back.
pub(super) fn lan_tables_tick(&mut self, host: &mut LanHost) {
let invalid: Vec<(u32, i32)> = host
.play
.iter()
.filter_map(|(c, p)| p.crafting.table.as_ref().map(|t| (*c, t.0, t.3)))
.filter(|&(c, _, pos)| {
host.hub
.guests
.iter()
.find(|g| g.conn == c)
.is_some_and(|g| host.hub.here(g) && !self.lan_table_valid(g, pos))
})
.map(|(c, window, _)| (c, window))
.collect();
for (conn, window) in invalid {
self.lan_crafting_closed(host, conn, Some(window));
host.hub.send_to(
conn,
&C::ContainerClose(play::ContainerClose { container: window }),
);
if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) {
self.guest_carried_back(host, gi);
}
}
}
/// The whole crafting table menu for the client (`sendAllDataToRemote`).
fn lan_send_table_content(&mut self, host: &mut LanHost, conn: u32) {
let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else {
return;
};
let Some((window, state, menu)) = host
let Some((window, state, menu, _)) = host
.play
.get_mut(&conn)
.and_then(|p| p.crafting.table.as_mut())
@@ -499,9 +540,9 @@ impl Game<'_> {
} else {
match crafting
.table
.take_if(|(w, _, _)| window.is_none_or(|window| *w == window))
.take_if(|(w, ..)| window.is_none_or(|window| *w == window))
{
Some((_, _, menu)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(),
Some((_, _, menu, _)) => (1..10).filter_map(|s| menu.slot(s).cloned()).collect(),
None => return false,
}
};
@@ -527,7 +568,7 @@ impl Game<'_> {
let mut grid: Vec<ItemStack> = g.craft_grid.iter_mut().filter_map(Option::take).collect();
g.craft_result = None;
if let Some(play) = play {
if let Some((_, _, menu)) = play.crafting.table {
if let Some((_, _, menu, _)) = play.crafting.table {
grid.extend((1..10).filter_map(|s| menu.slot(s).cloned()));
}
// A workstation's inputs too.
+2 -26
View File
@@ -588,7 +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);
if !(block && within_reach(g, gs.pos)) {
if !(block && g.within_block_range(gs.pos, 4.0)) {
let window = gs.window;
self.lan_station_closed(host, conn, Some(window));
host.hub.send_to(
@@ -631,16 +631,7 @@ impl Game<'_> {
Some(BlockEntity::Lectern(l)) if l.book.is_some()
);
// Container.stillValidBlockEntity: the interaction range and its buffer.
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;
let pos = [key.0, key.1, key.2];
let near = (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::<f64>()
< reach * reach;
let near = g.within_block_range([key.0, key.1, key.2], 4.0);
if has_book && near {
self.lan_send_lectern(host, conn, false);
} else {
@@ -660,18 +651,3 @@ pub(super) fn station_inputs(gs: &GuestStation) -> Vec<ItemStack> {
.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::<f64>()
< reach * reach
}
+3 -4
View File
@@ -76,15 +76,14 @@ impl Game<'_> {
let pos = ChunkPos::new(chunk.x, chunk.z);
let time = self.world.game_time;
let mut extras: ChunkExtras = chunk.saved.as_deref().cloned().unwrap_or_default();
// A chunk the scheduler hasn't registered yet (one loaded and
// unloaded again before the next tick) still holds its saved ticks:
// `register_chunk_ticks` empties that list once it takes them.
if let Some(t) = self.block_ticks.blocks.chunk(pos) {
extras.block_ticks = t.pack(time);
} else {
extras.block_ticks.clear();
}
if let Some(t) = self.block_ticks.fluids.chunk(pos) {
extras.fluid_ticks = t.pack(time);
} else {
extras.fluid_ticks.clear();
}
extras.last_update = time;
// TheEndGatewayBlockEntity saves its Age (the server copy's).
@@ -27,6 +27,11 @@ impl Game<'_> {
if ready.is_empty() {
return Ok(());
}
// The ticks the marks schedule go to the chunks' containers, which a
// chunk that arrived since the last tick doesn't have yet
// (`LevelChunk.registerTickContainerInLevel` comes before
// `postProcessGeneration`).
self.sync_tick_chunks();
for key in ready {
let Some(chunk) = self.world.chunks.get_mut(&key) else {
continue;
+23 -15
View File
@@ -597,13 +597,19 @@ impl Game<'_> {
))
}
/// A stack to the server (`SetCreativeModeSlot`): the same component
/// patch a Horizon server sends its clients, with the synced registries'
/// ids, so the server's echo doesn't hand back a bare item.
/// patch a Horizon server sends its clients, with the registries' ids, so
/// the server's echo doesn't hand back a bare item.
fn to_network(&self, s: &Option<ItemStack>) -> Option<Stack> {
let r = self.remote.as_ref()?;
horizon_client::lan::guest::stack_to_network(
|name| self.item_id(name),
|registry, name| r.registries.id(registry, name),
// Built-in first, as a hub's `SyncData::id` does: potions are one.
|registry, name| {
r.builtin
.get(registry)
.and_then(|ids| ids.id(name))
.or_else(|| r.registries.id(registry, name))
},
s,
)
}
@@ -1884,15 +1890,6 @@ impl Game<'_> {
}
}
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Rabbit
{
for (index, _, value) in &p.values {
if let (15, Value::Byte(flags)) = (index, value) {
m.no_ai = flags & 1 != 0;
}
}
}
self.remote_mob_data(p.id, &p.values);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Creeper
@@ -3899,8 +3896,14 @@ impl Game<'_> {
}
if reacts {
self.predict_use(&changes, seq);
} else if let Some(stack) = held.as_ref() {
self.predict_item_on_block(stack, &hit);
} else if let Some(stack) = held.as_ref()
&& self.predict_item_on_block(stack, &hit)
{
// Item.useOn succeeded here (InteractionResult.SUCCESS):
// this hand swings and the click ends, so the other hand
// (a shield, a torch) is never tried.
self.with_hand(hand, Game::swing_arm);
return true;
}
if held_block {
let placed = if reacts {
@@ -3930,7 +3933,8 @@ impl Game<'_> {
/// `playSound(player, ...)`: the server sends them to the others only):
/// honeycomb waxing copper, and an axe, hoe or shovel transforming a
/// block (stripping, scraping, removing wax, tilling, making a path).
fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) {
/// Whether the item's use succeeded, which ends the click.
fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) -> bool {
let at = [
f64::from(hit.pos[0]) + 0.5,
f64::from(hit.pos[1]) + 0.5,
@@ -3949,11 +3953,15 @@ impl Game<'_> {
self.audio
.play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0);
}
waxes
} else if let Some((_, sound, _, _, particle)) =
self.block_transform(stack, hit.pos, hit.face)
{
self.transform_particle(&particle, hit.pos);
self.audio.play(&sound, Some(at), 1.0, 1.0);
true
} else {
false
}
}
@@ -23,6 +23,14 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
// animation follow it.
(9, Value::Float(health)) => m.health = *health,
// Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2, aggressive 4.
// Mob.isAggressive draws the illagers' and skeletons' attack
// poses and the vindicator's axe.
(15, Value::Byte(flags)) => {
m.no_ai = flags & 1 != 0;
m.extra.left_handed = flags & 2 != 0;
m.ai.aggressive = flags & 4 != 0;
}
(i, Value::Bool(b)) if Some(i) == baby => m.extra.age = if *b { -1 } else { 0 },
_ => {}
}
@@ -178,6 +186,19 @@ mod tests {
assert_eq!(m.fire_ticks, 0);
}
#[test]
fn mob_flags_turn_aggression_on_and_off() {
let Some(mut m) = mob("minecraft:vindicator") else {
return;
};
apply(&mut m, &[(15, s::BYTE, Value::Byte(4 | 2))]);
assert!(m.ai.aggressive && m.extra.left_handed && !m.no_ai);
assert!(horizon_client::mobs::illager::shows_item(&m));
apply(&mut m, &[(15, s::BYTE, Value::Byte(0))]);
assert!(!m.ai.aggressive && !m.extra.left_handed);
assert!(!horizon_client::mobs::illager::shows_item(&m));
}
#[test]
fn a_villager_takes_its_type_profession_and_level() {
let Some(mut m) = mob("minecraft:villager") else {
@@ -332,6 +332,7 @@ impl Game<'_> {
return;
}
self.load_scoreboard();
host.hub.teams.clone_from(&self.score.board.teams);
let view = horizon_client::lan::scoreboard::View::of(&self.score.board);
for g in host.hub.guests.iter_mut().filter(|g| g.placed) {
if g.scoreboard != view {
+22 -5
View File
@@ -2,6 +2,7 @@
use super::{Game, Screen};
use horizon_client::{
Result,
command::args::GameMode,
hud::{HudBatch, rgba},
text::{self, Text},
ui,
@@ -81,9 +82,15 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
(x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"),
]
}
fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] {
/// DeathScreen.init: a hardcore player can only spectate.
fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8); 2] {
let respawn = if hardcore {
"deathScreen.spectate"
} else {
"deathScreen.respawn"
};
[
(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0),
(w / 2.0 - 100.0, h / 4.0 + 72.0, respawn, 0),
(
w / 2.0 - 100.0,
h / 4.0 + 96.0,
@@ -223,7 +230,12 @@ impl Game<'_> {
),
);
}
let title = Text::translate("deathScreen.title", &[]);
let title = if self.level.hardcore {
"deathScreen.title.hardcore"
} else {
"deathScreen.title"
};
let title = Text::translate(title, &[]);
let tw = atlas.font.width_text(&title);
ui::text_scaled(
batch,
@@ -258,7 +270,7 @@ impl Game<'_> {
.ui
.died_at
.is_none_or(|t| t.elapsed().as_millis() >= 1000);
for (x, y, key, _) in death_buttons(w, h) {
for (x, y, key, _) in death_buttons(w, h, self.level.hardcore) {
let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0);
ui::button(
batch,
@@ -286,7 +298,7 @@ impl Game<'_> {
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let hit = death_buttons(b.width, b.height)
let hit = death_buttons(b.width, b.height, self.level.hardcore)
.into_iter()
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
.map(|d| d.3);
@@ -330,6 +342,11 @@ impl Game<'_> {
Some(1) => self.close_world()?,
_ => {}
}
// ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's
// respawned player only watches.
if hit == Some(0) && self.remote.is_none() && self.level.hardcore {
self.set_mode(GameMode::Spectator);
}
if hit.is_some() {
self.audio.play_button_click();
}
+1 -1
View File
@@ -78,7 +78,7 @@ impl Game<'_> {
let Some(g) = host.hub.guest(conn) else {
return;
};
let near = super::lan_stations::within_reach(g, p.pos);
let near = g.within_block_range(p.pos, 4.0);
let Some(play) = host.play.get_mut(&conn) else {
return;
};
+46
View File
@@ -127,6 +127,52 @@ impl Game<'_> {
None => vec![own],
}
}
/// `Container.stillValidBlockEntity`: the open block container closes once
/// the player's eyes are out of reach of any of its blocks (a 4-block buffer).
pub(super) fn tick_container_reach(&mut self) {
// A server's menu ends when the server closes it.
if self.remote.is_some() {
return;
}
let Some(eye) = self.eye_position() else {
return;
};
if self
.container
.is_none_or(|k| k.1 == super::minecarts::CART_KEY_Y)
{
return;
}
let range = self.reach() + 4.0;
let near = self.container_parts().iter().all(|&((x, y, z), _)| {
horizon_client::lan::guest::within_block_range(eye, range, [x, y, z])
});
if !near {
self.close_container();
self.screen = super::Screen::Playing;
self.capture(true);
}
}
/// `CraftingMenu.stillValid`: the open crafting table closes once its
/// block is no longer a crafting table or the player's eyes are out of
/// reach (a 4-block buffer).
pub(super) fn tick_craft_table(&mut self) {
// A server's menu ends when the server closes it.
if self.remote.is_some() || self.craft_size != 3 {
return;
}
let (Some(pos), Some(eye)) = (self.craft_table, self.eye_position()) else {
return;
};
let state = self.world.block(pos[0], pos[1], pos[2]);
let table = &*self.res.facts().get(state).name == "minecraft:crafting_table";
let range = self.reach() + 4.0;
if !(table && horizon_client::lan::guest::within_block_range(eye, range, pos)) {
self.close_container();
self.screen = super::Screen::Playing;
self.capture(true);
}
}
/// The number of slots of the open container.
pub(super) fn container_size(&self) -> usize {
self.container_parts().iter().map(|p| p.1).sum()
+40 -2
View File
@@ -106,6 +106,16 @@ fn components_tag(s: &Stack, builtin: &Builtin, synced: &Dynamic) -> Option<Tag>
("mob_factor", Tag::Float(v[5].to_bits())),
]),
Component::Profile(p) => profile_tag(p),
// PotionContents' NBT: the potion by name and the custom colour.
Component::Potion { potion, color, .. } => {
let potion = potion.and_then(|id| builtin.get("minecraft:potion")?.name(id));
Tag::compound(
potion
.map(|name| ("potion", Tag::String(name.into())))
.into_iter()
.chain(color.map(|c| ("custom_color", Tag::Int(c)))),
)
}
// ItemStackTemplate.CODEC: id, count and components.
Component::Stacks(stacks) => Tag::List(
stacks
@@ -206,6 +216,7 @@ mod tests {
(component::DAMAGE, "minecraft:damage"),
(component::CUSTOM_NAME, "minecraft:custom_name"),
(component::ENCHANTMENTS, "minecraft:enchantments"),
(component::POTION_CONTENTS, "minecraft:potion_contents"),
(component::REPAIR_COST, "minecraft:repair_cost"),
(
component::STORED_ENCHANTMENTS,
@@ -220,12 +231,20 @@ mod tests {
registries: [
(
"minecraft:item".to_owned(),
Ids::from_names(names(&["minecraft:air", "minecraft:diamond_chestplate"])),
Ids::from_names(names(&[
"minecraft:air",
"minecraft:diamond_chestplate",
"minecraft:splash_potion",
])),
),
(
"minecraft:data_component_type".to_owned(),
Ids::from_names(components),
),
(
"minecraft:potion".to_owned(),
Ids::from_names(names(&["minecraft:water", "minecraft:swiftness"])),
),
]
.into(),
};
@@ -256,6 +275,12 @@ mod tests {
d.repair_cost = 9;
d.custom_name = Some("Keeper".to_owned());
d.trim = Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")));
let id = |registry: &str, name: &str| {
builtin
.get(registry)
.and_then(|ids| ids.id(name))
.or_else(|| dynamic.id(registry, name))
};
let wire = crate::lan::guest::stack_to_network(
|name| {
builtin
@@ -263,7 +288,7 @@ mod tests {
.and_then(|i| i.id(name))
.unwrap_or(0)
},
|registry, name| dynamic.id(registry, name),
id,
&Some(stack.clone()),
)
.unwrap();
@@ -282,5 +307,18 @@ mod tests {
d.trim,
Some((Arc::from("minecraft:gold"), Arc::from("minecraft:sentry")))
);
// PotionContents: the potion is a built-in registry, as a hub's
// `SyncData::id` treats it, so the id has to come from there.
let potion = ItemStack::new("minecraft:splash_potion", 1).with_potion("swiftness");
let wire = crate::lan::guest::stack_to_network(
|name| id("minecraft:item", name).unwrap_or(0),
id,
&Some(potion),
)
.unwrap();
assert_eq!(
from_network(&wire, &builtin, &dynamic).potion(),
Some("minecraft:swiftness")
);
}
}
@@ -343,7 +343,21 @@ impl Hub {
if !window_ok || self.guests[i].spectator() {
return Vec::new();
}
// A menu that is no longer valid takes no clicks.
if let Some(m) = self.guests[i].menu.as_ref().filter(|_| in_menu)
&& !m.slots.still_valid(world, &self.guests[i], m.pos)
{
return Vec::new();
}
let source = self.guests[i].menu.as_ref().map(|m| m.slots);
let shulker_box = self
.sync
.builtin
.get("minecraft:menu")
.and_then(|m| m.id("minecraft:shulker_box"));
let shulker = in_menu
&& shulker_box.is_some()
&& self.guests[i].menu.as_ref().map(|m| m.kind) == shulker_box;
let mut drag = if in_menu {
self.guests[i].menu.as_mut().and_then(|m| m.drag.take())
} else {
@@ -357,6 +371,7 @@ impl Hub {
let mut view = View {
guest,
container: items.as_deref_mut(),
shulker,
};
let (drops, changed) = menu::click(
&mut view,
+60
View File
@@ -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,
@@ -404,6 +407,17 @@ impl Guest {
pub fn eye_height(&self) -> f64 {
if self.sneaking { 1.27 } else { 1.62 }
}
/// `Player.isWithinBlockInteractionRange(pos, buffer)` for the guest:
/// its block interaction range is 4.5, 5 in creative.
pub fn within_block_range(&self, pos: [i32; 3], buffer: f64) -> bool {
let eye = [
self.position[0],
self.position[1] + self.eye_height(),
self.position[2],
];
let range = if self.creative() { 5.0 } else { 4.5 };
within_block_range(eye, range + buffer, pos)
}
/// The inventory menu's 46 slots (ServerPlayer.inventoryMenu): 0 crafting
/// result, 1..=4 crafting grid, 5..=8 armor, 9..=35 main, 36..=44 hotbar,
/// 45 off hand.
@@ -521,6 +535,22 @@ fn network_stack(
horizon_protocol::item::Component::Int(i32::from(mode)),
));
}
// PotionContents: the potion by its `minecraft:potion` id.
if let Some(id) = (d.potion.as_deref()).and_then(|potion| {
synced_id(
"minecraft:potion",
&horizon_world::datafix::dynamic::namespaced(potion),
)
}) {
stack.added.push((
horizon_protocol::item::component::POTION_CONTENTS,
horizon_protocol::item::Component::Potion {
potion: Some(id),
color: None,
rest: Vec::new(),
},
));
}
// A loaded crossbow's ammunition.
if !d.charged.is_empty() {
let charged = d
@@ -568,11 +598,41 @@ fn network_stack(
Some(stack)
}
/// `Player.isWithinBlockInteractionRange`: `eye` closer than `range` to the
/// box of the block at `pos` (`AABB.distanceToSqr`).
pub fn within_block_range(eye: [f64; 3], range: f64, pos: [i32; 3]) -> bool {
(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::<f64>()
< range * range
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_protocol::item::{Component, component};
#[test]
fn potions_go_as_potion_registry_ids() {
let synced_id = |registry: &str, name: &str| match (registry, name) {
("minecraft:potion", "minecraft:swiftness") => Some(14),
_ => None,
};
let potion = ItemStack::new("minecraft:splash_potion", 1).with_potion("swiftness");
let stack = stack_to_network(|_| 7, synced_id, &Some(potion)).unwrap();
assert_eq!(
stack.component(component::POTION_CONTENTS),
Some(&Component::Potion {
potion: Some(14),
color: None,
rest: Vec::new(),
})
);
}
#[test]
fn trims_go_as_synced_registry_references() {
let mut chestplate = ItemStack::new("minecraft:diamond_chestplate", 1);
+22
View File
@@ -149,6 +149,9 @@ pub struct Hub {
pub singleplayer_owner: Option<u128>,
/// Who rides what, set by the game before each tick.
pub riding: super::entity::Riding,
/// The scoreboard's teams, set by the game each tick, for players'
/// display names.
pub teams: Vec<crate::scoreboard::Team>,
last_clock: i64,
last_rate: f32,
ticking: (f32, bool),
@@ -206,6 +209,24 @@ pub fn display_name(uuid: u128, name: &str) -> Tag {
])
}
impl Hub {
/// Player.getDisplayName: the name formatted for the player's team
/// (PlayerTeam.formatNameForTeam), suggesting `/tell NAME `, showing the
/// player on hover and inserting the name.
pub fn player_display_name(&self, uuid: u128, name: &str) -> Tag {
let Some(team) = self.teams.iter().find(|t| t.players.contains(name)) else {
return display_name(uuid, name);
};
let mut c = team.formatted_name_comp(&crate::scoreboard::literal(name));
c["click_event"] =
serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")});
c["hover_event"] = serde_json::json!({"action": "show_entity", "id": "minecraft:player",
"uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name});
c["insertion"] = name.into();
crate::scoreboard::component_tag(&c)
}
}
/// A yellow translation of player names (`multiplayer.player.joined`).
fn yellow_names(key: &str, names: Vec<Tag>) -> Tag {
Tag::compound([
@@ -315,6 +336,7 @@ impl Hub {
entity_types: Default::default(),
entities: Default::default(),
entity_out: Vec::new(),
teams: Vec::new(),
}
}
+6 -6
View File
@@ -2,7 +2,7 @@
//! handle it: chat sessions validated against the services' keys, signed
//! messages checked link by link, the acknowledged window, and messages
//! relayed with each connection's numbering and signature cache.
use super::{HostEvent, Hub, display_name};
use super::{HostEvent, Hub};
use horizon_protocol::{
packets::play::{self, Clientbound as C},
secure_chat::{self, Body, Chain, ChatSession, DecodeError, ProfileKey, Signature, Unpacked},
@@ -214,7 +214,7 @@ impl Hub {
}
let bound = play::ChatTypeBound {
chat_type: self.chat_type,
name: display_name(uuid, &name),
name: self.player_display_name(uuid, &name),
target: None,
};
let line = format!("<{name}> {}", message.content);
@@ -427,7 +427,7 @@ impl Hub {
let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone());
let bound = play::ChatTypeBound {
chat_type: self.chat_type_id(chat_type),
name: display_name(uuid, &name),
name: self.player_display_name(uuid, &name),
target: None,
};
let line = match chat_type {
@@ -467,15 +467,15 @@ impl Hub {
self.chat_type_id("msg_command_incoming"),
);
for &t in targets {
let target = display_name(self.guests[t].uuid, &self.guests[t].name);
let target = self.player_display_name(self.guests[t].uuid, &self.guests[t].name);
let out = play::ChatTypeBound {
chat_type: outgoing,
name: display_name(uuid, &name),
name: self.player_display_name(uuid, &name),
target: Some(target),
};
let inc = play::ChatTypeBound {
chat_type: incoming,
name: display_name(uuid, &name),
name: self.player_display_name(uuid, &name),
target: None,
};
match &message {
+75 -13
View File
@@ -64,6 +64,19 @@ impl Slots {
.iter()
.all(|k| world.block_entities.contains_key(k))
}
/// `Container.stillValid` for the guest: the block entities are there
/// and the guest is within reach of each (`stillValidBlockEntity`). The
/// ender chest's block is `at` (`PlayerEnderChestContainer.activeChest`).
pub fn still_valid(self, world: &World, guest: &Guest, at: Option<(i32, i32, i32)>) -> bool {
let blocks = match self {
Slots::Ender => at.into_iter().collect(),
_ => self.halves(),
};
self.valid(world)
&& blocks
.iter()
.all(|k| guest.within_block_range([k.0, k.1, k.2], 4.0))
}
/// Container slot `n`.
pub fn get(self, world: &World, guest: &Guest, mut n: usize) -> Option<ItemStack> {
if self == Slots::Ender {
@@ -111,6 +124,8 @@ pub struct View<'a> {
pub guest: &'a mut Guest,
/// The container's slots, or None for the inventory menu.
pub container: Option<&'a mut [Option<ItemStack>]>,
/// The container is a shulker box (`ShulkerBoxSlot`).
pub shulker: bool,
}
impl View<'_> {
@@ -153,6 +168,12 @@ impl View<'_> {
if self.container.is_none() && (5..=8).contains(&i) {
return rules.armor_index(&stack.item) == Some(i - 5);
}
if self.shulker
&& self.container.as_ref().is_some_and(|c| i < c.len())
&& !crate::menu::fits_inside_container_items(stack)
{
return false;
}
self.enabled(i)
}
fn slot_max(&self, i: usize, stack: &ItemStack, rules: &dyn Rules) -> u32 {
@@ -665,6 +686,24 @@ mod tests {
)
}
/// The prepared resources' items, or None (the test is skipped) without them.
fn rules() -> Option<ItemRules> {
let root = std::env::var_os("HORIZON_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION)
});
if !root.join("items.json").exists() {
eprintln!("skipping resource-backed menu check: {}", root.display());
return None;
}
let registry = horizon_world::level::data::load_registry(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, &registry).unwrap();
Some(ItemRules(Items::load(&root, &registry, &facts).unwrap()))
}
fn contents(stack: &Option<ItemStack>) -> Vec<(String, u32)> {
let inside = stack.as_ref().and_then(|s| s.data());
inside.map_or(Vec::new(), |d| {
@@ -680,20 +719,9 @@ mod tests {
/// slot; a stack clicked onto a bundle goes in, as far as it fits.
#[test]
fn guest_chest_clicks_fill_and_empty_bundles() {
let root = std::env::var_os("HORIZON_RESOURCES")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| {
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client")
.join(horizon_core::VANILLA_VERSION)
});
if !root.join("items.json").exists() {
eprintln!("skipping resource-backed bundle check: {}", root.display());
let Some(rules) = rules() else {
return;
}
let registry = horizon_world::level::data::load_registry(&root).unwrap();
let facts = crate::blocks::BlockFacts::load(&root, &registry).unwrap();
let rules = ItemRules(Items::load(&root, &registry, &facts).unwrap());
};
let mut g = guest();
let mut chest = vec![
Some(ItemStack::new("minecraft:stone", 48)),
@@ -704,6 +732,7 @@ mod tests {
let mut view = View {
guest: &mut g,
container: Some(&mut chest),
shulker: false,
};
view.guest.carried = Some(ItemStack::new("minecraft:bundle", 1));
// Left click with the bundle: the stone goes in.
@@ -736,4 +765,37 @@ mod tests {
);
assert_eq!(contents(&view.get(2)), []);
}
#[test]
fn guest_shulker_box_menu_refuses_shulker_boxes() {
let Some(rules) = rules() else {
return;
};
for shulker in [true, false] {
let mut g = guest();
let mut container = vec![None; 27];
let mut drag = None;
let mut view = View {
guest: &mut g,
container: Some(&mut container),
shulker,
};
// Carried onto an empty slot, shift-clicked from the hotbar
// (menu slot 27 + 27) and swapped in with the number key 1.
view.guest.carried = Some(ItemStack::new("minecraft:red_shulker_box", 1));
click(&mut view, &mut drag, 0, 0, input::PICKUP, &rules);
assert_eq!(view.get(0).is_none(), shulker);
view.guest.carried = None;
view.guest.inventory[0] = Some(ItemStack::new("minecraft:shulker_box", 1));
click(&mut view, &mut drag, 54, 0, input::QUICK_MOVE, &rules);
assert_eq!(view.guest.inventory[0].is_some(), shulker);
view.guest.inventory[0] = Some(ItemStack::new("minecraft:blue_shulker_box", 1));
click(&mut view, &mut drag, 5, 0, input::SWAP, &rules);
assert_eq!(view.get(5).is_none(), shulker);
// Anything else goes in.
view.guest.carried = Some(ItemStack::new("minecraft:diamond", 1));
click(&mut view, &mut drag, 9, 0, input::PICKUP, &rules);
assert!(view.get(9).is_some());
}
}
}
+7 -6
View File
@@ -247,6 +247,12 @@ pub fn beacon_required_levels(effect: Option<&str>) -> i32 {
.map_or(i32::MAX, |i| i as i32 + 1)
}
/// `Item.canFitInsideContainerItems` (`ShulkerBoxSlot.mayPlace`): shulker
/// boxes cannot nest.
pub fn fits_inside_container_items(stack: &ItemStack) -> bool {
!stack.item.ends_with("shulker_box")
}
/// The containers a menu spans.
const PLAYER: usize = 0;
const MAIN: usize = 1;
@@ -1210,11 +1216,6 @@ impl Menu {
env.items.get(&stack.item).is_some_and(|i| i.fuel.is_some())
}
/// `Item.canFitInsideContainerItems`: shulker boxes cannot nest.
fn fits_inside(stack: &ItemStack) -> bool {
!(stack.item.ends_with("shulker_box"))
}
// ---- Slot ----
fn may_place(&self, env: &Env, s: usize, stack: &ItemStack) -> bool {
@@ -1247,7 +1248,7 @@ impl Menu {
.as_deref()
.is_some_and(|m| i.equip_allowed.as_ref().is_none_or(|a| a.contains(m)))
}),
Role::Shulker => Self::fits_inside(stack),
Role::Shulker => fits_inside_container_items(stack),
Role::Fuel => Self::is_fuel(env, stack) || Self::is_bucket(stack),
Role::Output | Role::CraftResult | Role::Inert => false,
Role::CrafterIn => self.data.get(self.slots[s].index) != Some(&1),
+21 -4
View File
@@ -1083,11 +1083,26 @@ impl MotionWorld<'_, '_, '_> {
}
/// What `applyEffectsFromBlocks` does to a server's player along the
/// moves its client sent since `from` (in its history): the damage of
/// magma, cactus, lit campfires and grown sweet berry bushes. Its client
/// moves it, so the slowing and the rest are the client's.
/// magma, cactus, lit campfires and grown sweet berry bushes, and powder
/// snow's FREEZE, then `LivingEntity.aiStep`'s freezing and its damage.
/// Its client moves it, so the slowing and the rest are the client's.
pub fn server_block_damage(&mut self, from: Vec3) -> Result<()> {
self.player.old_position = from;
self.effects_from_blocks(true)
// Entity.baseTick
self.player.was_in_powder_snow = self.player.in_powder_snow;
self.player.in_powder_snow = false;
self.effects_from_blocks(true)?;
// LivingEntity.aiStep "freezing" (server).
if !self.player.in_powder_snow || !self.player.can_freeze() {
self.player.ticks_frozen = (self.player.ticks_frozen - 2).max(0);
}
if self.player.health.tick_count % 40 == 0
&& self.player.is_fully_frozen()
&& self.player.can_freeze()
{
self.freeze_damage()?;
}
Ok(())
}
fn effects_from_blocks(&mut self, damage_only: bool) -> Result<()> {
use horizon_world::entity_move::MovementRecord;
@@ -1191,7 +1206,7 @@ impl MotionWorld<'_, '_, '_> {
groups += 1;
last_step = step;
}
if groups == 1 {
if groups == 1 && !damage_only {
// A later group finds the fire already out.
self.player.powder_snow_entered.push(p);
}
@@ -1316,6 +1331,8 @@ impl MotionWorld<'_, '_, '_> {
"minecraft:sweet_berry_bush" if damage_only => {
self.sweet_berry_bush_damage(state)?;
}
// PowderSnowBlock.entityInside's FREEZE.
"minecraft:powder_snow" if damage_only => entered.push((step, p)),
_ => {}
}
if damage_only {
+90
View File
@@ -35,6 +35,7 @@ pub mod component {
pub const MAP_ID: i32 = 48;
pub const MAP_POST_PROCESSING: i32 = 50;
pub const CHARGED_PROJECTILES: i32 = 51;
pub const POTION_CONTENTS: i32 = 53;
pub const WRITABLE_BOOK_CONTENT: i32 = 56;
pub const WRITTEN_BOOK_CONTENT: i32 = 57;
pub const TRIM: i32 = 58;
@@ -65,6 +66,13 @@ pub enum Component {
Lore(Vec<Tag>),
Enchantments(Vec<(i32, i32)>),
AttackRange([f32; 6]),
/// `PotionContents`: the potion's `minecraft:potion` id and the custom
/// colour; the custom effects and name stay their encoded bytes.
Potion {
potion: Option<i32>,
color: Option<i32>,
rest: Vec<u8>,
},
Profile(Profile),
CustomModelData {
floats: Vec<f32>,
@@ -162,6 +170,22 @@ impl Component {
.collect::<Result<_>>()?,
)
}
POTION_CONTENTS => {
let potion = if r.bool()? { Some(r.varint()?) } else { None };
let color = if r.bool()? { Some(r.i32()?) } else { None };
let start = r.position();
skip::potion_effects_and_name(r)?;
// No custom effects and no name: an empty tail.
let rest = match r.since(start) {
[0, 0] => Vec::new(),
bytes => bytes.to_vec(),
};
Self::Potion {
potion,
color,
rest,
}
}
ATTACK_RANGE => {
let mut values = [0.0f32; 6];
for v in &mut values {
@@ -283,6 +307,27 @@ impl Component {
}
}
Self::AttackRange(values) => values.iter().for_each(|v| w.f32(*v)),
Self::Potion {
potion,
color,
rest,
} => {
w.bool(potion.is_some());
if let Some(id) = potion {
w.varint(*id);
}
w.bool(color.is_some());
if let Some(color) = color {
w.i32(*color);
}
// An empty tail is no custom effects and no name.
if rest.is_empty() {
w.varint(0);
w.bool(false);
} else {
w.bytes(rest);
}
}
Self::Profile(p) => {
w.u8(0);
w.bool(p.name.is_some());
@@ -532,6 +577,51 @@ mod tests {
assert_eq!(r.remaining(), 0);
}
#[test]
fn potion_contents_round_trip() {
let mut arrow = Stack::new(7, 3);
arrow.added.push((
component::POTION_CONTENTS,
Component::Potion {
potion: Some(31),
color: None,
rest: Vec::new(),
},
));
round::<Option<Stack>, Slot>(Some(arrow));
// A custom colour, one custom effect (speed II for 600 ticks, shown,
// no hidden effect) and a custom name survive as they came.
let mut w = Writer::new();
w.bool(false);
w.bool(true);
w.i32(0x00FF_8800);
w.varint(1);
for v in [1, 1, 600] {
w.varint(v);
}
for b in [false, true, true, false] {
w.bool(b);
}
w.bool(true);
w.string("Tea");
let mut r = Reader::new(&w.data);
let read = Component::read(component::POTION_CONTENTS, &mut r).unwrap();
assert_eq!(r.remaining(), 0);
let Component::Potion {
potion,
color,
rest,
} = &read
else {
panic!("{read:?}");
};
assert_eq!((*potion, *color), (None, Some(0x00FF_8800)));
assert!(!rest.is_empty());
let mut again = Writer::new();
read.write(component::POTION_CONTENTS, &mut again);
assert_eq!(again.data, w.data);
}
#[test]
fn stacks_round_trip() {
round::<Option<Stack>, Slot>(None);
+3 -5
View File
@@ -87,7 +87,6 @@ pub(super) fn component(kind: i32, r: &mut Reader) -> Result<()> {
}
// BundleContents: templates.
52 => list(r, template),
53 => potion_contents(r),
// SuspiciousStewEffects: effect, duration.
55 => list(r, |r| {
varint(r)?;
@@ -410,10 +409,9 @@ fn kinetic_weapon(r: &mut Reader) -> Result<()> {
optional(r, sound)?;
optional(r, sound)
}
/// PotionContents: potion, customColor, customEffects, customName.
fn potion_contents(r: &mut Reader) -> Result<()> {
optional(r, varint)?;
optional(r, i32)?;
/// PotionContents' customEffects and customName (`Component::read` reads
/// the potion and colour before them).
pub(super) fn potion_effects_and_name(r: &mut Reader) -> Result<()> {
list(r, mob_effect)?;
optional(r, string)
}
+11 -1
View File
@@ -849,7 +849,17 @@ mod tests {
let first = lock(&dir).unwrap();
assert!(lock(&dir).unwrap_err().contains("already running"));
drop(first);
lock(&dir).unwrap();
// A process another test spawns holds a copy of the lock's descriptor between its fork and exec:
// the lock comes back once that child has exec'd.
let mut again = lock(&dir);
for _ in 0..50 {
if again.is_ok() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(20));
again = lock(&dir);
}
again.unwrap();
std::fs::remove_dir_all(&dir).unwrap();
}
}
@@ -23,6 +23,7 @@ use horizon_core::{
pub use library::MaterialRuleLibrary;
pub use noise::MaterialNoiseSources;
use rule::CompiledRule;
pub use rule::SurfaceVariants;
pub use rule::{MaterialRule, MaterialRuleError};
use std::{
collections::{BTreeMap, BTreeSet},
@@ -299,7 +300,81 @@ enum Kind<R: RandomSource> {
},
Not(Box<Compiled<R>>),
}
/// What a specialised rule may assume about every position it is applied to
/// (`CompiledRule::specialize`): its y lies in `low..=high`, and whether it is
/// at or above the column's preliminary surface level, when known.
#[derive(Clone, Copy, Debug)]
pub struct Facts {
pub low: i32,
pub high: i32,
pub above_surface: Option<bool>,
}
impl<R: RandomSource> Clone for Kind<R>
where
R::Positional: Clone,
{
fn clone(&self) -> Self {
match self {
Self::Simple(condition) => Self::Simple(condition.clone()),
Self::Biome(names) => Self::Biome(names.clone()),
Self::Constant(value) => Self::Constant(*value),
Self::Noise { sampler, min, max } => Self::Noise {
sampler: *sampler,
min: *min,
max: *max,
},
Self::Gradient { low, high, random } => Self::Gradient {
low: *low,
high: *high,
random: random.clone(),
},
Self::Not(child) => Self::Not(child.clone()),
}
}
}
impl<R: RandomSource> Clone for Compiled<R>
where
R::Positional: Clone,
{
fn clone(&self) -> Self {
Self {
kind: self.kind.clone(),
revision: self.revision,
result: self.result,
}
}
}
impl<R: RandomSource> Compiled<R> {
/// The value `facts` decide for this condition at every position they
/// cover. Conditions read the position and the world, never change them,
/// so one decided in advance gives what testing it would.
fn decided(&self, facts: Facts) -> Option<bool> {
match &self.kind {
Kind::Constant(value) => Some(*value),
Kind::Simple(MaterialCondition::AbovePreliminarySurface) => facts.above_surface,
Kind::Gradient { low, high, .. } => {
if facts.high <= *low {
Some(true)
} else if facts.low >= *high {
Some(false)
} else {
None
}
}
Kind::Not(child) => child.decided(facts).map(|value| !value),
_ => None,
}
}
/// The vertical gradients' bounds, and whether the preliminary surface
/// is asked for.
fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) {
match &self.kind {
Kind::Gradient { low, high, .. } => gradients.push((*low, *high)),
Kind::Simple(MaterialCondition::AbovePreliminarySurface) => *surface = true,
Kind::Not(child) => child.inputs(gradients, surface),
_ => {}
}
}
fn constant_result(&self) -> Option<bool> {
match &self.kind {
Kind::Constant(value) => Some(*value),
@@ -1,5 +1,7 @@
//! Compiled material rule composition, sharing the condition worker's context.
use super::{Compiled, Context, MaterialCondition, MaterialConditions, MaterialSurfaceQueries};
use super::{
Compiled, Context, Facts, MaterialCondition, MaterialConditions, MaterialSurfaceQueries,
};
use crate::{registry::BlockStateId, worldgen::DecodeError};
use horizon_core::{
density::DensitySampler,
@@ -209,6 +211,161 @@ impl<R: RandomSource> CompiledRule<R> {
}
}
}
impl<R: RandomSource> CompiledRule<R>
where
R::Positional: Clone,
{
/// This rule where `facts` hold: conditions they decide are folded away,
/// with what can no longer produce a block, and a sequence stops at its
/// first child that always produces one. For every position the facts
/// cover it gives the block the whole rule gives.
fn specialize(&self, facts: Facts) -> Self {
match self {
Self::Empty => Self::Empty,
Self::Block(block) => Self::Block(*block),
Self::Bandlands => Self::Bandlands,
Self::OreVein {
blocks,
raw_ore_chance,
densities,
random,
} => Self::OreVein {
blocks: *blocks,
raw_ore_chance: *raw_ore_chance,
densities: *densities,
random: random.clone(),
},
Self::Condition { condition, rule } => match condition.decided(facts) {
Some(false) => Self::Empty,
Some(true) => rule.specialize(facts),
None => match rule.specialize(facts) {
Self::Empty => Self::Empty,
rule => Self::Condition {
condition: condition.clone(),
rule: Box::new(rule),
},
},
},
Self::Sequence(children) => {
let mut result = Vec::new();
for child in children {
let child = child.specialize(facts);
if matches!(child, Self::Empty) {
continue;
}
let last = child.always_produces();
result.push(child);
if last {
break;
}
}
match result.len() {
0 => Self::Empty,
1 => result.pop().unwrap(),
_ => Self::Sequence(result),
}
}
}
}
/// Whether applying this rule never gives `None` (only an error).
fn always_produces(&self) -> bool {
match self {
Self::Block(_) | Self::Bandlands => true,
Self::Sequence(children) => children.iter().any(Self::always_produces),
Self::Empty | Self::OreVein { .. } | Self::Condition { .. } => false,
}
}
fn inputs(&self, gradients: &mut Vec<(i32, i32)>, surface: &mut bool) {
match self {
Self::Condition { condition, rule } => {
condition.inputs(gradients, surface);
rule.inputs(gradients, surface);
}
Self::Sequence(children) => {
for child in children {
child.inputs(gradients, surface);
}
}
_ => {}
}
}
}
/// A rule specialised (`CompiledRule::specialize`) for each band of y between
/// its vertical gradients' bounds, and below and at or above the preliminary
/// surface when the rule asks for it: most blocks of a column, deep stone,
/// then evaluate only the few rules that can apply there.
pub struct SurfaceVariants {
/// The first y of each band after the first, ascending.
starts: Vec<i32>,
/// The rule index per band (two per band, below then above the surface,
/// when `surface`).
rules: Vec<usize>,
pub surface: bool,
}
impl SurfaceVariants {
/// The rule for a block at `y`, `above` the preliminary surface (ignored
/// unless `surface`).
#[inline]
pub fn rule(&self, y: i32, above: bool) -> usize {
let band = self.starts.partition_point(|&start| start <= y);
if self.surface {
self.rules[band * 2 + usize::from(above)]
} else {
self.rules[band]
}
}
}
impl<R: RandomSource, S: MaterialSurfaceQueries> MaterialConditions<R, S>
where
R::Positional: Clone,
{
/// Add the specialised variants of rule `index` (`SurfaceVariants`).
pub fn surface_variants(&mut self, index: usize) -> Result<SurfaceVariants, MaterialRuleError> {
let rule = self
.rules
.get(index)
.ok_or(MaterialRuleError::UnknownRule)?;
let (mut gradients, mut surface) = (Vec::new(), false);
rule.inputs(&mut gradients, &mut surface);
// A gradient is true at and below `low`, random between, false at
// and above `high`: it is decided within each band these bound.
let mut starts: Vec<i32> = gradients
.iter()
.flat_map(|&(low, high)| [low.saturating_add(1), high])
.collect();
starts.sort_unstable();
starts.dedup();
let mut variants = Vec::new();
for band in 0..=starts.len() {
let low = if band == 0 {
i32::MIN
} else {
starts[band - 1]
};
let high = starts.get(band).map_or(i32::MAX, |&next| next - 1);
let sides: &[Option<bool>] = if surface {
&[Some(false), Some(true)]
} else {
&[None]
};
for &above_surface in sides {
let facts = Facts {
low,
high,
above_surface,
};
variants.push(self.rules[index].specialize(facts));
}
}
let first = self.rules.len();
self.rules.extend(variants);
Ok(SurfaceVariants {
starts,
rules: (first..self.rules.len()).collect(),
surface,
})
}
}
impl<R: RandomSource, S: MaterialSurfaceQueries> MaterialConditions<R, S> {
/// Compile all children in order, even after an unconditional block rule.
/// Failed compilation never adds a partial rule to this worker.
@@ -196,7 +196,10 @@ pub fn build_surface<R: RandomSource, S: MaterialSurfaceQueries, B: TerrainBlock
rule: MaterialRule,
inputs: SurfaceInputs<'_, R, S>,
extensions: &MaterialExtensions<R::Positional>,
) -> Result<(), SurfaceError> {
) -> Result<(), SurfaceError>
where
R::Positional: Clone,
{
let min = chunk.min_y();
let max = min + chunk.height() - 1;
if inputs.write_min_y < min
@@ -240,9 +243,13 @@ fn build_columns<R: RandomSource, S: MaterialSurfaceQueries, B: TerrainBlockStat
extensions: &MaterialExtensions<R::Positional>,
write_min_y: i32,
write_max_y: i32,
) -> Result<(), SurfaceError> {
) -> Result<(), SurfaceError>
where
R::Positional: Clone,
{
let min = chunk.min_y();
let rule = worker.add_rule(rule)?;
let variants = worker.surface_variants(rule)?;
let cx = chunk.position().x.wrapping_shl(4);
let cz = chunk.position().z.wrapping_shl(4);
for lx in 0..16 {
@@ -321,6 +328,8 @@ fn build_columns<R: RandomSource, S: MaterialSurfaceQueries, B: TerrainBlockStat
above = above.wrapping_add(1);
worker.update_y(above, y.wrapping_sub(bottom).wrapping_add(1), water, y);
if y >= write_min_y && y <= write_max_y {
let above = variants.surface && y >= worker.minimum_surface_level()?;
let rule = variants.rule(y, above);
if let Some(state) = worker.try_apply(rule, BlockPos::new(x, y, z))? {
column.set_block(y, state)?;
}
+18
View File
@@ -191,6 +191,24 @@ fn client_jars(base: &Path, version: &str) -> Vec<String> {
jars.push(jar);
}
}
jars.extend(loader_jars(base, version));
jars
}
/// The client jars the Modrinth App keeps for a mod loader's profile: `versions/<v>-<loader>/`,
/// the vanilla jar under the loader's name, when only a Fabric or Quilt profile of the version
/// was ever played (#1783). The jar is checked against the pin like the others.
fn loader_jars(base: &Path, version: &str) -> Vec<String> {
let prefix = format!("{version}-");
let mut jars: Vec<String> = fs::read_dir(base.join("versions"))
.into_iter()
.flatten()
.flatten()
.filter_map(|entry| entry.file_name().into_string().ok())
.filter(|name| name.starts_with(&prefix))
.map(|name| format!("versions/{name}/{name}.jar"))
.collect();
jars.sort();
jars
}
+23
View File
@@ -289,6 +289,29 @@ fn the_modrinth_app_atlauncher_and_gdlauncher_are_found() {
}
}
/// A Modrinth App that only ever played a Fabric profile of 26.3 keeps the vanilla client jar
/// under the loader's name (#1783); a profile of another version beside it is not taken.
#[test]
fn a_modrinth_loader_profile_has_the_client_jar() {
let s = Scratch::new("modrinth-fabric");
s.write(
"ModrinthApp/meta/versions/26.3.1-0.18.1/26.3.1-0.18.1.jar",
b"other",
);
let jar = "versions/26.3-0.18.1/26.3-0.18.1.jar";
let dir = s.launcher("ModrinthApp", "meta", jar);
s.write(
"ModrinthApp/meta/versions/26.3-0.18.1/26.3-0.18.1.json",
br#"{"id":"26.3-0.18.1","inheritsFrom":"26.3"}"#,
);
let profile = dir.join("profiles/Fabric 26.3");
fs::create_dir_all(&profile).unwrap();
let linked = s.0.join("linked");
let got = resolve_with(&profile, &[], &linked, &Mojang::new(MANIFEST)).unwrap();
assert_eq!(got, linked);
assert_linked(&linked, &dir.join("meta"), jar);
}
#[test]
fn an_instance_folder_may_be_chosen() {
let s = Scratch::new("instance");
@@ -84,7 +84,12 @@ 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 use NAME PITCH} (the main hand's item used looking that way,
* ServerboundUseItemPacket), {@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 +135,12 @@ 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 "use" -> players.get(w[1]).use(Float.parseFloat(w[2]));
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();
@@ -250,6 +261,13 @@ public final class LocatorBarClient {
}
}
private int sequence;
void use(float pitch) throws Exception {
send(new net.minecraft.network.protocol.game.ServerboundUseItemPacket(
net.minecraft.world.InteractionHand.MAIN_HAND, ++sequence, position.yRot(), pitch));
}
void still() throws Exception {
PositionMoveRotation at = position;
// A tick of its own: the server takes one position per client tick (receivedPositionThisTick).
+39
View File
@@ -291,6 +291,19 @@ def entities():
cmd('/data get entity @e[tag=root,limit=1] Passengers[0].Health'),
cmd('/data get entity @e[tag=root,limit=1] Passengers[0].id'),
cmd('/kill @e[tag=root]'),
# Saved attribute bases are read for every mob, then Health or the max
# health when there is none (LivingEntity.readAdditionalSaveData, #1483).
cmd('/summon minecraft:cow 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,'
'attributes:[{id:"minecraft:max_health",base:40.0d},{id:"minecraft:movement_speed",base:0.5d}]}'),
cmd('/data get entity @e[tag=attr,limit=1] Health'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:max_health base get'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:movement_speed base get'),
cmd('/kill @e[tag=attr]'),
cmd('/summon minecraft:zombie 4.5 210 8.5 {Tags:["attr"],NoAI:1b,NoGravity:1b,Health:7.0f,'
'attributes:[{id:"minecraft:attack_damage",base:9.0d}]}'),
cmd('/data get entity @e[tag=attr,limit=1] Health'),
cmd('/attribute @e[tag=attr,limit=1] minecraft:attack_damage base get'),
cmd('/kill @e[tag=attr]'),
*setup('/kill @e[type=minecraft:armor_stand]'),
{'op': 'tick', 'n': 25},
cmd('/execute if entity @e[tag=h]'),
@@ -327,6 +340,31 @@ def riding_teleport():
'/tp @s 8.5 230 8.5 0 0')
def mob_riding():
"""Mobs mount and dismount mobs with /ride, NBT passengers included (#1520)."""
rider, vehicle = '@e[tag=ride_r,limit=1]', '@e[tag=ride_v,limit=1]'
return [
*setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"]}',
'/summon minecraft:pig 6.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_r"]}'),
cmd(f'/ride {rider} dismount'),
cmd(f'/ride {rider} mount @s'),
cmd(f'/ride {rider} mount {rider}'),
cmd(f'/ride {rider} mount {vehicle}'),
cmd(f'/ride {rider} mount {vehicle}'),
cmd(f'/ride {vehicle} mount {rider}'),
cmd('/execute as @e[tag=ride_r] on vehicle run say carrying'),
cmd(f'/ride {rider} dismount'),
cmd(f'/data get entity {rider} Pos'),
cmd('/execute as @e[tag=ride_r] on vehicle run say still carrying'),
*setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'),
*setup('/summon minecraft:cow 4.5 220 12.5 {NoAI:1b,NoGravity:1b,Tags:["ride_v"],'
'Passengers:[{id:"minecraft:pig",NoAI:1b,NoGravity:1b,Tags:["ride_r"]}]}'),
cmd(f'/ride {rider} dismount'),
cmd(f'/data get entity {rider} Pos'),
*setup('/kill @e[tag=ride_r]', '/kill @e[tag=ride_v]'),
]
def scores():
return [
cmd('/scoreboard objectives add harness dummy'),
@@ -1017,6 +1055,7 @@ def groups():
('blocks and border', world_blocks()),
('entities', entities()),
('riding teleport', riding_teleport()),
('mob riding', mob_riding()),
('scores, teams and bossbars', scores()),
('execute', execute()),
('levels', levels()),
+58
View File
@@ -0,0 +1,58 @@
#!/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 sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
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 on', 'cmd Alice execute if entity @e[type=minecraft:item,x=10.5,y=-60,z=0.5,distance=..4]']),
]
def shown(lines):
"""Alice's slots, respawns, teleports and chat from the death on."""
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3
and parts[1] in ('step=death', 'step=respawn', 'step=check')
and parts[2] in ('slot', 'inventory', 'respawn', 'teleport', 'chat')]
def check(vanilla, _):
if not any(l.startswith('Alice step=check chat') for l in vanilla):
return 'vanilla answered no check command'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, '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(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')
+49
View File
@@ -0,0 +1,49 @@
#!/usr/bin/env python3
"""Respawning in a hardcore world 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 hardcore
flat world vanilla generated first, with Alice an operator in survival. LocatorBarClient (a player made of
vanilla's protocol code) joins, runs /kill on itself and presses the death screen's button
(ServerboundClientCommandPacket PERFORM_RESPAWN). Vanilla's ServerGamePacketListenerImpl.handleClientCommand
respawns the player, then makes it a spectator because the server is hardcore. The game mode changes and respawns
Alice is sent in the death and respawn steps are compared exactly.
"""
import sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
NAME = 'hardcore-respawn-parity'
# server_dir and generate_world write these server.properties.
locator.PROPERTIES = dict(locator.PROPERTIES, hardcore='true', gamemode='survival')
SCRIPT = [
('death', ['cmd Alice kill @s']),
('respawn', ['respawn Alice']),
]
def shown(lines):
"""Alice's game mode changes and respawns in the death and respawn steps."""
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3
and parts[1] in ('step=death', 'step=respawn') and parts[2] in ('gamemode', 'respawn')]
def check(vanilla, _):
if 'Alice step=respawn gamemode 3' not in vanilla:
return 'vanilla did not make the respawned player a spectator'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, 'A player dying and respawning in a hardcore world on a '
'dedicated server: the respawn and the game mode it is sent (spectator).')
print(f'hardcore respawn: {len(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')
+72 -4
View File
@@ -205,12 +205,13 @@ def run_side(label, server_command, client_command, build, world):
return out.read_text(encoding='utf-8').splitlines()
def main():
def sides(name):
"""The vanilla and Horizon dedicated servers and the LocatorBarClient that joins them, built for harness
`name`: (lock, build directory, vanilla server, Horizon server, client) commands."""
lock, jars, libraries = base.verify_artifacts()
build = lab.LOCAL / NAME
build = lab.LOCAL / name
build.mkdir(parents=True, exist_ok=True)
report = build / 'report.json'
report.unlink(missing_ok=True)
(build / 'report.json').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)
@@ -228,7 +229,74 @@ def main():
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']
return lock, build, vanilla_server, horizon_server, client
def one_player(name, script, shown, check, scope, step_seconds=4.0):
"""A harness of one player, Alice: on each server she joins, then runs `script`, a list of (step, client
actions) `step_seconds` apart. The lines `shown(transcript)` keeps must match vanilla's exactly, and
`check(vanilla's shown lines, vanilla's transcript)` returns why vanilla's run is no proof (the script did
not run), or None."""
lock, build, vanilla_server, horizon_server, client = sides(name)
def run(label, server_command, world):
directory = build / label
port = 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:
process = subprocess.Popen([*map(str, client), '127.0.0.1', str(port), str(out)], cwd=lab.ROOT,
stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, text=True)
def tell(line):
process.stdin.write(line + '\n')
process.stdin.flush()
try:
for line in ['players on', 'state on', 'step joins', 'join Alice']:
tell(line)
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)
time.sleep(step_seconds)
tell('end')
process.wait(timeout=60)
finally:
if process.poll() is None:
process.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()
world = generate_world(vanilla_server, build)
vanilla_all = run('vanilla', vanilla_server, world)
horizon_all = run('horizon', horizon_server, 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 (why := check(vanilla, vanilla_all)) is not None:
raise AssertionError(f'{why}: the script did not run (see {build})')
lab.write_json(build / 'report.json', 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=scope))
return vanilla
def main():
lock, build, vanilla_server, horizon_server, client = sides(NAME)
report = build / 'report.json'
world = generate_world(vanilla_server, build)
vanilla = run_side('vanilla', vanilla_server, client, build, world)
horizon = run_side('horizon', horizon_server, client, build, world)
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""An ender pearl in flight when its thrower dies, 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. LocatorBarClient (a player made of vanilla's protocol
code) throws an ender pearl straight up (ServerboundUseItemPacket), runs /kill on itself while the pearl flies,
presses the death screen's button (PERFORM_RESPAWN) and waits for the pearl to come down, with the rule
ender_pearls_vanish_on_death true: ThrownEnderpearl.tick discards a dead owner's pearl, so the respawned player is
never teleported. The teleports, game mode changes and respawns Alice is sent from the throw on are compared
exactly.
"""
import sys
try:
from . import test_locator_bar_parity as locator
except ImportError:
import test_locator_bar_parity as locator
NAME = 'pearl-death-parity'
# server_dir and generate_world write these server.properties.
locator.PROPERTIES = dict(locator.PROPERTIES, gamemode='survival')
SCRIPT = [
('setup', ['cmd Alice gamerule ender_pearls_vanish_on_death true', 'cmd Alice give @s minecraft:ender_pearl']),
# Straight up: it comes down about four seconds later, near where it was thrown.
('throw', ['use Alice -90', 'cmd Alice kill @s']),
('respawn', ['respawn Alice']),
('landed', []),
]
def shown(lines):
"""Alice's teleports, game mode changes and respawns from the throw on."""
steps = {f'step={step}' for step, _ in SCRIPT if step != 'setup'}
return [line for line in lines if len(parts := line.split(' ', 3)) >= 3 and parts[1] in steps
and parts[2] in ('teleport', 'gamemode', 'respawn')]
def check(vanilla, vanilla_all):
killed = any(l.startswith('Alice step=throw killed') for l in vanilla_all)
if not killed or 'Alice step=respawn respawn minecraft:overworld' not in vanilla:
return 'vanilla did not kill and respawn Alice'
return None
def main():
lines = locator.one_player(NAME, SCRIPT, shown, check, 'An ender pearl in flight when its thrower dies and '
'respawns on a dedicated server, with ender_pearls_vanish_on_death true: the pearl '
'vanishes and never teleports the player.')
print(f'pearl death: {len(lines)} lines identical')
if __name__ == '__main__':
try:
main()
except AssertionError as error:
sys.exit(f'{NAME}: {error}')