diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b64eeb9a5..bc0cb86b9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1442,6 +1442,8 @@ struct Game<'a> { mount_menu: mount_menu::MountMenu, /// The player's fishing hook. hook: Option, + /// The other players' hooks a server tracks to this client. + remote_hooks: Vec, tridents: Vec, rockets: Vec, /// Ominous trial spawners' item spawners. @@ -11801,6 +11803,7 @@ impl<'a> Game<'a> { recipe_ui: Default::default(), mount_menu: Default::default(), hook: None, + remote_hooks: Vec::new(), tridents: Vec::new(), rockets: Vec::new(), ominous_spawners: Vec::new(), diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 94067e7f9..d454df406 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -2,6 +2,7 @@ //! bobbing, lure and bite timers, open water, hooking mobs, retrieving the //! `gameplay/fishing` loot) and `FishingHookRenderer` (bobber and line). use super::{Game, view_vector}; +use horizon_client::lan::{entity::States, hub::Hub}; use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, @@ -15,7 +16,10 @@ use horizon_core::{ geometry::{Aabb, Vec3, trig}, random::RandomSource, }; -use std::sync::Arc; +use horizon_protocol::entity_data::{Value, serializer}; +use std::{collections::HashMap, sync::Arc}; + +use super::lan_actions::GuestPlay; #[derive(Clone, Copy, Debug, PartialEq)] enum State { @@ -24,6 +28,8 @@ enum State { Hooked(u32), } pub(super) struct Hook { + /// Its entity id, which a server's players track it under. + id: u32, position: Vec3, previous: Vec3, velocity: Vec3, @@ -114,7 +120,9 @@ impl Game<'_> { ); // A spawned hook's start position is its feet: centre the box on the eye. let start = Vec3::new(start.x, start.y - SIZE / 2.0, start.z); + self.next_entity += 1; self.hook = Some(Hook { + id: self.next_entity, position: start, previous: start, velocity: v, @@ -562,12 +570,17 @@ impl Game<'_> { lerp(h.previous.z, h.position.z), )) } - /// FishingHookRenderer: the bobber, a camera-facing half-block quad - /// centred on the hook. + /// FishingHookRenderer: the bobbers (this player's and the others' a + /// server tracks), camera-facing half-block quads centred on the hooks. pub(super) fn fishing_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(p) = self.hook_position(alpha) else { + let hooks: Vec = self + .hook_position(alpha) + .into_iter() + .chain(self.remote_hook_ends(alpha).into_iter().map(|(h, _)| h)) + .collect(); + if hooks.is_empty() { return; - }; + } let Some(r) = self .gui .atlas @@ -577,56 +590,57 @@ impl Game<'_> { else { return; }; - let light = self - .world - .light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); let s = 0.25; - let corners = [ - p - right * s - up * s, - p + right * s - up * s, - p + right * s + up * s, - p - right * s + up * s, - ]; let uv = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]]; - for (v, uv) in corners.iter().zip(uv) { - out.push(Vertex { - normal: [0; 4], - pos: (*v - camera).as_vec3().to_array(), - uv, - layer: 0, - color: 0xFFFF_FFFF, - light: packed, - }); + for p in hooks { + let light = + self.world + .light(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); + let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + let corners = [ + p - right * s - up * s, + p + right * s - up * s, + p + right * s + up * s, + p - right * s + up * s, + ]; + for (v, uv) in corners.iter().zip(uv) { + out.push(Vertex { + normal: [0; 4], + pos: (*v - camera).as_vec3().to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: packed, + }); + } } } - /// FishingHookRenderer: the line, 16 black `lines` segments sagging from - /// a quarter block above the hook to the rod in the player's hand, + /// FishingHookRenderer: each line, 16 black `lines` segments sagging + /// from a quarter block above the hook to the rod in its owner's hand, /// `width` pixels wide (`Window.getAppropriateLineWidth`). pub(super) fn fishing_line(&self, alpha: f64, size: [u32; 2]) -> Vec { - let (Some(hook), Some(hand)) = ( - self.hook_position(alpha), - self.rod_hand_position(alpha, size), - ) else { - return Vec::new(); - }; - let offset = (hand - (hook + glam::DVec3::new(0.0, 0.25, 0.0))).as_vec3(); - let point = |a: f32| { - let y = offset.y * (a * a + a) * 0.5 + 0.25; - hook + glam::Vec3::new(offset.x * a, y, offset.z * a).as_dvec3() - }; + let own = self + .hook_position(alpha) + .zip(self.rod_hand_position(alpha, size)); let width = horizon_client::gfx::outline_width(size[0]); - (0..16) - .map(|i| Line { + let mut lines = Vec::new(); + for (hook, hand) in own.into_iter().chain(self.remote_hook_ends(alpha)) { + let offset = (hand - (hook + glam::DVec3::new(0.0, 0.25, 0.0))).as_vec3(); + let point = |a: f32| { + let y = offset.y * (a * a + a) * 0.5 + 0.25; + hook + glam::Vec3::new(offset.x * a, y, offset.z * a).as_dvec3() + }; + lines.extend((0..16).map(|i| Line { start: point(i as f32 / 16.0).to_array(), end: point((i + 1) as f32 / 16.0).to_array(), color: 0xFF00_0000, width, - }) - .collect() + })); + } + lines } /// `FishingHookRenderer.getPlayerHandPos`: on the near plane in first /// person, beside the body otherwise. @@ -694,6 +708,20 @@ impl Game<'_> { } } impl Game<'_> { + /// The hooks drawn here, with their owners' ids (0 for this player's own). + pub(super) fn hooks_status(&self) -> Vec { + let at = |p: Vec3| [p.x, p.y, p.z]; + let own = self.hook.iter().map(|h| (h.id, 0, h.position)); + let others = self + .remote_hooks + .iter() + .map(|h| (h.id, h.owner, h.position)); + own.chain(others) + .map(|(id, owner, p)| { + serde_json::json!({"id": id, "kind": "minecraft:fishing_bobber", "owner": owner, "position": at(p)}) + }) + .collect() + } /// The hook for `horizon-ctl status`. pub(super) fn hook_status(&self) -> Option { let h = self.hook.as_ref()?; @@ -706,3 +734,175 @@ impl Game<'_> { })) } } + +/// A hook a server tracks to this client (`FishingHook.recreateFromPacket`) +/// that another player cast: drawn where the server puts it, its line +/// running to that player's hand. +pub(super) struct RemoteHook { + id: u32, + owner: u32, + position: Vec3, + previous: Vec3, +} + +impl Hook { + /// This client's own hook as its server tracks it: drawn, never ticked here. + fn remote(id: u32, at: Vec3) -> Self { + Self { + id, + position: at, + previous: at, + velocity: Vec3::ZERO, + state: State::Flying, + life: 0, + on_ground: false, + nibble: 0, + time_until_lured: 0, + time_until_hooked: 0, + fish_angle: 0.0, + out_of_water: 0, + open_water: true, + luck: 0, + lure: 0, + } + } + /// `FishingHook`'s entity for the players tracking it: the owner's id in + /// its add packet, DATA_HOOKED_ENTITY (the hooked id plus one) and + /// DATA_BITING when they differ from their defaults. + fn track(&self, owner: i32, out: &mut States) { + let p = self.position; + let e = out.add( + self.id as i32, + super::lan::entity_uuid(self.id), + "minecraft:fishing_bobber", + ); + e.position = [p.x, p.y, p.z]; + e.velocity = [self.velocity.x, self.velocity.y, self.velocity.z]; + e.on_ground = self.on_ground; + e.data = owner; + if let State::Hooked(id) = self.state { + e.meta.push((8, serializer::INT, Value::Int(id as i32 + 1))); + } + if self.nibble > 0 { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); + } + } +} + +impl Game<'_> { + /// The hooks guests track: the host's and each guest's in the level. + pub(super) fn lan_hook_states( + &self, + host_entity: Option, + play: &HashMap, + hub: &Hub, + out: &mut States, + ) { + if let (Some(h), Some(owner)) = (&self.hook, host_entity) { + h.track(owner, out); + } + for g in hub.guests.iter().filter(|g| hub.here(g)) { + if let Some(h) = play.get(&g.conn).and_then(|p| p.hook.as_ref()) { + h.track(g.entity_id, out); + } + } + } + + /// `handleAddEntity` for a fishing bobber: this player's own becomes its + /// hook (`Player.fishing`), another player's is drawn on its line to them. + pub(super) fn spawn_remote_hook(&mut self, id: u32, at: Vec3, owner: i32) { + let own = self.remote.as_ref().map(|r| r.entity_id); + if own == Some(owner) { + self.hook = Some(Hook::remote(id, at)); + } else { + self.remote_hooks.push(RemoteHook { + id, + owner: owner as u32, + position: at, + previous: at, + }); + } + } + + /// One tick of interpolation for the hooks a server tracks. + pub(super) fn step_remote_hooks(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + if self.remote.is_none() { + return; + } + if let Some(h) = self.hook.as_mut() { + h.previous = h.position; + h.position = step(h.id, h.position); + } + for h in &mut self.remote_hooks { + h.previous = h.position; + h.position = step(h.id, h.position); + } + } + + /// `FishingHook.onSyncedDataUpdated`: this player's hook is biting + /// (DATA_BITING), which `status` shows as a nibble. + pub(super) fn remote_hook_data(&mut self, id: u32, values: &[(u8, i32, Value)]) { + let Some(h) = self + .hook + .as_mut() + .filter(|h| h.id == id && self.remote.is_some()) + else { + return; + }; + for (index, _, value) in values { + if let (9, Value::Bool(biting)) = (index, value) { + h.nibble = i32::from(*biting); + } + } + } + + pub(super) fn remove_remote_hook(&mut self, id: u32) { + if self.remote.is_some() && self.hook.as_ref().is_some_and(|h| h.id == id) { + self.hook = None; + } + self.remote_hooks.retain(|h| h.id != id); + } + + pub(super) fn clear_remote_hooks(&mut self) { + if self.remote.is_some() { + self.hook = None; + } + self.remote_hooks.clear(); + } + + /// Other players' hooks: the bobber and its line to the owner's hand + /// (`FishingHookRenderer.getPlayerHandPos` in third person), as + /// (hook, hand) this frame. + fn remote_hook_ends(&self, alpha: f64) -> Vec<(glam::DVec3, glam::DVec3)> { + let lerp = |a: Vec3, b: Vec3| { + glam::DVec3::new( + a.x + (b.x - a.x) * alpha, + a.y + (b.y - a.y) * alpha, + a.z + (b.z - a.z) * alpha, + ) + }; + self.remote_hooks + .iter() + .filter_map(|h| { + let owner = self.mobs.iter().find(|m| m.id == h.owner)?; + let feet = lerp(owner.previous, owner.position); + let body = horizon_client::camera::lerp( + alpha as f32, + owner.previous_body_yaw, + owner.body_yaw, + ); + let angle = f64::from(body * (std::f64::consts::PI / 180.0) as f32); + let (sin, cos) = (f64::from(trig::sin(angle)), f64::from(trig::cos(angle))); + // The right arm; a crouching owner's eyes are lower. + let eye = owner.eye_y() - owner.position.y; + let hand = feet + + glam::DVec3::new( + -cos * 0.35 - sin * 0.8, + eye - 0.45, + -sin * 0.35 + cos * 0.8, + ); + Some((lerp(h.previous, h.position), hand)) + }) + .collect() + } +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index bab304569..8bf72abee 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -875,6 +875,7 @@ impl Game<'_> { .collect(); self.lan_riding(host_entity, &guests, &mut host.hub.riding); self.lan_entities(host_entity, &host.mob_players, &mut host.hub, &mut states); + self.lan_hook_states(host_entity, &host.play, &host.hub, &mut states); } else { states.clear(); } @@ -1068,6 +1069,7 @@ impl Game<'_> { } // A dedicated server has no host player. self.lan_entities(None, &host.mob_players, &mut host.hub, &mut theirs); + self.lan_hook_states(None, &host.play, &host.hub, &mut theirs); theirs.as_slice() } else { entities diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2c2c25e93..4a4a94a8d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -82,6 +82,8 @@ pub(super) struct GuestPlay { /// (`LivingEntity.collectEquipmentChanges`). modifiers: Vec<(String, String)>, equipped: Option>>, + /// The guest's cast fishing hook (`Player.fishing`). + pub(super) hook: Option, } /// A guest's command waiting for the hub (`LanHost::commands`). @@ -342,6 +344,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); std::mem::swap(&mut self.stats, &mut play.stats); + std::mem::swap(&mut self.hook, &mut play.hook); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take()); @@ -549,6 +552,7 @@ impl Game<'_> { std::mem::swap(&mut self.adv.unlocked, &mut g.recipes_unlocked); std::mem::swap(&mut self.level.recipe_book, &mut g.recipe_book); std::mem::swap(&mut self.stats, &mut play.stats); + std::mem::swap(&mut self.hook, &mut play.hook); self.adv.loaded = adv_loaded; play.last_inventory = std::mem::replace(&mut self.adv.last_inventory, last_inventory); let stat_events = std::mem::take(&mut play.stats.events); @@ -1711,6 +1715,7 @@ impl Game<'_> { // PlayerAdvancements.flushDirty. let sleeping = host.hub.guests[gi].sleeping; self.as_guest(host, conn, |g| { + g.tick_fishing(); g.count_tick_stats(sleeping); g.tick_advancements(); g.update_player_attributes(); @@ -1721,6 +1726,10 @@ impl Game<'_> { self.guest_orbs(host, gi); if host.hub.guests[gi].health <= 0.0 && !host.hub.guests[gi].dead { self.guest_forget_digging(host, conn); + // FishingHook.shouldStopFishing: its owner is dead. + if let Some(play) = host.play.get_mut(&conn) { + play.hook = None; + } } let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 82d0a11e2..58f82e3a9 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -88,6 +88,8 @@ impl Game<'_> { self.end .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) } + // FishingHook.recreateFromPacket: the owner's id is the data. + "minecraft:fishing_bobber" => self.spawn_remote_hook(id, at, data), "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { id, position: at, @@ -114,6 +116,7 @@ impl Game<'_> { /// `handleSetEntityData` for these types: what changes how they look. pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; + self.remote_hook_data(id, values); if self.potions.has_thrown(id) { // ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is. for (index, _, value) in values { @@ -205,6 +208,7 @@ impl Game<'_> { c.position = step(c.id, c.position); } self.potions.step_remote_thrown(&mut step); + self.step_remote_hooks(&mut step); self.end.step_remote_eyes(|id, at| { let at = step(id, Vec3::new(at[0], at[1], at[2])); [at.x, at.y, at.z] @@ -220,6 +224,7 @@ impl Game<'_> { self.crystals.retain(|c| c.id != id); self.potions.remove_remote_thrown(id); self.end.remove_remote_eye(id); + self.remove_remote_hook(id); } /// Every one a server sent (a new connection, level or dimension). @@ -232,6 +237,7 @@ impl Game<'_> { self.crystals.clear(); self.potions.clear_thrown(); self.end.clear_remote_eyes(); + self.clear_remote_hooks(); } /// Their kind and place, for `status`. @@ -260,6 +266,7 @@ impl Game<'_> { for (id, p) in self.end.eye_positions() { out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p})); } + out.extend(self.hooks_status()); out } } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 41d39f37b..0097d40ff 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -202,6 +202,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - wind: the host and the guest each throw a wind charge at their feet: the server's burst launches them about six blocks up (the push in ClientboundExplodePacket) and they land unhurt (#1386). +- fishing: the host and the guest each cast a fishing rod: the hook stays out on the server and + both sides draw it and it reels back in from the ground, and in open water a fish + bites and reeling in catches it (#1348). 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). @@ -4726,5 +4729,82 @@ CHECKS += ['wind'] CHECK_FNS.update(wind=check_wind) +def bobbers(game): + """The fishing bobbers this side draws, as (owner) ids: 0 for its own player's.""" + return [q.get('owner') for q in game('status')['projectiles'] if q['kind'] == 'minecraft:fishing_bobber'] + + +def check_fishing(host, guest, out): + """FishingHook for each player, on the server: a cast hook stays out (ticked by the server and + tracked to the clients as a fishing bobber under its owner), lands on the ground and reels back + in; cast into open water with Lure III, a fish bites and reeling in + during the bite catches it for 1 (#1348).""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + host('command', command='weather clear') + seen = {} + try: + for game, other, dz in ((host, guest, -5), (guest, host, 5)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 14} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 14} {hy + 4} {z + 1} minecraft:air') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:fishing_rod') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + # On the ground: the floor four blocks ahead. + game.raw('look-at', f'{x + 4.5:.2f}', f'{hy:.2f}', f'{z + 0.5:.2f}') + game.raw('use-item') + game.wait(40) + s = {'own': bobbers(game), 'other': bobbers(other)} + game.shot(out, 'fishing-cast') + game.raw('use-item') + game.wait(10) + s['reeled'] = {'own': bobbers(game), 'damage': (game('state').get('held') or {}).get('damage')} + # Open water: a pool 7x7 and 3 deep, ahead. + host('command', command=f'fill {x + 3} {hy - 3} {z - 3} {x + 9} {hy - 1} {z + 3} minecraft:water') + game('command', command='item replace entity @s weapon.mainhand with minecraft:fishing_rod[enchantments={lure:3}]') + game.wait(10) + game.raw('look-at', f'{x + 6.5:.2f}', f'{hy - 1:.2f}', f'{z + 0.5:.2f}') + game.raw('use-item') + bit = None + for t in range(0, 900, 5): + game.wait(5) + if (game('status').get('fishing') or {}).get('nibble', 0) > 0: + bit = t + break + game.raw('use-item') + game.wait(40) + counts = game.raw('inventory')['counts'] + s['caught'] = {'bit': bit is not None, + 'damage': (game('state').get('held') or {}).get('damage'), + 'items': sum(counts.values()) - 1} + game.shot(out, 'fishing-caught') + host('command', command=f'fill {x + 3} {hy - 3} {z - 3} {x + 9} {hy - 2} {z + 3} minecraft:stone') + host('command', command=f'fill {x + 3} {hy - 1} {z - 3} {x + 9} {hy - 1} {z + 3} minecraft:stone') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:item]') + for game in (host, guest): + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + other = guest if name == 'host' else host + assert s['own'] == [0], f'{name}: {seen}' + # The in-frame host draws only its own hook. + if other is guest or SERVER_THREAD: + assert len(s['other']) == 1 and s['other'][0] != 0, f'{name}: {seen}' + # FishingHook.retrieve costs 2 on the ground, but a resting hook's onGround + # alternates every tick on the server (Entity.move with no vertical motion + # clears it, the next tick's gravity sets it again): 2 or nothing. + assert s['reeled']['own'] == [] and s['reeled']['damage'] in (None, 0, 2), f'{name}: {seen}' + assert s['caught']['bit'] and s['caught']['damage'] == 1 and s['caught']['items'] >= 1, f'{name}: {seen}' + return seen + + +CHECKS += ['fishing'] +CHECK_FNS.update(fishing=check_fishing) + + if __name__ == '__main__': main()