diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f90e050ca..5ac44a987 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -109,6 +109,7 @@ mod powder_snow; mod raids; mod recipe_book; mod remote; +mod remote_objects; mod render_control; mod render_tick; mod respawn_anchor; diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index fa72c7a40..58733bf45 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -758,6 +758,8 @@ impl Game<'_> { .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); status["physical_keys"] = json!(physical_keys); + // Boats, minecarts, armor stands, item frames and paintings. + status["objects"] = json!(self.objects_status()); status } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 1b99eb7e5..ae65b6d37 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -82,7 +82,7 @@ pub(super) struct Remote { pub brand: String, builtin: Arc, lang: Arc, - registries: Arc, + pub(super) registries: Arc, joined: bool, status: String, entity_id: i32, @@ -246,6 +246,7 @@ impl Game<'_> { self.player = None; self.spawn = None; self.mobs.clear(); + self.clear_remote_objects(); self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); @@ -363,6 +364,7 @@ impl Game<'_> { self.world = World::new(self.res.facts.air, 0); self.player = None; self.mobs.clear(); + self.clear_remote_objects(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -445,7 +447,7 @@ impl Game<'_> { .and_then(|i| i.id(name)) .unwrap_or(0) } - fn to_stack(&self, s: &Option) -> Option { + pub(super) fn to_stack(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut out = ItemStack { item: self.item_name(s.item), @@ -658,6 +660,7 @@ impl Game<'_> { self.world.day_time = day; self.world.weather = weather; self.mobs.clear(); + self.clear_remote_objects(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -1043,11 +1046,13 @@ impl Game<'_> { if let Some(m) = mob { m.on_ground = on_ground; } + self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); } fn remove_entity(&mut self, id: i32) { self.mobs.retain(|m| m.id != id as u32); self.orbs.retain(|o| o.id != id as u32); self.dropped.retain(|d| d.id != id as u32); + self.remove_remote_object(id as u32); if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); @@ -1311,6 +1316,7 @@ impl Game<'_> { } } self.spawn_entity(p.id, &kind, p.position, rotation); + self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data); } C::RemoveEntities(p) => { for id in p.ids { @@ -1419,10 +1425,12 @@ impl Game<'_> { o.value = (*v).max(0) as u32; } } + self.remote_object_data(p.id, &p.values); } // ClientPacketListener.handleSetEquipment: what a mob or another // player holds and wears (EquipmentSlot ordinals). C::SetEquipment(p) => { + self.remote_object_equipment(p.id, &p.slots); let items: Vec<(u8, Option>)> = p .slots .iter() @@ -2592,8 +2600,23 @@ impl Game<'_> { l.steps -= 1; } } - lerps.retain(|_, l| l.steps > 0); head_lerps.retain(|_, (_, steps)| *steps > 0); + if running { + // Boats, minecarts and armor stands interpolate like mobs. + self.tick_remote_objects(|id, at| match lerps.get_mut(&(id as i32)) { + Some(l) if l.steps > 0 => { + let n = f64::from(l.steps); + l.steps -= 1; + Vec3::new( + at.x + (l.target[0] - at.x) / n, + at.y + (l.target[1] - at.y) / n, + at.z + (l.target[2] - at.z) / n, + ) + } + _ => at, + }); + } + lerps.retain(|_, l| l.steps > 0); if let Some(r) = self.remote.as_mut() { for (id, l) in lerps { r.lerps.entry(id).or_insert(l); diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs new file mode 100644 index 000000000..12a15bc34 --- /dev/null +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -0,0 +1,270 @@ +//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, +//! `handleSetEquipment`): the server simulates them, the client places them +//! where it says and interpolates their moves like a mob's. +use super::Game; +use horizon_client::entities::{ArmorStand, ItemFrame, Painting}; +use horizon_core::geometry::Vec3; +use horizon_protocol::entity_data::Value; +use std::sync::Arc; + +impl Game<'_> { + /// `handleAddEntity` for an object type; false when `kind` isn't one. + /// Hanging entities come at their block, with their direction as the + /// spawn data (`Direction.from3DDataValue`). + pub(super) fn spawn_remote_object( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + yaw: f32, + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let block = position.map(|v| v.floor() as i32); + self.remove_remote_object(id); + if let Some(cart) = super::minecarts::CartKind::from_id(kind) { + let mut c = super::minecarts::Minecart::new(id, cart, at); + c.yaw = yaw; + c.previous_yaw = yaw; + self.carts.push(c); + } else if let Some((wood, chest)) = super::boats::any_boat_wood(kind) + && self.boat_models.has(wood, chest) + { + let mut b = super::boats::Boat::new(id, Arc::from(wood), at, yaw); + if chest { + b = b.with_chest(); + } + self.boats.push(b); + } else if kind == "minecraft:armor_stand" { + self.armor_stands.push(ArmorStand::new(id, at, yaw)); + } else if kind == "minecraft:item_frame" || kind == "minecraft:glow_item_frame" { + self.item_frames.push(ItemFrame { + id, + pos: block, + facing: data.clamp(0, 5) as u8, + glow: kind == "minecraft:glow_item_frame", + item: None, + rotation: 0, + drop_chance: 1.0, + fixed: false, + invisible: false, + check_interval: 0, + }); + } else if kind == "minecraft:painting" { + // The variant comes with the entity data; until then the + // registry's first one (VariantUtils.getAny). + let (variant, width, height) = self + .remote_painting_variant(0) + .map_or((Arc::from("minecraft:kebab"), 1, 1), |v| { + (v.id, v.width, v.height) + }); + // Direction 3D data value (north 2, south 3, west 4, east 5) to 2D. + let facing = match data { + 2 => 2, + 4 => 1, + 5 => 3, + _ => 0, + }; + self.paintings.push(Painting { + id, + pos: block, + facing, + variant, + width, + height, + check_interval: 0, + }); + } else { + return false; + } + true + } + + /// A `painting_variant` by its network id, from the server's registry. + fn remote_painting_variant(&self, id: i32) -> Option { + let r = self.remote.as_ref()?; + let name = r.registries.name("minecraft:painting_variant", id)?; + self.painting_variants.get(name).cloned() + } + + /// `handleSetEntityData` for an object: what changes how it looks. + pub(super) fn remote_object_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if self.item_frames.iter().any(|f| f.id == id) { + // HangingEntity.DATA_DIRECTION, ItemFrame.DATA_ITEM and DATA_ROTATION. + let item = match (index, value) { + (9, Value::Item(stack)) => Some(self.to_stack(stack)), + _ => None, + }; + let Some(f) = self.item_frames.iter_mut().find(|f| f.id == id) else { + continue; + }; + match (index, value) { + (8, Value::Id(d)) => f.facing = (*d).clamp(0, 5) as u8, + (10, Value::Int(r)) => f.rotation = r.rem_euclid(8) as u8, + _ => {} + } + if let Some(item) = item { + f.item = item; + } + } else if self.paintings.iter().any(|p| p.id == id) { + // Painting.DATA_PAINTING_VARIANT_ID: a registry holder (id + 1). + if let (9, Value::Id(holder)) = (index, value) + && let Some(v) = self.remote_painting_variant(holder - 1) + && let Some(p) = self.paintings.iter_mut().find(|p| p.id == id) + { + p.variant = v.id; + p.width = v.width; + p.height = v.height; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + match (index, value) { + (0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0, + (9, Value::Float(health)) => a.health = *health, + // ArmorStand.DATA_CLIENT_FLAGS. + (15, Value::Byte(flags)) => { + a.small = flags & 1 != 0; + a.show_arms = flags & 4 != 0; + a.no_base_plate = flags & 8 != 0; + a.marker = flags & 16 != 0; + } + _ => {} + } + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + // VehicleEntity's hurt, direction and damage; the paddles. + match (index, value) { + (8, Value::Int(v)) => b.hurt_time = *v, + (9, Value::Int(v)) => b.hurt_dir = *v, + (10, Value::Float(v)) => b.damage = *v, + (11, Value::Bool(v)) => b.paddling[0] = *v, + (12, Value::Bool(v)) => b.paddling[1] = *v, + _ => {} + } + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + match (index, value) { + (8, Value::Int(v)) => c.hurt_time = *v, + (9, Value::Int(v)) => c.hurt_dir = *v, + (10, Value::Float(v)) => c.damage = *v, + _ => {} + } + } + } + } + + /// `handleSetEquipment` for an armor stand (EquipmentSlot ordinals 0 to + /// 5: main hand, off hand, feet, legs, chest, head, its storage order). + pub(super) fn remote_object_equipment( + &mut self, + id: i32, + slots: &[(u8, Option)], + ) { + if !self.armor_stands.iter().any(|a| a.id == id as u32) { + return; + } + let items: Vec<_> = slots + .iter() + .map(|(slot, stack)| (usize::from(*slot), self.to_stack(stack))) + .collect(); + if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id as u32) { + for (slot, item) in items { + if let Some(s) = a.equipment.get_mut(slot) { + *s = item; + } + } + } + } + + /// A move's rotation and ground state for an object. + pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option, on_ground: bool) { + let id = id as u32; + if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + if let Some(yaw) = yaw { + b.yaw = yaw; + } + b.on_ground = on_ground; + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + if let Some(yaw) = yaw { + c.yaw = yaw; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + if let Some(yaw) = yaw { + a.yaw = yaw; + } + a.on_ground = on_ground; + } + } + + /// One tick of interpolation: `step` moves a position a step toward + /// the entity's last sent one, if it has a move in progress. + pub(super) fn tick_remote_objects(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for c in &mut self.carts { + c.previous = c.position; + c.previous_yaw = c.yaw; + c.position = step(c.id, c.position); + } + for b in &mut self.boats { + b.previous = b.position; + b.previous_yaw = b.yaw; + b.position = step(b.id, b.position); + } + for a in &mut self.armor_stands { + a.position = step(a.id, a.position); + } + } + + /// The boats, minecarts, armor stands, item frames and paintings in the + /// level (a server's client: the ones it was sent), for `status`. + pub(super) fn objects_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for b in &self.boats { + out.push(json!({"id": b.id, "kind": b.entity_type(), "position": at(b.position), "yaw": b.yaw})); + } + for c in &self.carts { + out.push( + json!({"id": c.id, "kind": c.kind.id(), "position": at(c.position), "yaw": c.yaw}), + ); + } + for a in &self.armor_stands { + let items: Vec<_> = a + .equipment + .iter() + .map(|i| i.as_ref().map(|i| &*i.item)) + .collect(); + out.push(json!({"id": a.id, "kind": "minecraft:armor_stand", "position": at(a.position), "yaw": a.yaw, + "small": a.small, "arms": a.show_arms, "no_base_plate": a.no_base_plate, "equipment": items})); + } + for f in &self.item_frames { + out.push( + json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing, + "item": f.item.as_ref().map(|i| &*i.item), "rotation": f.rotation}), + ); + } + for p in &self.paintings { + out.push(json!({"id": p.id, "kind": "minecraft:painting", "position": p.pos, "facing": p.facing, + "variant": &*p.variant})); + } + out + } + + /// Every object a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_objects(&mut self) { + self.carts.clear(); + self.boats.clear(); + self.armor_stands.clear(); + self.item_frames.clear(); + self.paintings.clear(); + } + + pub(super) fn remove_remote_object(&mut self, id: u32) { + self.carts.retain(|c| c.id != id); + self.boats.retain(|b| b.id != id); + self.armor_stands.retain(|a| a.id != id); + self.item_frames.retain(|f| f.id != id); + self.paintings.retain(|p| p.id != id); + } +} diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 8a03a82ff..42b21baf7 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -42,6 +42,8 @@ address. The script then checks, from both sides, what a guest's game used to ge counts up) and the server eats one loaf and feeds the guest. - xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the guest their points (not the host). +- objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the + guest as the host has them (kind, place, rotation, what they hold or wear, the variant). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -74,7 +76,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', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'effects', 'portals'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'effects', 'portals'] class Game: @@ -1081,6 +1083,59 @@ def check_xp(host, guest, out): return {'seen': seen, 'guest': xp, 'host': host_xp} +def objects_near(game, centre): + """`status`'s objects within 8 blocks of centre, without their ids (each side numbers its own).""" + out = [] + for o in game('status')['objects']: + if all(abs(o['position'][i] - centre[i]) <= 8 for i in (0, 2)): + o = dict(o) + o.pop('id') + o['position'] = [round(v, 2) for v in o['position']] + if 'yaw' in o: # as the packets carry it, in 256ths of a turn + o['yaw'] = round(o['yaw'] * 256 / 360) % 256 + out.append(o) + return sorted(out, key=json.dumps) + + +def check_objects(host, guest, out): + x, y, z = (int(v // 1) for v in pos_of(host)) + commands = [ + f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:stone', + f'summon minecraft:minecart {x - 4.5} {y} {z + 3.5}', + f'summon minecraft:chest_minecart {x - 2.5} {y} {z + 3.5}', + f'summon minecraft:furnace_minecart {x + 1.5} {y} {z + 3.5}', + f'summon minecraft:tnt_minecart {x + 4.5} {y} {z + 3.5}', + f'summon minecraft:oak_boat {x - 4.5} {y} {z + 6.5} {{Rotation:[45f,0f]}}', + f'summon minecraft:birch_chest_boat {x - 1.5} {y} {z + 6.5}', + f'summon minecraft:bamboo_raft {x + 2.5} {y} {z + 6.5}', + f'summon minecraft:armor_stand {x - 2.5} {y} {z - 2.5} {{Rotation:[90f,0f]}}', + f'summon minecraft:armor_stand {x - 4.5} {y} {z - 2.5} {{ShowArms:1b,Small:1b,NoBasePlate:1b,' + 'equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}', + f'summon minecraft:item_frame {x - 3.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 4},{y + 1},{z - 5}],Facing:3b,' + 'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}', + f'summon minecraft:glow_item_frame {x - 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x - 2},{y + 1},{z - 5}],Facing:3b}}', + f'summon minecraft:painting {x + 1.5} {y + 1} {z - 4.97} {{block_pos:[I;{x + 1},{y + 1},{z - 5}],facing:0b,' + 'variant:"minecraft:kebab"}', + f'summon minecraft:painting {x + 4} {y + 1} {z - 4.97} {{block_pos:[I;{x + 4},{y + 1},{z - 5}],facing:0b,' + 'variant:"minecraft:courbet"}', + ] + try: + for command in commands: + host('command', command=command) + host.wait(60) + guest.raw('look-at', x, y, z - 5) + guest.wait(10) + guest.shot(out, 'objects') + host.shot(out, 'objects') + mine, theirs = objects_near(host, (x, y, z)), objects_near(guest, (x, y, z)) + finally: + host('command', command=f'kill @e[type=!minecraft:player,x={x - 8},y={y - 2},z={z - 8},dx=16,dy=8,dz=16]') + host('command', command=f'fill {x - 6} {y} {z - 6} {x + 6} {y + 3} {z - 6} minecraft:air') + assert len(mine) == len(commands) - 1, f'the host has {len(mine)} objects: {mine}' + assert theirs == mine, f'the guest sees {theirs}\nthe host has {mine}' + return f'{len(theirs)} objects identical' + + CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, @@ -1089,7 +1144,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, - 'xp': check_xp} + 'xp': check_xp, 'objects': check_objects} def run(ctl, out, resources, checks):