diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index ab6cce246..8c16f9a32 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -456,6 +456,7 @@ fn main() -> horizon_client::Result<()> { yaw: 0.0, hero: false, uuid: [0, 0x1234, 0, 0x5678], + allies: Default::default(), } }); let mut scratch = LegacyRandom::new(0); diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 812ac6118..587f13e05 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -655,15 +655,19 @@ impl Game<'_> { let Some(p) = self.player.as_ref() else { return; }; + let below_world = p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64); + let name = self.player_display_text(); let message = match cause { - Some(key) => Text::translate(&key, &[Text::literal(PLAYER_NAME)]), - None if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) => { - Text::translate("death.attack.outOfWorld", &[Text::literal(PLAYER_NAME)]) - } + Some(key) => Text::translate(&key, &[name]), + None if below_world => Text::translate("death.attack.outOfWorld", &[name]), None => self.combat_death_message(), }; self.ui.death_text = Some(message.clone()); - self.system_message(message); + // ServerPlayer.die: a team that hides death messages keeps it out of + // the dying player's own chat (the death screen still shows it). + if horizon_client::scoreboard::own_death_message_shown(self.player_team()) { + self.system_message(message); + } } /// F1 hides the HUD (and hand); the screenshot key still works. pub(super) fn toggle_hide_gui(&mut self) { diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 241f61ce8..73c6b7fc0 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -25,6 +25,9 @@ pub(super) struct CombatTracker { pub(super) last_hurt_mob: Option<(u32, i64)>, /// The mob whose projectile is hitting the player now. pub(super) projectile_owner: Option, + /// The mob exploding now (`ServerExplosion.source`): its team's friendly + /// fire decides whom the blast may hurt. + pub(super) explosion_source: Option, /// The player's fall distance before this tick's movement (as of the /// end of the last one). fall_before: f64, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 0d7e34572..ef4af9eb9 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -166,6 +166,7 @@ impl Game<'_> { yaw: self.yaw, hero: self.potions.effects.get("hero_of_the_village").is_some(), uuid: self.level.player_uuid.unwrap_or_default(), + allies: std::sync::Arc::new(self.player_allies()), }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -458,7 +459,14 @@ impl Game<'_> { } keep }); - push_apart(&mut mobs); + // EntitySelector.pushableBy: the collision rules of the mobs' teams. + let teams: Vec> = + if self.score.board.teams.is_empty() { + Vec::new() + } else { + mobs.iter().map(|m| self.mob_team(m.id).cloned()).collect() + }; + push_apart(&mut mobs, &teams); } self.mobs.append(&mut mobs); self.sync_riders(); @@ -667,18 +675,21 @@ impl Game<'_> { MobEvent::Shoot(..) => {} MobEvent::Explode(at, radius) => { // The exploding mob causes the damage (Creeper.explodeCreeper). - if let Some(id) = self + let source_mob = self .mobs .iter() .filter(|m| { (m.position.x - at[0]).powi(2) + (m.position.z - at[2]).powi(2) < 1.0 }) .map(|m| m.id) - .next() - { + .next(); + if let Some(id) = source_mob { self.note_attacker("minecraft:explosion", id); } - self.explode(at, radius)? + self.combat.explosion_source = source_mob; + let result = self.explode(at, radius); + self.combat.explosion_source = None; + result? } MobEvent::AttackMob { target, @@ -2421,8 +2432,12 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack { } item } -/// Entity.push between overlapping mobs (LivingEntity.pushEntities). -fn push_apart(mobs: &mut [Mob]) { +/// Entity.push between overlapping mobs (LivingEntity.pushEntities), unless +/// their teams' collision rules keep both from pushing the other (`teams` +/// holds each mob's team, or is empty when there are no teams). +fn push_apart(mobs: &mut [Mob], teams: &[Option]) { + use horizon_client::scoreboard::pushable_by; + let team = |i: usize| teams.get(i).and_then(Option::as_ref); let n = mobs.len(); for i in 0..n { if !mobs[i].alive() { @@ -2437,6 +2452,12 @@ fn push_apart(mobs: &mut [Mob]) { if mobs[i].extra.mount == Some(mobs[j].id) || mobs[j].extra.mount == Some(mobs[i].id) { continue; } + if !teams.is_empty() + && !pushable_by(team(i), team(j), true) + && !pushable_by(team(j), team(i), true) + { + continue; + } let (dx, dz) = ( mobs[j].position.x - mobs[i].position.x, mobs[j].position.z - mobs[i].position.z, diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 4bd13bd15..3119591b0 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -191,6 +191,15 @@ impl Game<'_> { [d[0] / l, d[1] / l, d[2] / l] } }; + // `source.doTeamsAllowDamage(entity)`: the exploding mob spares its + // team mates when its team has no friendly fire (they are still pushed). + let exploding = self.combat.explosion_source; + let teams_allow = |g: &Self, victim: Option<&horizon_client::scoreboard::Team>| { + exploding.is_none_or(|id| { + horizon_client::scoreboard::teams_allow_damage(g.mob_team(id), victim) + }) + }; + let player_hurtable = teams_allow(self, self.player_team()); // Player. if let Some(p) = self.player.as_ref() { let feet = [p.position.x, p.position.y, p.position.z]; @@ -217,7 +226,7 @@ impl Game<'_> { && let Some(id) = self.motion.health.damage.id("minecraft:explosion") { // Creative players are invulnerable to explosions. - if !creative { + if !creative && player_hurtable { hurt = p .hurt(&self.motion.health, self.world.health_rules, id, amount) .unwrap_or(false); @@ -236,6 +245,7 @@ impl Game<'_> { // Mobs. let mut mobs = std::mem::take(&mut self.mobs); for m in mobs.iter_mut().filter(|m| m.alive()) { + let hurtable = teams_allow(self, self.mob_team(m.id)); let feet = [m.position.x, m.position.y, m.position.z]; let dist = distance(feet) / diameter; if dist > 1.0 { @@ -253,7 +263,7 @@ impl Game<'_> { attacker: None, from: Some(center), }; - if !m.damage(damage(dist, exposure), source) { + if hurtable && !m.damage(damage(dist, exposure), source) { continue; } let dir = direction(eye); diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 14a6220cf..224ce17e0 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -1,9 +1,11 @@ //! Custom names: `NameTagItem.interactLivingEntity` and the name tag //! (`EntityRenderer.submitNameTag`): above the head, facing the camera, //! on a translucent black background, shown when the name is visible or the -//! mob is under the crosshair within 64 blocks. +//! mob is under the crosshair within 64 blocks, as its team's name tag +//! visibility allows, in the team's colours, with its score in the +//! objective displayed below names. use super::{Game, view_vector}; -use horizon_client::mesher::Vertex; +use horizon_client::{mesher::Vertex, save::uuid_text, scoreboard as sb, text::Text}; impl Game<'_> { /// A named name tag names the mob under the crosshair. @@ -26,17 +28,37 @@ impl Game<'_> { self.swing_arm(); true } + /// `Entity.belowNameDisplay`: the mob's score in the objective shown below + /// names, then a space and the objective's name. + fn below_name_text(&self, id: u32) -> Option { + let board = &self.score.board; + let objective = board.display_objective(sb::SLOT_BELOW_NAME)?; + let uuid = self.persist.uuids.get(&id)?; + let score = board.score(&uuid_text(*uuid), &objective.name)?; + // numberFormatOrDefault(StyledFormat.NO_STYLE). + let format = score + .number_format + .clone() + .or_else(|| objective.number_format.clone()) + .unwrap_or(sb::NumberFormat::Styled(serde_json::json!({}))); + let mut t = Text::empty(); + t.push(format.format(score.value)); + t.push(Text::literal(" ")); + t.push(objective.display_text()); + Some(t) + } pub(super) fn name_tag_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let target = self.mob_hit().map(|(i, _)| self.mobs[i].id); 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 white = self.res.atlas.font.white(); + let viewer = self.player_team(); for m in &self.mobs { let Some(name) = m.custom_name.as_deref() else { continue; }; - if !(m.name_visible || Some(m.id) == target) || !m.alive() { + if !m.alive() { continue; } let p = glam::DVec3::new( @@ -44,19 +66,48 @@ impl Game<'_> { m.previous.y + (m.position.y - m.previous.y) * alpha + f64::from(m.height()) + 0.5, m.previous.z + (m.position.z - m.previous.z) * alpha, ); - if p.distance_squared(camera) >= 64.0 * 64.0 { + // The name tag distance (64) is measured to the entity. + let distance_sqr = + glam::DVec3::new(m.position.x, m.position.y, m.position.z).distance_squared(camera); + if distance_sqr >= 64.0 * 64.0 { continue; } - let o = (p - camera).as_vec3(); - let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025); - // Text space: x right, y down (scale 0.025, -0.025). - let at = |x: f32, y: f32| o + r * x - u * y; - let width: f32 = name - .chars() - .map(|c| self.res.atlas.glyph(c).map_or(6.0, |g| g.1)) - .sum(); - let x0 = -(width / 2.0).trunc(); - let y0 = if name == "deadmau5" { -10.0 } else { 0.0 }; + let team = self.mob_team(m.id); + // LivingEntityRenderer.shouldShowName (team rules included), then + // MobRenderer: a visible name, or the mob under the crosshair. + let invisible = sb::invisible_to( + team, + viewer, + self.spectator(), + m.has_effect("minecraft:invisibility"), + ); + let view = sb::NameView { + discrete: false, + distance_sqr, + invisible_to_viewer: invisible, + hud_hidden: self.ui.hide_gui, + is_camera: false, + is_vehicle: self.mobs.iter().any(|o| o.extra.mount == Some(m.id)), + }; + if !sb::name_shown(team, viewer, view) || !(m.name_visible || Some(m.id) == target) { + continue; + } + // getDisplayName: the custom name in the team's prefix, suffix and colour. + let shown = match team { + Some(t) => t.formatted_name(Text::literal(name)), + None => Text::literal(name), + }; + let mut lines = Vec::new(); + // EntityRenderer.extractNameTags: the score shows within the + // below-name distance (10), under the name. + let mut lift = 0.0; + if distance_sqr < 10.0 * 10.0 + && let Some(score) = self.below_name_text(m.id) + { + lines.push((score, 0.0)); + lift = f64::from(9.0f32 * 1.15 * 0.025); + } + lines.push((shown, lift)); let l = self.world.light( m.position.x.floor() as i32, (m.position.y + f64::from(m.height())).floor() as i32, @@ -64,48 +115,77 @@ impl Game<'_> { ); let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); let away = forward.as_vec3() * 0.002; - // `background`: unlit (vertex colour only) and a hair behind the text. - let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| { - let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])]; - let uvs = [ - [uv[0], uv[3]], - [uv[2], uv[3]], - [uv[2], uv[1]], - [uv[0], uv[1]], - ]; - for ((x, y), uv) in corners.into_iter().zip(uvs) { - out.push(Vertex { - pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO }) - .to_array(), - uv, - layer: if background { 2 } else { 0 }, - color, - light, - }); - } - }; - // Background: Options.getBackgroundOpacity(0.25) black. - quad( - [x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0], - [white.u0, white.v0, white.u1, white.v1], - 0x40_00_00_00, - true, - ); - let mut x = x0; - for ch in name.chars() { - let Some((g, advance)) = self.res.atlas.glyph(ch) else { - x += 6.0; - continue; + for (text, lift) in lines { + let o = (p + glam::DVec3::new(0.0, lift, 0.0) - camera).as_vec3(); + let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025); + // Text space: x right, y down (scale 0.025, -0.025). + let at = |x: f32, y: f32| o + r * x - u * y; + let chars: Vec<(char, u32)> = text + .spans + .iter() + .flat_map(|s| { + let rgb = s.style.color.unwrap_or(0xFF_FF_FF); + // RGBA8, alpha in the top byte. + let color = 0xFF00_0000 + | ((rgb & 0xFF) << 16) + | (rgb & 0xFF00) + | ((rgb >> 16) & 0xFF); + s.text.chars().map(move |c| (c, color)) + }) + .collect(); + let width: f32 = chars + .iter() + .map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1)) + .sum(); + let x0 = -(width / 2.0).trunc(); + let y0 = if text.plain() == "deadmau5" { + -10.0 + } else { + 0.0 }; - if ch != ' ' { - quad( - [x, y0, x + 8.0, y0 + 8.0], - [g.u0, g.v0, g.u1, g.v1], - 0xFFFF_FFFF, - false, - ); + // `background`: unlit (vertex colour only) and a hair behind the text. + let mut quad = |a: [f32; 4], uv: [f32; 4], color: u32, background: bool| { + let corners = [(a[0], a[3]), (a[2], a[3]), (a[2], a[1]), (a[0], a[1])]; + let uvs = [ + [uv[0], uv[3]], + [uv[2], uv[3]], + [uv[2], uv[1]], + [uv[0], uv[1]], + ]; + for ((x, y), uv) in corners.into_iter().zip(uvs) { + out.push(Vertex { + pos: (at(x, y) + if background { away } else { glam::Vec3::ZERO }) + .to_array(), + uv, + layer: if background { 2 } else { 0 }, + color, + light, + }); + } + }; + // Background: Options.getBackgroundOpacity(0.25) black. + quad( + [x0 - 1.0, y0 - 1.0, x0 + width, y0 + 8.0], + [white.u0, white.v0, white.u1, white.v1], + 0x40_00_00_00, + true, + ); + let mut x = x0; + for (ch, color) in chars { + let Some((g, advance)) = self.res.atlas.glyph(ch) else { + x += 6.0; + continue; + }; + if ch != ' ' { + quad( + [x, y0, x + 8.0, y0 + 8.0], + [g.u0, g.v0, g.u1, g.v1], + color, + false, + ); + } + x += advance; } - x += advance; } } } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index d6962d674..eec1be6fb 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -20,7 +20,8 @@ use std::collections::HashSet; /// What `ServerPlayer` last recorded for the criteria that follow the player. #[derive(Default)] pub(super) struct Recorded { - health: Option, + /// `lastRecordedHealthAndAbsorption` (compared as a float). + health_and_absorption: Option, food: Option, air: Option, armor: Option, @@ -306,18 +307,29 @@ impl Game<'_> { }); } } + let display = self.player_display_comp(); if let Some(p) = self.player.as_mut() { - let health = (p.health.health() + p.health.absorption()).ceil() as i32; + let health_and_absorption = p.health.health() + p.health.absorption(); let food = p.health.food.food; + // getArmorValue: the armor attribute rounded down. let armor = p .attribute("minecraft:armor") .or_else(|_| p.attribute("armor")) .unwrap_or(0.0) - .ceil() as i32; + .floor() as i32; let rec = &mut self.score.recorded; let board = &mut self.score.board; + if rec.health_and_absorption != Some(health_and_absorption) { + rec.health_and_absorption = Some(health_and_absorption); + let value = health_and_absorption.ceil() as i32; + board.for_all_objectives_with( + sb::CRITERIA_HEALTH, + PLAYER_NAME, + Some(&display), + |_| value, + ); + } for (criteria, last, value) in [ - (sb::CRITERIA_HEALTH, &mut rec.health, health), (sb::CRITERIA_FOOD, &mut rec.food, food), // The air supply is full unless the player is drowning. (sb::CRITERIA_AIR, &mut rec.air, 300), @@ -327,7 +339,12 @@ impl Game<'_> { ] { if *last != Some(value) { *last = Some(value); - board.for_all_objectives(criteria, PLAYER_NAME, |_| value); + board.for_all_objectives_with( + criteria, + PLAYER_NAME, + Some(&display), + |_| value, + ); } } } @@ -338,29 +355,39 @@ impl Game<'_> { } /// `ServerPlayer.die`: the death count. pub(super) fn score_player_died(&mut self) { + let display = self.player_display_comp(); let board = &mut self.score.board; - board.for_all_objectives(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, |v| v + 1); + board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| { + v.wrapping_add(1) + }); // A respawned player has everything to record again. self.score.recorded = Recorded::default(); } /// `ServerPlayer.awardKillScore`: total kills and the team kill counts. pub(super) fn score_player_killed(&mut self, victim: Target) { let victim_name = self.holder_name(victim); + let display = self.player_display_comp(); let board = &mut self.score.board; - board.for_all_objectives(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, |v| v + 1); + let inc = |v: i32| v.wrapping_add(1); + board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc); if victim == Target::Player { - board.for_all_objectives(sb::CRITERIA_PLAYER_KILLS, PLAYER_NAME, |v| v + 1); + board.for_all_objectives_with( + sb::CRITERIA_PLAYER_KILLS, + PLAYER_NAME, + Some(&display), + inc, + ); } let color_of = |board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone()); if let Some(victim_name) = victim_name { if let Some(color) = color_of(board, &victim_name) { let criteria = format!("teamkill.{color}"); - board.for_all_objectives(&criteria, PLAYER_NAME, |v| v + 1); + board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc); } if let Some(color) = color_of(board, PLAYER_NAME) { let criteria = format!("killedByTeam.{color}"); - board.for_all_objectives(&criteria, &victim_name, |v| v + 1); + board.for_all_objectives(&criteria, &victim_name, inc); } } } @@ -369,9 +396,44 @@ impl Game<'_> { let Some(uuid) = self.persist.uuids.get(&id).copied() else { return; }; - let name = uuid_text(uuid); - self.score.board.reset_all(&name); - self.score.board.remove_from_team(&name); + self.score.board.entity_removed(&uuid_text(uuid)); + } + + // ---- teams in gameplay ----------------------------------------------------- + + /// `Entity.getTeam` of a mob (a mob joins a team by its UUID). + pub(super) fn mob_team(&self, id: u32) -> Option<&sb::Team> { + let uuid = self.persist.uuids.get(&id)?; + self.score.board.players_team(&uuid_text(*uuid)) + } + pub(super) fn player_team(&self) -> Option<&sb::Team> { + self.score.board.players_team(PLAYER_NAME) + } + /// The mobs on the player's team (`isAlliedTo`). + pub(super) fn player_allies(&self) -> HashSet { + let Some(team) = self.player_team() else { + return HashSet::new(); + }; + self.persist + .uuids + .iter() + .filter(|(_, uuid)| team.players.contains(&uuid_text(**uuid))) + .map(|(id, _)| *id) + .collect() + } + /// `Player.getDisplayName`: the name with the team's prefix, suffix and colour. + pub(super) fn player_display_comp(&self) -> Comp { + let name = literal(PLAYER_NAME); + match self.player_team() { + Some(t) => t.formatted_name_comp(&name), + None => name, + } + } + pub(super) fn player_display_text(&self) -> Text { + match self.player_team() { + Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)), + None => Text::literal(PLAYER_NAME), + } } // ---- commands ------------------------------------------------------------ diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index e6dd71e45..577847f71 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -904,6 +904,9 @@ pub struct PlayerView { pub hero: bool, /// The player's UUID (villagers' gossip is keyed by it). pub uuid: [i32; 4], + /// The mobs on the player's team (`isAlliedTo`): combat targeting + /// leaves the player alone. + pub allies: std::sync::Arc>, } pub struct MobWorld<'a> { pub world: &'a World, diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c5439479b..2b74bb42a 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -397,7 +397,8 @@ impl Mob { /// creative, within range scaled by visibility, optionally visible. pub fn can_target_player(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { let Some(p) = &w.player else { return false }; - if !p.alive || p.creative { + // TargetingConditions.isCombat: never an ally. + if !p.alive || p.creative || p.allies.contains(&self.id) { return false; } let mut visibility = 1.0;