diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 71a9377ed..2e600333a 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -68,6 +68,14 @@ impl EffectInstance { } changed } + /// `MobEffectInstance.tickClient`: a client counts its effects down + /// (the server removes them). + pub fn tick_client(&mut self) { + if self.infinite() || self.duration > 0 { + self.tick_down(); + self.downgrade(); + } + } fn tick_down(&mut self) { if let Some(h) = self.hidden.as_mut() { h.tick_down(); @@ -170,6 +178,39 @@ impl PlayerEffects { pub fn clear(&mut self) { self.list.clear(); } + /// The effects of a saved player (`Player.active_effects`: id, + /// duration, amplifier, ambient, visible). + pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self { + let mut effects = Self::default(); + for (id, duration, amplifier, ambient, _) in saved { + if let Some(def) = brewing::effect(id) { + let mut e = EffectInstance::new(def.id, *duration, *amplifier); + e.ambient = *ambient; + effects.add(e); + } + } + effects + } + /// `Player.active_effects` for the save. + pub fn saved(&self) -> Vec<(String, i32, i32, bool, bool)> { + self.list + .iter() + .map(|e| { + ( + format!("minecraft:{}", e.id), + e.duration, + e.amplifier, + e.ambient, + e.visible, + ) + }) + .collect() + } + /// ClientboundUpdateMobEffectPacket's flags without blending: ambient, + /// particles visible and the icon shown (always, for these effects). + pub fn flags(e: &EffectInstance) -> i8 { + i8::from(e.ambient) | i8::from(e.visible) << 1 | 4 + } /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` /// (on its last tick). Returns the actions to apply, in order, and diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index cc03d8333..c746637af 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8310,21 +8310,7 @@ impl Game<'_> { self.ender_items = items.clone(); } level.ender_items = self.ender_items.clone(); - level.active_effects = self - .potions - .effects - .list - .iter() - .map(|e| { - ( - format!("minecraft:{}", e.id), - e.duration, - e.amplifier, - e.ambient, - e.visible, - ) - }) - .collect(); + level.active_effects = self.potions.effects.saved(); } fn save_game(&mut self) -> Result<()> { self.save_game_with(true) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6bf76f160..1f6921e0c 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -43,6 +43,8 @@ pub(super) struct GuestPlay { pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. pub(super) crafting: super::lan_crafting::GuestCrafting, + /// What the guest's body was given for its effects and enchantments. + potions: super::potions::BodyPotions, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -92,7 +94,11 @@ impl Game<'_> { let mut play = host.play.remove(&conn).unwrap_or_default(); let g = &mut host.hub.guests[i]; // The guest's body. - let mut motion = g.motion.take()?; + let Some(mut motion) = g.motion.take() else { + host.play.insert(conn, play); + return None; + }; + self.potions.swap_player(&mut g.effects, &mut play.potions); motion.position = Vec3::new(g.position[0], g.position[1], g.position[2]); motion.ground.on_ground = g.on_ground; motion.yaw = g.yaw; @@ -188,6 +194,7 @@ impl Game<'_> { } let g = &mut host.hub.guests[i]; std::mem::swap(&mut self.ender_items, &mut g.ender_items); + self.potions.swap_player(&mut g.effects, &mut play.potions); if let Some(key) = host_ender { self.world .block_entities @@ -759,6 +766,10 @@ impl Game<'_> { g.saturation = 5.0; g.sent_health = None; g.motion = None; + // A new body: nothing given to the old one carries over. + if let Some(play) = host.play.get_mut(&conn) { + play.potions = Default::default(); + } host.hub.respawn(i, spawn); } @@ -846,12 +857,17 @@ impl Game<'_> { g.moves_from_ground }; if g.spectator() { + // Spectators' effects still run (LivingEntity.baseTick). + if !g.effects.list.is_empty() { + self.as_guest(host, conn, |game| game.tick_mob_effects()); + } return; } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; let sounds = self.as_guest(host, conn, |game| { - let (rules, health) = (game.world.health_rules, &game.motion.health); + let (rules, motion) = (game.world.health_rules, game.motion); + let health = &motion.health; let Some(player) = game.player.as_mut() else { return Vec::new(); }; @@ -889,9 +905,16 @@ impl Game<'_> { let _ = w.tick_environment_damage(); let _ = w.apply_fire_contact(); let _ = w.server_hazards_tick(in_wall); - let _ = w.player.peaceful_regeneration(rules); - let _ = w.player.food_tick(health, rules); - std::mem::take(&mut w.player.events) + let mut events = std::mem::take(&mut w.player.events); + // LivingEntity.baseTick ends with tickEffects. + game.tick_mob_effects(); + let Some(player) = game.player.as_mut() else { + return Vec::new(); + }; + let _ = player.peaceful_regeneration(rules); + let _ = player.food_tick(health, rules); + events.append(&mut player.events); + events .into_iter() .filter_map(|e| match e { MotionEvent::HurtSound(sound) => Some(sound), diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index fbc8556e7..a60926256 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -49,6 +49,14 @@ impl Game<'_> { }); } } +/// What a player's body was last given for its effects and enchantments: +/// a guest keeps their own while the host's are in `PotionState`. +#[derive(Default)] +pub(super) struct BodyPotions { + applied: Vec<(&'static str, &'static str, f64, &'static str)>, + protection_for: Option>>, + enchant_modifiers: Vec<(String, String, f64, String)>, +} /// Effects, thrown potions and the attribute modifiers last applied. #[derive(Default)] pub(super) struct PotionState { @@ -63,6 +71,14 @@ pub(super) struct PotionState { } impl PotionState { + /// Trade the player's own state (effects and what their body was given) + /// with a guest's, around `as_guest`. Potions in flight stay. + pub(super) fn swap_player(&mut self, effects: &mut PlayerEffects, body: &mut BodyPotions) { + std::mem::swap(&mut self.effects, effects); + std::mem::swap(&mut self.applied, &mut body.applied); + std::mem::swap(&mut self.protection_for, &mut body.protection_for); + std::mem::swap(&mut self.enchant_modifiers, &mut body.enchant_modifiers); + } /// Thrown potions in flight as (entity type, position, motion), for the /// dispenser parity fixture. pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> { @@ -274,8 +290,16 @@ impl Game<'_> { } } } - /// `LivingEntity.tickEffects`, attribute modifiers and the status flags. + /// The local player's effects (`tick_mob_effects`), then the potions + /// in flight, which a server without a local player still has. pub(super) fn tick_effects(&mut self) { + self.tick_mob_effects(); + self.tick_thrown_potions(); + } + /// `LivingEntity.tickEffects` (server side) for `self.player`, the local + /// player or a guest acting (`as_guest`), then its attribute modifiers + /// and status flags. + pub(super) fn tick_mob_effects(&mut self) { let Some(player) = self.player.as_ref() else { return; }; @@ -294,6 +318,20 @@ impl Game<'_> { for action in actions { self.apply_effect_action(action); } + self.apply_effect_status(); + } + /// A client's own effects (`LivingEntity.tickEffects` on the client, + /// `MobEffectInstance.tickClient`): they count down, and the server + /// removes them. Their modifiers and flags move the predicted player. + pub(super) fn tick_client_effects(&mut self) { + for e in &mut self.potions.effects.list { + e.tick_client(); + } + self.apply_effect_status(); + } + /// The effects' attribute modifiers, armor protection and status flags + /// on `self.player`. + fn apply_effect_status(&mut self) { let modifiers = self.potions.effects.modifiers(); if modifiers != self.potions.applied && let Some(p) = self.player.as_mut() @@ -346,7 +384,6 @@ impl Game<'_> { status.protection = std::mem::take(&mut p.status.protection); p.status = status; } - self.tick_thrown_potions(); } fn tick_thrown_potions(&mut self) { let mut thrown = std::mem::take(&mut self.potions.thrown); @@ -606,13 +643,7 @@ impl Game<'_> { /// Effects saved in level.dat (`Player.active_effects`). pub(super) fn restore_effects(&mut self) { self.potions = PotionState::default(); - for (id, duration, amplifier, ambient, _) in self.level.active_effects.clone() { - if let Some(def) = brewing::effect(&id) { - let mut e = EffectInstance::new(def.id, duration, amplifier); - e.ambient = ambient; - self.potions.effects.add(e); - } - } + self.potions.effects = PlayerEffects::from_saved(&self.level.active_effects); } pub(super) fn effects_json(&self) -> serde_json::Value { serde_json::json!({ diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index d08e95bc8..7e5c9f1e2 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -382,6 +382,31 @@ impl Game<'_> { .unwrap_or("minecraft:air"), ) } + /// A mob effect's network id as the effect (`brewing::EFFECTS` id). + fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { + let r = self.remote.as_ref()?; + let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?; + horizon_client::brewing::effect(name).map(|d| d.id) + } + /// ClientPacketListener.handleUpdateMobEffect for the player itself + /// (`LivingEntity.forceAddEffect`): the effect replaces any of its kind. + /// Other entities' effects are not shown. + fn remote_effect(&mut self, p: &play::UpdateMobEffect) { + if !self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + return; + } + let Some(id) = self.remote_effect_id(p.effect) else { + return; + }; + let mut e = horizon_client::effects::EffectInstance::new(id, p.duration, p.amplifier); + e.ambient = p.flags & 1 != 0; + e.visible = p.flags & 2 != 0; + let list = &mut self.potions.effects.list; + match list.iter_mut().find(|x| x.id == id) { + Some(existing) => *existing = e, + None => list.push(e), + } + } fn item_id(&self, name: &str) -> i32 { let r = self.remote.as_ref().expect("remote"); r.builtin @@ -827,6 +852,8 @@ impl Game<'_> { )); } C::Respawn(p) => { + // A new player, without effects: the server sends them again. + self.potions.effects.clear(); self.enter_remote_dimension(&p.spawn, true); self.screen = Screen::Playing; if let Some(r) = self.remote.as_mut() { @@ -1141,6 +1168,14 @@ impl Game<'_> { } } C::Animate(p) if p.action == 0 => {} + C::UpdateMobEffect(p) => self.remote_effect(&p), + C::RemoveMobEffect(p) => { + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) + && let Some(id) = self.remote_effect_id(p.effect) + { + self.potions.effects.list.retain(|e| e.id != id); + } + } C::SetHealth(p) => { if let Some(r) = self.remote.as_mut() { r.health = (p.health, p.food, p.saturation); @@ -1810,6 +1845,7 @@ impl Game<'_> { self.tick_block_entity_anims(); self.tick_hand(); self.tick_particles(); + self.tick_client_effects(); let ghast_collisions = self.happy_ghast_player_collisions(); let Some(player) = self.player.as_mut() else { return Ok(()); diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 954ffc714..243c90d18 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -18,6 +18,16 @@ pub const CREATIVE: i32 = 1; pub const ADVENTURE: i32 = 2; pub const SPECTATOR: i32 = 3; +/// An effect as last sent in ClientboundUpdateMobEffectPacket. +#[derive(Clone, Debug, PartialEq)] +pub struct SentEffect { + pub id: &'static str, + pub amplifier: i32, + pub flags: i8, + pub duration: i32, + pub tick_count: i32, +} + pub struct Guest { pub conn: u32, /// The client's address (IP bans, `list`). @@ -92,6 +102,12 @@ pub struct Guest { pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, + /// Active status effects (`LivingEntity.activeEffects`). + pub effects: crate::effects::PlayerEffects, + /// What the client was told of each effect: id, amplifier, flags, and + /// the duration and `effects.tick_count` at the time, so a duration that + /// only counted down is not sent again (`ServerPlayer.onEffectUpdated`). + pub sent_effects: Vec, /// What the client believes the inventory menu holds (for change detection). pub menu_sent: Vec>, pub menu_state: i32, @@ -174,6 +190,8 @@ impl Guest { xp_level: 0, xp_progress: 0.0, xp_total: 0, + effects: Default::default(), + sent_effects: Vec::new(), menu_sent: vec![None; 46], menu_state: 0, sent_health: None, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index fcae7c097..3f1f88c4a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -9,9 +9,13 @@ use super::{ chunks::ChunkEncoder, data::SyncData, entity::EntityState, - guest::{Guest, stack_to_network}, + guest::{Guest, SentEffect, stack_to_network}, +}; +use crate::{ + effects::{EffectInstance, PlayerEffects}, + items::ItemStack, + world::World, }; -use crate::{items::ItemStack, world::World}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, @@ -553,11 +557,106 @@ impl Hub { })); g.center_sent = Some((cx, cz)); g.placed_at = self.ticks; + self.send_active_effects(i); // ServerPlayer.sendPostEffects and initInventoryMenu. self.guests[i].send(&raw(ids::POST_EFFECTS, vec![0])); self.send_inventory(i); } + /// ClientboundUpdateMobEffectPacket for one of the guest's effects. + fn send_effect(&mut self, i: usize, e: &EffectInstance, blend: bool) -> Option { + let effect = self + .sync + .id("minecraft:mob_effect", &format!("minecraft:{}", e.id))?; + let flags = PlayerEffects::flags(e); + let g = &self.guests[i]; + g.send(&C::UpdateMobEffect(play::UpdateMobEffect { + id: g.entity_id, + effect, + amplifier: e.amplifier, + duration: e.duration, + flags: flags | if blend { 8 } else { 0 }, + })); + Some(SentEffect { + id: e.id, + amplifier: e.amplifier, + flags, + duration: e.duration, + tick_count: g.effects.tick_count, + }) + } + + /// PlayerList.sendActivePlayerEffects: every effect, unblended, when the + /// player is placed (or respawns). + pub fn send_active_effects(&mut self, i: usize) { + let effects = self.guests[i].effects.list.clone(); + let sent = effects + .iter() + .filter_map(|e| self.send_effect(i, e, false)) + .collect(); + self.guests[i].sent_effects = sent; + } + + /// ServerPlayer.onEffectAdded (blended), onEffectUpdated and + /// onEffectsRemoved, from what changed since the client was told: an + /// effect that only counted down is not sent again, except at every + /// 600 ticks left (`LivingEntity.tickEffects`). + fn sync_effects(&mut self, i: usize) { + let g = &self.guests[i]; + if g.effects.list.is_empty() && g.sent_effects.is_empty() { + return; + } + let now = g.effects.tick_count; + let mut sent = Vec::with_capacity(g.effects.list.len()); + let mut changes = Vec::new(); + for e in &g.effects.list { + match g.sent_effects.iter().find(|s| s.id == e.id) { + None => changes.push((e.clone(), true)), + Some(s) => { + let ticked = now.wrapping_sub(s.tick_count); + let expected = if s.duration == -1 { + -1 + } else { + s.duration - ticked + }; + let refresh = ticked > 0 && e.duration > 0 && e.duration % 600 == 0; + if s.amplifier != e.amplifier + || s.flags != PlayerEffects::flags(e) + || e.duration != expected + || refresh + { + changes.push((e.clone(), false)); + } else { + sent.push(s.clone()); + } + } + } + } + let removed: Vec<&'static str> = g + .sent_effects + .iter() + .filter(|s| g.effects.get(s.id).is_none()) + .map(|s| s.id) + .collect(); + for id in removed { + let Some(effect) = self + .sync + .id("minecraft:mob_effect", &format!("minecraft:{id}")) + else { + continue; + }; + let g = &self.guests[i]; + g.send(&C::RemoveMobEffect(play::RemoveMobEffect { + id: g.entity_id, + effect, + })); + } + for (e, added) in changes { + sent.extend(self.send_effect(i, &e, added)); + } + self.guests[i].sent_effects = sent; + } + /// PlayerList.sendPlayerPermissionLevel: the op level as an entity event /// (24 + level), then the commands that level may use. fn send_permission_level(&self, i: usize) { @@ -789,6 +888,7 @@ impl Hub { for i in 0..self.guests.len() { if self.guests[i].placed { self.sync_player_state(i); + self.sync_effects(i); } } let latencies: Vec<_> = self @@ -1559,6 +1659,10 @@ impl Hub { spawn: info, keep: 0, })); + // The respawned player is a new one, without effects; so is the + // client's (ClientPacketListener.handleRespawn). + g.effects = Default::default(); + g.sent_effects.clear(); g.center = None; g.sent_chunks.clear(); g.chunk_queue.clear(); diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 3554463ea..d824683d2 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_level = level.xp_level; guest.xp_progress = level.xp_progress; guest.xp_total = level.xp_total; + guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); guest.saved = level.player_extra.clone(); @@ -119,6 +120,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.xp_level = guest.xp_level; level.xp_progress = guest.xp_progress; level.xp_total = guest.xp_total; + level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; level.selected_slot = guest.selected as i32; diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index a3ee81912..ab3489328 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2361,6 +2361,7 @@ impl Level { "Inventory", "EnderItems", "equipment", + "active_effects", "Pos", "respawn", "recipeBook", @@ -3191,4 +3192,19 @@ mod tests { assert!(dir.join("data/minecraft/world_gen_settings.dat").exists()); let _ = fs::remove_dir_all(&dir); } + + #[test] + fn effects_that_ended_are_not_saved_again() { + // A player loaded with an effect that has since run out: the loaded + // compound still holds it, but the save writes only what is active. + let mut level = Level { + active_effects: vec![("minecraft:speed".into(), 200, 1, false, true)], + ..Level::default() + }; + let loaded = level.player_tag(); + assert!(loaded.get("active_effects").is_some()); + level.player_extra = Some(loaded); + level.active_effects.clear(); + assert!(level.player_tag().get("active_effects").is_none()); + } }