From e28d1a58903bc383dc2e500a093b02b6297008c9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 9 Oct 2026 04:59:58 +0200 Subject: [PATCH] Add the ender dragon fight The dragon with its phases, path nodes, fireballs and breath, end crystals that heal it, the boss bar and boss music, and the kill: XP, the exit portal, the egg and a new gateway. The fight state is saved where 26.3 saves it. Creative players are now invulnerable, as in vanilla. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 28 +- crates/horizon-client/src/game/control.rs | 7 + crates/horizon-client/src/game/creatures.rs | 19 + crates/horizon-client/src/game/dragon.rs | 2265 +++++++++++++++++++ crates/horizon-client/src/game/end.rs | 62 +- crates/horizon-client/src/game/explosion.rs | 1 + crates/horizon-client/src/game/music.rs | 4 + crates/horizon-client/src/game/persist.rs | 32 + crates/horizon-client/src/health.rs | 8 +- crates/horizon-client/src/hunger.rs | 1 + crates/horizon-client/src/motion.rs | 3 + 11 files changed, 2406 insertions(+), 24 deletions(-) create mode 100644 crates/horizon-client/src/game/dragon.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b88712438..743f2c377 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -11,6 +11,7 @@ mod commands; mod control; mod creatures; mod crossbow; +mod dragon; mod enchant_effects; mod end; mod explosion; @@ -569,6 +570,13 @@ struct Game<'a> { jukebox_sounds: HashMap<(i32, i32, i32), u64>, bolts: Vec, maps: maps::Maps, + /// The ender dragon fight (game/dragon.rs). + fight: dragon::Fight, + dragon: Option, + crystals: Vec, + dragon_fireballs: Vec, + breath_clouds: Vec, + dragon_model: Option, /// Map textures waiting for the next HUD batch to upload them. map_patches: Vec, cart_models: minecarts::CartModels, @@ -2084,6 +2092,7 @@ impl Game<'_> { let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; player.may_fly = self.creative; + player.invulnerable = self.creative; player.pitch = self.pitch; // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { @@ -2166,6 +2175,7 @@ impl Game<'_> { } player.yaw = self.yaw; player.may_fly = self.creative; + player.invulnerable = self.creative; player.pitch = self.pitch; // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { @@ -2679,6 +2689,7 @@ impl Game<'_> { } self.draw_effect_icons(&mut batch); // Hud: the action bar and titles draw over the hotbar (nextStratum). + self.draw_boss_bar(&mut batch); self.draw_titles(&mut batch); let atlas = &self.res.atlas; if !self.creative @@ -3969,6 +3980,7 @@ impl Game<'_> { || self.attack_armor_stand() || self.attack_boat(hand_damage) || self.attack_cart(hand_damage) + || self.attack_dragon() { return true; } @@ -6269,6 +6281,7 @@ impl Game<'_> { .save(&chunks, self.res.assets.registry, &self.res.biomes)?; self.save_entities()?; self.save_maps(); + self.save_fight(); self.level.selected_slot = self.selected as i32; let level = &mut self.level; level.creative = self.creative; @@ -6430,7 +6443,7 @@ impl Game<'_> { // Map textures changed since the last drawn frame (game/maps.rs). hud.patches.append(&mut self.map_patches); let title = self.title.is_some(); - let entities = if title { + let mut entities = if title { Vec::new() } else { self.entity_geometry(camera, alpha) @@ -6438,6 +6451,12 @@ impl Game<'_> { let mut additive = Vec::new(); if !title { self.bolt_geometry(camera, &mut additive); + if self.dim == Dim::End { + let mut dragon = Vec::new(); + self.dragon_geometry(camera, alpha, &mut dragon, &mut additive); + self.dragon_fireball_geometry(camera, alpha, &mut dragon); + entities.extend(dragon); + } } let celestial = if title { self.panorama_geometry() @@ -6458,7 +6477,6 @@ impl Game<'_> { } else { self.screen_quads(alpha as f32, size) }; - let mut entities = entities; if !title { self.end_geometry(camera, &mut entities); } @@ -7366,6 +7384,12 @@ pub fn run() -> Result<()> { jukebox_sounds: HashMap::new(), bolts: Vec::new(), maps: maps::Maps::default(), + fight: dragon::Fight::default(), + dragon: None, + crystals: Vec::new(), + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), map_patches: Vec::new(), cart_models: minecarts::CartModels::load(&root), riding: None, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index b8d6300d0..d5eccb14b 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -386,6 +386,12 @@ impl Game<'_> { self.save_game()?; ok() } + "dragon-hurt" => { + // Test hook: damage the dragon's head as the player would. + let amount: f32 = arg(1)?.parse()?; + self.hit_special(super::dragon::SPECIAL, amount, true); + ok() + } "quit" => { if self.title.is_none() { // Player.closeContainer: menu items go back before saving. @@ -482,6 +488,7 @@ impl Game<'_> { "fishing": self.hook_status(), "tridents": self.tridents.len(), "rockets": self.rockets.len(), + "fight": self.dragon_status(), "carts": self.carts.iter().map(|c| serde_json::json!({"kind": c.kind.id(), "position": [c.position.x, c.position.y, c.position.z], "velocity": [c.velocity.x, c.velocity.y, c.velocity.z]})).collect::>(), "riding": self.riding, "using": self.using, diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 37d5769a7..6e9fe2111 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -956,6 +956,12 @@ impl Game<'_> { { targets.push((Who::Player, p.bounds)); } + // Dragon parts and end crystals under reserved ids (game/dragon.rs). + targets.extend( + self.special_targets() + .into_iter() + .map(|(id, b)| (Who::Mob(id), b)), + ); let w = self.mob_world_base(&[]); let pw = ProjWorld { w: &w, targets }; projectiles.retain_mut(|p| { @@ -977,6 +983,19 @@ impl Game<'_> { Hit::Entity { at, .. } | Hit::Block { at, .. } => at, Hit::None => return Ok(()), }; + if let Hit::Entity { + who: Who::Mob(id), .. + } = hit + && id >= super::dragon::SPECIAL + { + let amount = match p.kind { + ProjectileKind::Arrow { .. } => p.arrow_damage(&mut self.world.random), + ProjectileKind::SmallFireball | ProjectileKind::LargeFireball { .. } => 6.0, + _ => 0.0, + }; + self.hit_special(id, amount, p.owner == Some(Who::Player)); + return Ok(()); + } let atp = [at.x, at.y, at.z]; let source_kind = match p.kind { ProjectileKind::Arrow { .. } => DamageKind::Arrow, diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs new file mode 100644 index 000000000..ca926f3f5 --- /dev/null +++ b/crates/horizon-client/src/game/dragon.rs @@ -0,0 +1,2265 @@ +//! The ender dragon fight (`EnderDragonFight`, `EnderDragon`, its phases, +//! `EndCrystal`, `DragonFireball`): the fight state saved in the End's +//! `ender_dragon_fight.dat`, the dragon spawned over the island, the +//! holding pattern over the 24-node path graph, strafing with fireballs, +//! landing on the podium to breathe and charge, healing from the crystals on +//! the spikes, its parts (head and neck take full damage, the rest a quarter +//! plus one), wing knockback, block breaking, the death flight and rays, the +//! exit portal, the egg and the next gateway; and its rendering and boss bar. +use super::{Dim, Game}; +use horizon_client::{ + hud::{HudBatch, rgba}, + mesher::Vertex, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::{LegacyRandom, RandomSource}, +}; +use horizon_world::nbt::Tag; + +/// Mob ids from here on are dragon parts (`SPECIAL + part`) and crystals +/// (`SPECIAL + 16 + crystal`), so projectiles can target them. +pub(super) const SPECIAL: u32 = u32::MAX - 4096; +const CRYSTAL_IDS: u32 = SPECIAL + 16; +const FIGHT_FILE: &str = "data/minecraft/ender_dragon_fight.dat"; +const MAX_HEALTH: f32 = 200.0; + +#[derive(Default)] +pub(super) struct Fight { + loaded: bool, + needs_scan: bool, + pub killed: bool, + pub previously_killed: bool, + gateways: Vec, + exit_portal: Option<[i32; 3]>, + alive_crystals: i32, + crystal_scan: i32, + /// The spikes' crystals have been placed (worldgen does not place entities here). + crystals_placed: bool, + dirty: bool, +} +#[derive(Clone, Debug)] +pub(super) struct Crystal { + pub position: Vec3, + pub show_bottom: bool, + /// EndCrystal.time (the bob and spin), starting random. + pub time: i32, + pub beam: Option<[i32; 3]>, +} +#[derive(Clone, Debug, Default)] +struct Path { + nodes: Vec<[i32; 3]>, + next: usize, +} +impl Path { + fn done(&self) -> bool { + self.next >= self.nodes.len() + } + fn advance(&mut self) { + self.next += 1; + } + fn next_pos(&self) -> [i32; 3] { + self.nodes[self.next] + } +} +#[derive(Clone, Debug, PartialEq)] +enum Phase { + Holding { + path: Option, + target: Option, + clockwise: bool, + }, + Strafe { + charge: i32, + path: Option, + target: Option, + clockwise: bool, + }, + LandingApproach { + path: Option, + target: Option, + }, + Landing { + target: Option, + }, + Takeoff { + first: bool, + path: Option, + target: Option, + }, + Scanning { + time: i32, + }, + Attacking { + ticks: i32, + }, + Flaming { + ticks: i32, + }, + Charging { + target: Option, + since: i32, + }, + Dying { + target: Option, + time: i32, + }, + Hover { + target: Option, + }, +} +/// A path compared by identity only (phases compare by kind). +#[derive(Clone, Debug)] +struct PathBox(Path); +impl PartialEq for PathBox { + fn eq(&self, _: &Self) -> bool { + true + } +} +impl Phase { + /// `EnderDragonPhase` ids. + fn id(&self) -> i32 { + match self { + Self::Holding { .. } => 0, + Self::Strafe { .. } => 1, + Self::LandingApproach { .. } => 2, + Self::Landing { .. } => 3, + Self::Takeoff { .. } => 4, + Self::Flaming { .. } => 5, + Self::Scanning { .. } => 6, + Self::Attacking { .. } => 7, + Self::Charging { .. } => 8, + Self::Dying { .. } => 9, + Self::Hover { .. } => 10, + } + } + fn from_id(id: i32) -> Self { + match id { + 1 => Self::Strafe { + charge: 0, + path: None, + target: None, + clockwise: false, + }, + 2 => Self::LandingApproach { + path: None, + target: None, + }, + 3 => Self::Landing { target: None }, + 4 => Self::Takeoff { + first: true, + path: None, + target: None, + }, + 5 => Self::Flaming { ticks: 0 }, + 6 => Self::Scanning { time: 0 }, + 7 => Self::Attacking { ticks: 0 }, + 8 => Self::Charging { + target: None, + since: 0, + }, + 9 => Self::Dying { + target: None, + time: 0, + }, + 10 => Self::Hover { target: None }, + _ => Self::Holding { + path: None, + target: None, + clockwise: false, + }, + } + } + fn sitting(&self) -> bool { + matches!( + self, + Self::Scanning { .. } + | Self::Attacking { .. } + | Self::Flaming { .. } + | Self::Hover { .. } + ) + } + fn target(&self) -> Option { + match self { + Self::Holding { target, .. } + | Self::Strafe { target, .. } + | Self::LandingApproach { target, .. } + | Self::Landing { target } + | Self::Takeoff { target, .. } + | Self::Charging { target, .. } + | Self::Dying { target, .. } + | Self::Hover { target } => *target, + _ => None, + } + } + fn fly_speed(&self) -> f32 { + match self { + Self::Landing { .. } => 1.5, + Self::Charging { .. } | Self::Dying { .. } => 3.0, + _ => 0.6, + } + } +} +pub(super) struct Dragon { + pub position: Vec3, + pub previous: Vec3, + velocity: Vec3, + pub yaw: f32, + pub previous_yaw: f32, + yaw_accel: f32, + pub health: f32, + pub hurt_time: i32, + invulnerable: i32, + pub death_time: i32, + pub flap: f32, + pub old_flap: f32, + in_wall: bool, + phase: Phase, + flame_count: i32, + sitting_damage: f32, + growl: i32, + ticks: i32, + /// DragonFlightHistory: (y, yRot) samples, newest at `head`. + history: [(f64, f32); 64], + head: usize, + /// head, neck, body, tail1-3, wing1-2. + pub parts: [(Vec3, Vec3); 8], + nodes: Option<[[i32; 3]; 24]>, + nearest_crystal: Option, + random: LegacyRandom, +} +const PART_SIZES: [(f64, f64); 8] = [ + (1.0, 1.0), + (3.0, 3.0), + (5.0, 3.0), + (2.0, 2.0), + (2.0, 2.0), + (2.0, 2.0), + (4.0, 2.0), + (4.0, 2.0), +]; +const ADJACENCY: [u32; 24] = [ + 6146, 8197, 8202, 16404, 32808, 32848, 65696, 131392, 131712, 263424, 526848, 525313, 1581057, + 3166214, 2138120, 6373424, 4358208, 12910976, 9044480, 9706496, 15216640, 13688832, 11763712, + 8257536, +]; +impl Dragon { + fn new(position: Vec3, yaw: f32, seed: i64) -> Self { + Self { + position, + previous: position, + velocity: Vec3::ZERO, + yaw, + previous_yaw: yaw, + yaw_accel: 0.0, + health: MAX_HEALTH, + hurt_time: 0, + invulnerable: 0, + death_time: 0, + flap: 0.0, + old_flap: 0.0, + in_wall: false, + phase: Phase::Holding { + path: None, + target: None, + clockwise: false, + }, + flame_count: 0, + sitting_damage: 0.0, + growl: 100, + ticks: 0, + history: [(position.y, yaw); 64], + head: 0, + parts: [(position, position); 8], + nodes: None, + nearest_crystal: None, + random: LegacyRandom::new(seed), + } + } + /// DragonFlightHistory.record. + fn record(&mut self) { + self.head = (self.head + 1) & 63; + self.history[self.head] = (self.position.y, self.yaw); + } + /// DragonFlightHistory.get(delay). + fn sample(&self, delay: usize) -> (f64, f32) { + self.history[(self.head + 64 - (delay & 63)) & 63] + } + /// DragonFlightHistory.get(delay, partial). + fn sample_lerp(&self, delay: usize, partial: f32) -> (f64, f32) { + let a = self.sample(delay); + let b = self.sample(delay + 1); + let yaw = b.1 + wrap(a.1 - b.1) * partial; + (b.0 + (a.0 - b.0) * f64::from(partial), yaw) + } + pub fn alive(&self) -> bool { + self.health > 0.0 + } + fn part_box(&self, i: usize) -> Aabb { + let (w, h) = PART_SIZES[i]; + let p = self.parts[i].0; + Aabb::new( + Vec3::new(p.x - w / 2.0, p.y, p.z - w / 2.0), + Vec3::new(p.x + w / 2.0, p.y + h, p.z + w / 2.0), + ) + } + fn set_phase(&mut self, phase: Phase) { + if self.phase.id() == phase.id() && phase.id() != 1 { + return; + } + if let Phase::Flaming { .. } = phase { + self.flame_count += 1; + } + self.phase = phase; + } +} +fn wrap(d: f32) -> f32 { + let r = d.rem_euclid(360.0); + if r >= 180.0 { r - 360.0 } else { r } +} +fn wrap64(d: f64) -> f64 { + let r = d.rem_euclid(360.0); + if r >= 180.0 { r - 360.0 } else { r } +} +impl Game<'_> { + fn fight_path(&self) -> std::path::PathBuf { + horizon_client::save::dimension_dir(&self.world_root, "minecraft:the_end").join(FIGHT_FILE) + } + /// The saved fight, or `createDefault` with the gateways shuffled by the seed. + fn load_fight(&mut self) { + if self.fight.loaded { + return; + } + let tag = horizon_client::save::read_dat(&self.fight_path()); + let data = tag.as_ref().and_then(|t| t.get("data")); + let flag = |k: &str, default: bool| match data.and_then(|d| d.get(k)) { + Some(Tag::Byte(v)) => *v != 0, + _ => default, + }; + let mut fight = Fight { + loaded: true, + needs_scan: flag("needs_state_scanning", true), + killed: flag("dragon_killed", false), + previously_killed: flag("previously_killed", false), + crystals_placed: flag("horizon_crystals_placed", false), + gateways: match data.and_then(|d| d.get("gateways")) { + Some(Tag::IntArray(v)) => v.clone(), + Some(Tag::List(v)) => v + .iter() + .filter_map(|t| match t { + Tag::Int(i) => Some(*i), + _ => None, + }) + .collect(), + _ => Vec::new(), + }, + exit_portal: match data.and_then(|d| d.get("exit_portal_location")) { + Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), + _ => None, + }, + ..Default::default() + }; + if fight.gateways.is_empty() { + // Util.shuffle(0..20, RandomSource.create(seed)). + let mut gateways: Vec = (0..20).collect(); + let mut random = LegacyRandom::new(self.level.seed); + for i in (2..=gateways.len()).rev() { + let j = random.next_int_bound(i as i32).unwrap_or(0) as usize; + gateways.swap(i - 1, j); + } + fight.gateways = gateways; + fight.dirty = true; + } + // A world from before this fight existed: one with an active portal + // already won it. + if tag.is_none() && self.end_portal_active() { + fight.killed = true; + fight.previously_killed = true; + fight.crystals_placed = true; + fight.needs_scan = false; + } + self.fight = fight; + } + fn end_portal_active(&self) -> bool { + (0..256).any(|y| { + &*self.res.facts.get(self.world.block(0, y, 0)).name == "minecraft:bedrock" + && (-3..=3).any(|d| { + &*self.res.facts.get(self.world.block(d, y, 0)).name == "minecraft:end_portal" + }) + }) + } + pub(super) fn save_fight(&mut self) { + if !self.fight.loaded || !self.fight.dirty { + return; + } + + let f = &self.fight; + let b = |v: bool| Tag::Byte(i8::from(v)); + let mut data = vec![ + ("needs_state_scanning", b(f.needs_scan)), + ("dragon_killed", b(f.killed)), + ("previously_killed", b(f.previously_killed)), + ("respawn_time", Tag::Int(0)), + ("gateways", Tag::IntArray(f.gateways.clone())), + ("horizon_crystals_placed", b(f.crystals_placed)), + ]; + if let Some(p) = f.exit_portal { + data.push(("exit_portal_location", Tag::IntArray(p.to_vec()))); + } + let tag = Tag::compound([ + ("data", Tag::compound(data)), + ("DataVersion", Tag::Int(horizon_world::DATA_VERSION)), + ]); + if horizon_client::save::write_dat(&self.fight_path(), tag).is_ok() { + self.fight.dirty = false; + } + } + /// The island's centre chunks are lit (the arena is "loaded"). + fn arena_loaded(&self) -> bool { + (-2..=1).all(|cz| (-2..=1).all(|cx| self.streaming.is_lit(cx, cz))) + } + /// `EnderDragonFight.tick` while the player is in the End. + pub(super) fn tick_fight(&mut self) { + if self.dim != Dim::End || self.travelling.is_some() { + return; + } + self.load_fight(); + if !self.arena_loaded() { + return; + } + if self.fight.needs_scan { + // scanState: a missing exit portal means a fight in progress. + self.fight.previously_killed = self.end_portal_active(); + if !self.fight.previously_killed { + self.fight.killed = false; + } + self.fight.needs_scan = false; + self.fight.dirty = true; + } + if !self.fight.crystals_placed { + self.place_spike_crystals(); + self.fight.crystals_placed = true; + self.fight.dirty = true; + } + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let near = p.x.powi(2) + (p.y - 128.0).powi(2) + p.z.powi(2) <= 192.0 * 192.0; + if !self.fight.killed && near && self.dragon.is_none() { + // createNewDragon: over the podium, holding pattern, a random yaw. + let yaw = self.world.random.next_float() * 360.0; + let seed = self.world.random.next_long(); + self.dragon = Some(Dragon::new(Vec3::new(0.0, 128.0, 0.0), yaw, seed)); + } + self.fight.crystal_scan += 1; + if self.fight.crystal_scan >= 100 { + self.count_crystals(); + } + self.tick_crystals(); + self.tick_dragon(); + } + /// EndSpikeFeature's crystals (with fire under them on the bedrock). + fn place_spike_crystals(&mut self) { + for spike in horizon_world::worldgen::end_spike::spikes_for_seed(self.level.seed) { + let at = Vec3::new( + f64::from(spike.center_x) + 0.5, + f64::from(spike.height + 1), + f64::from(spike.center_z) + 0.5, + ); + if self + .crystals + .iter() + .any(|c| (c.position.x - at.x).abs() < 1.0 && (c.position.z - at.z).abs() < 1.0) + { + continue; + } + let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + self.crystals.push(Crystal { + position: at, + show_bottom: true, + time, + beam: None, + }); + self.world + .modified + .insert((at.x.floor() as i32 >> 4, at.z.floor() as i32 >> 4)); + } + } + /// `updateCrystalCount`: crystals on the spike tops. + fn count_crystals(&mut self) { + self.fight.crystal_scan = 0; + let spikes = horizon_world::worldgen::end_spike::spikes_for_seed(self.level.seed); + self.fight.alive_crystals = self + .crystals + .iter() + .filter(|c| { + spikes.iter().any(|s| { + (c.position.x - f64::from(s.center_x) - 0.5).abs() <= f64::from(s.radius) + && (c.position.z - f64::from(s.center_z) - 0.5).abs() <= f64::from(s.radius) + && c.position.y >= f64::from(s.height) + }) + }) + .count() as i32; + } + /// `EndCrystal.tick`: the time and the fire below it in the End. + fn tick_crystals(&mut self) { + let fire = self.res.assets.registry.default_state("minecraft:fire"); + for i in 0..self.crystals.len() { + self.crystals[i].time += 1; + let p = self.crystals[i].position; + let b = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; + if let Some(fire) = fire + && self.res.facts.is_air(self.world.block(b[0], b[1], b[2])) + && self.world.loaded(b[0], b[2]) + { + let _ = self.level_set(b, fire); + } + } + } + /// A crystal took damage: `EndCrystal.hurtServer` blows it up (power 6). + fn destroy_crystal(&mut self, index: usize, by_player: bool) { + if index >= self.crystals.len() { + return; + } + let c = self.crystals.remove(index); + let at = [c.position.x, c.position.y, c.position.z]; + let _ = self.server_explode(at, 6.0, super::explosion::BlockInteraction::Destroy, false); + // EnderDragonFight.onCrystalDestroyed. + self.count_crystals(); + if let Some(d) = self.dragon.as_mut() { + if d.nearest_crystal == Some(index) { + d.nearest_crystal = None; + self.hurt_dragon(0, 10.0, true); + } else if let Some(n) = d.nearest_crystal.as_mut() + && *n > index + { + *n -= 1; + } + if by_player + && let Some(d) = self.dragon.as_mut() + && matches!(d.phase, Phase::Holding { .. }) + { + // DragonHoldingPatternPhase.onCrystalDestroyed: strafe the player. + d.set_phase(Phase::Strafe { + charge: 0, + path: None, + target: None, + clockwise: false, + }); + self.strafe_begin(); + } + } + } + /// Targets for projectiles: dragon parts and crystals. + pub(super) fn special_targets(&self) -> Vec<(u32, Aabb)> { + let mut out = Vec::new(); + if let Some(d) = self.dragon.as_ref().filter(|d| d.alive()) { + for i in 0..8 { + out.push((SPECIAL + i as u32, d.part_box(i))); + } + } + for (i, c) in self.crystals.iter().enumerate() { + let p = c.position; + out.push(( + CRYSTAL_IDS + i as u32, + Aabb::new( + Vec3::new(p.x - 1.0, p.y, p.z - 1.0), + Vec3::new(p.x + 1.0, p.y + 2.0, p.z + 1.0), + ), + )); + } + out + } + /// Damage to a special id (from projectiles and melee). + pub(super) fn hit_special(&mut self, id: u32, amount: f32, by_player: bool) { + if id >= CRYSTAL_IDS { + self.destroy_crystal((id - CRYSTAL_IDS) as usize, by_player); + } else if id >= SPECIAL { + self.hurt_dragon((id - SPECIAL) as usize, amount, by_player); + } + } + /// `EnderDragon.hurt(part, source, damage)`. + fn hurt_dragon(&mut self, part: usize, damage: f32, counts: bool) { + let Some(d) = self.dragon.as_mut() else { + return; + }; + if matches!(d.phase, Phase::Dying { .. }) || !d.alive() { + return; + } + let mut damage = damage; + if part != 0 && part != 1 { + damage = damage / 4.0 + damage.min(1.0); + } + if damage < 0.01 || !counts { + return; + } + // LivingEntity.hurt invulnerability: only damage above the last one in the window. + if d.invulnerable > 10 { + return; + } + let before = d.health; + d.health -= damage; + d.invulnerable = 20; + d.hurt_time = 10; + let at = [d.position.x, d.position.y, d.position.z]; + if d.health <= 0.0 { + if d.phase.sitting() { + d.health = 0.0; + } else { + // handleKillingBlow: dying flight first. + d.health = 1.0; + d.set_phase(Phase::Dying { + target: None, + time: 0, + }); + } + } + if d.phase.sitting() { + d.sitting_damage += before - d.health.max(0.0); + if d.sitting_damage > 0.25 * MAX_HEALTH { + d.sitting_damage = 0.0; + d.set_phase(Phase::Takeoff { + first: true, + path: None, + target: None, + }); + } + } + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.hurt", Some(at), 5.0, pitch); + } + /// Player melee on the dragon's parts or a crystal under the crosshair. + pub(super) fn attack_dragon(&mut self) -> bool { + let Some(eye) = self.eye_position() else { + return false; + }; + let dir = super::view_vector(self.yaw, self.pitch); + let reach: f64 = if self.creative { 5.0 } else { 3.0 }; + let mut best: Option<(u32, f64)> = None; + for (id, b) in self.special_targets() { + let (lo, hi) = (b.min_position(), b.max_position()); + let (lo, hi) = ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]); + let (mut t0, mut t1) = (0.0f64, reach); + let mut hit = true; + for a in 0..3 { + if dir[a].abs() < 1e-9 { + hit &= eye[a] >= lo[a] && eye[a] <= hi[a]; + continue; + } + let (mut ta, mut tb) = ((lo[a] - eye[a]) / dir[a], (hi[a] - eye[a]) / dir[a]); + if ta > tb { + std::mem::swap(&mut ta, &mut tb); + } + t0 = t0.max(ta); + t1 = t1.min(tb); + } + if hit && t0 <= t1 && best.is_none_or(|b| t0 < b.1) { + best = Some((id, t0)); + } + } + let Some((id, d)) = best else { return false }; + if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) { + return false; + } + let held = self.held().cloned(); + let modifiers = held + .as_ref() + .and_then(|h| self.res.items.get(&h.item)) + .map(|i| (i.attack_damage, i.attack_speed)) + .unwrap_or((0.0, 0.0)); + let speed = (4.0 + modifiers.1).max(0.1); + let scale = ((self.attack_ticks as f32 + 0.5) / (20.0 / speed)).clamp(0.0, 1.0); + let mut amount = + (1.0 + modifiers.0 + self.effect_attack_bonus()) * (0.2 + scale * scale * 0.8); + let falling = self + .player + .as_ref() + .is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting); + if scale > 0.9 && falling { + amount *= 1.5; + } + amount += self.enchant_damage_bonus("minecraft:ender_dragon") * scale; + self.attack_ticks = 0; + self.swing_arm(); + self.hit_special(id, amount, true); + true + } + /// The 24 nodes (`findClosestNode` builds them on first use). + fn dragon_nodes(&mut self) -> [[i32; 3]; 24] { + if let Some(n) = self.dragon.as_ref().and_then(|d| d.nodes) { + return n; + } + let mut nodes = [[0; 3]; 24]; + for (i, node) in nodes.iter_mut().enumerate() { + let (r, step, base, add) = if i < 12 { + (60.0f32, std::f32::consts::PI / 12.0, i, 5) + } else if i < 20 { + (40.0, std::f32::consts::PI / 8.0, i - 12, 15) + } else { + (20.0, std::f32::consts::PI / 4.0, i - 20, 5) + }; + let a = 2.0 * (-std::f32::consts::PI + step * base as f32); + let (x, z) = ((r * a.cos()).floor() as i32, (r * a.sin()).floor() as i32); + let y = (self.motion_blocking_no_leaves(x, z) + add).max(73); + *node = [x, y, z]; + } + if let Some(d) = self.dragon.as_mut() { + d.nodes = Some(nodes); + } + nodes + } + /// `getHeightmapPos(MOTION_BLOCKING_NO_LEAVES)`. + fn motion_blocking_no_leaves(&self, x: i32, z: i32) -> i32 { + (0..256) + .rev() + .find(|&y| { + let f = self.res.facts.get(self.world.block(x, y, z)); + (f.full_collision + || f.legacy_solid + || f.fluid != horizon_client::blocks::Fluid::None) + && !f.name.ends_with("_leaves") + }) + .map_or(0, |y| y + 1) + } + fn podium_top(&self) -> Vec3 { + Vec3::new(0.5, f64::from(self.motion_blocking_no_leaves(0, 0)), 0.5) + } + fn closest_node(&mut self, x: f64, y: f64, z: f64) -> usize { + let nodes = self.dragon_nodes(); + let start = if self.fight.alive_crystals == 0 { + 12 + } else { + 0 + }; + let p = [x.floor() as i32, y.floor() as i32, z.floor() as i32]; + let mut best = (10_000.0f32, 0); + for (i, n) in nodes.iter().enumerate().skip(start) { + let d = ((n[0] - p[0]).pow(2) + (n[1] - p[1]).pow(2) + (n[2] - p[2]).pow(2)) as f32; + if d < best.0 { + best = (d, i); + } + } + best.1 + } + /// `findPath` (A* over the adjacency masks), optionally ending at `last`. + fn dragon_path(&mut self, from: usize, to: usize, last: Option<[i32; 3]>) -> Option { + let nodes = self.dragon_nodes(); + let dist = |a: [i32; 3], b: [i32; 3]| { + (((a[0] - b[0]).pow(2) + (a[1] - b[1]).pow(2) + (a[2] - b[2]).pow(2)) as f32).sqrt() + }; + let min = if self.fight.alive_crystals == 0 { + 12 + } else { + 0 + }; + let mut g = [f32::MAX; 24]; + let mut came = [usize::MAX; 24]; + let mut closed = [false; 24]; + let mut open = vec![from]; + g[from] = 0.0; + let mut closest = from; + while !open.is_empty() { + let (k, &cur) = open + .iter() + .enumerate() + .min_by(|a, b| { + (g[*a.1] + dist(nodes[*a.1], nodes[to])) + .total_cmp(&(g[*b.1] + dist(nodes[*b.1], nodes[to]))) + }) + .expect("open set"); + open.swap_remove(k); + if cur == to { + closest = to; + break; + } + if dist(nodes[cur], nodes[to]) < dist(nodes[closest], nodes[to]) { + closest = cur; + } + closed[cur] = true; + for i in min..24 { + if ADJACENCY[cur] & (1 << i) != 0 && !closed[i] { + let tentative = g[cur] + dist(nodes[cur], nodes[i]); + if tentative < g[i] { + g[i] = tentative; + came[i] = cur; + if !open.contains(&i) { + open.push(i); + } + } + } + } + } + if closest == from && from != to { + return None; + } + let mut list = vec![nodes[closest]]; + let mut n = closest; + while came[n] != usize::MAX { + n = came[n]; + list.insert(0, nodes[n]); + } + if let Some(l) = last { + list.push(l); + } + Some(Path { + nodes: list, + next: 0, + }) + } + fn next_target(&mut self, path: &mut Option) -> Option { + let p = path.as_mut()?; + if p.0.done() { + return None; + } + let c = p.0.next_pos(); + p.0.advance(); + let d = self.dragon.as_mut()?; + let y = loop { + let y = f64::from(c[1]) + f64::from(d.random.next_float() * 20.0); + if y >= f64::from(c[1]) { + break y; + } + }; + Some(Vec3::new(f64::from(c[0]), y, f64::from(c[2]))) + } + /// The holding-pattern style path step: around the outer or inner ring. + fn ring_path(&mut self, clockwise: &mut bool) -> Option { + let d = self.dragon.as_mut()?; + let flip = d.random.next_int_bound(8).unwrap_or(1) == 0; + let current = { + let p = d.position; + self.closest_node(p.x, p.y, p.z) + }; + let mut target = current as i32; + if flip { + *clockwise = !*clockwise; + target += 6; + } + target += if *clockwise { 1 } else { -1 }; + if self.fight.alive_crystals > 0 { + target = target.rem_euclid(12); + } else { + target = ((target - 12) & 7) + 12; + } + let mut path = self.dragon_path(current, target as usize, None)?; + path.advance(); + Some(path) + } + fn strafe_begin(&mut self) { + let Some(p) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let Some(d) = self.dragon.as_ref() else { + return; + }; + let dp = d.position; + let current = self.closest_node(dp.x, dp.y, dp.z); + let target = self.closest_node(p.x, p.y, p.z); + let (fx, fz) = (p.x.floor() as i32, p.z.floor() as i32); + let sd = (f64::from(fx) - dp.x).hypot(f64::from(fz) - dp.z); + let ho = (0.4 + sd / 80.0 - 1.0).min(10.0); + let last = [fx, (p.y + ho).floor() as i32, fz]; + let mut path = self.dragon_path(current, target, Some(last)); + if let Some(path) = path.as_mut() { + path.advance(); + } + let mut boxed = path.map(PathBox); + let target = self.next_target(&mut boxed); + if let Some(Dragon { + phase: Phase::Strafe { + path, target: t, .. + }, + .. + }) = self.dragon.as_mut() + { + *path = boxed; + *t = target; + } + } + /// One phase server tick (`doServerTick`). + fn tick_phase(&mut self) { + let Some(d) = self.dragon.as_ref() else { + return; + }; + let pos = d.position; + let mut phase = d.phase.clone(); + let collided = false; + let far = |t: Option| { + t.map_or(0.0, |t| { + (t.x - pos.x).powi(2) + (t.y - pos.y).powi(2) + (t.z - pos.z).powi(2) + }) + }; + let player = self + .player + .as_ref() + .filter(|p| !p.health.dead_or_dying()) + .map(|p| p.position); + let survival_player = player.filter(|_| !self.creative); + let podium = self.podium_top(); + let mut next: Option = None; + match &mut phase { + Phase::Holding { + path, + target, + clockwise, + } => { + let dt = far(*target); + if dt < 100.0 || dt > 22500.0 || collided { + let done = path.as_ref().is_some_and(|p| p.0.done()); + let mut chosen = false; + if done { + let crystals = self.fight.alive_crystals; + let r = &mut self.dragon.as_mut().expect("dragon").random; + if r.next_int_bound(crystals + 3).unwrap_or(1) == 0 { + next = Some(Phase::LandingApproach { + path: None, + target: None, + }); + chosen = true; + } else if let Some(pp) = survival_player { + let dist = ((pp.x - podium.x).powi(2) + + (pp.y - podium.y).powi(2) + + (pp.z - podium.z).powi(2)) + / 512.0; + let r = &mut self.dragon.as_mut().expect("dragon").random; + if r.next_int_bound((dist + 2.0) as i32).unwrap_or(1) == 0 + || r.next_int_bound(crystals + 2).unwrap_or(1) == 0 + { + next = Some(Phase::Strafe { + charge: 0, + path: None, + target: None, + clockwise: false, + }); + chosen = true; + } + } + } + if !chosen { + if path.as_ref().is_none_or(|p| p.0.done()) { + *path = self.ring_path(clockwise).map(PathBox); + } + if let Some(t) = self.next_target(path) { + *target = Some(t); + } + } + } + } + Phase::Strafe { + charge, + path, + target, + clockwise, + } => { + let Some(pp) = survival_player else { + next = Some(Phase::Holding { + path: None, + target: None, + clockwise: false, + }); + self.dragon.as_mut().expect("dragon").phase = phase; + if let Some(n) = next { + self.dragon.as_mut().expect("dragon").set_phase(n); + } + return; + }; + if path.as_ref().is_some_and(|p| p.0.done()) { + let dist = (pp.x - pos.x).hypot(pp.z - pos.z); + let ho = (0.4 + dist / 80.0 - 1.0).min(10.0); + *target = Some(Vec3::new(pp.x, pp.y + ho, pp.z)); + } + let dt = far(*target); + if dt < 100.0 || dt > 22500.0 { + if path.as_ref().is_none_or(|p| p.0.done()) { + *path = self.ring_path(clockwise).map(PathBox); + } + if let Some(t) = self.next_target(path) { + *target = Some(t); + } + } + let d2 = (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2); + if d2 < 4096.0 { + *charge += 1; + let d = self.dragon.as_ref().expect("dragon"); + let r = d.yaw.to_radians(); + let dir = glam::DVec2::new(f64::from(r.sin()), f64::from(-r.cos())).normalize(); + let aim = glam::DVec2::new(pp.x - pos.x, pp.z - pos.z).normalize_or_zero(); + let angle = dir.dot(aim).clamp(-1.0, 1.0).acos().to_degrees() + 0.5; + if *charge >= 5 && (0.0..10.0).contains(&angle) { + // From the head, one block back along the view vector. + let head = d.parts[0].0; + let view = super::view_vector(d.yaw, 0.0); + let start = + Vec3::new(head.x - view[0], head.y + 0.5 + 0.5, head.z - view[2]); + let to = Vec3::new(pp.x - start.x, pp.y + 0.9 - start.y, pp.z - start.z); + self.spawn_dragon_fireball(start, to); + *charge = 0; + next = Some(Phase::Holding { + path: None, + target: None, + clockwise: false, + }); + } + } else if *charge > 0 { + *charge -= 1; + } + } + Phase::LandingApproach { path, target } => { + let dt = far(*target); + if dt < 100.0 || dt > 22500.0 || collided { + if path.as_ref().is_none_or(|p| p.0.done()) { + let current = self.closest_node(pos.x, pos.y, pos.z); + let target_node = match player { + Some(pp) => { + let aim = glam::DVec2::new(pp.x, pp.z).normalize_or_zero(); + self.closest_node(-aim.x * 40.0, 105.0, -aim.y * 40.0) + } + None => self.closest_node(40.0, podium.y, 0.0), + }; + let last = [ + podium.x.floor() as i32, + podium.y as i32, + podium.z.floor() as i32, + ]; + let mut p = self.dragon_path(current, target_node, Some(last)); + if let Some(p) = p.as_mut() { + p.advance(); + } + *path = p.map(PathBox); + } + if let Some(t) = self.next_target(path) { + *target = Some(t); + } + if path.as_ref().is_some_and(|p| p.0.done()) { + next = Some(Phase::Landing { target: None }); + } + } + } + Phase::Landing { target } => { + let t = *target.get_or_insert(podium); + if (t.x - pos.x).powi(2) + (t.y - pos.y).powi(2) + (t.z - pos.z).powi(2) < 1.0 { + self.dragon.as_mut().expect("dragon").flame_count = 0; + next = Some(Phase::Scanning { time: 0 }); + } + } + Phase::Takeoff { + first, + path, + target, + } => { + if !*first && path.is_some() { + if (podium.x - pos.x).powi(2) + + (podium.y - pos.y).powi(2) + + (podium.z - pos.z).powi(2) + >= 100.0 + { + next = Some(Phase::Holding { + path: None, + target: None, + clockwise: false, + }); + } + } else { + *first = false; + let current = self.closest_node(pos.x, pos.y, pos.z); + let look = self.dragon_look(); + let mut t = self.closest_node(-look[0] * 40.0, 105.0, -look[2] * 40.0) as i32; + if self.fight.alive_crystals > 0 { + t = t.rem_euclid(12); + } else { + t = ((t - 12) & 7) + 12; + } + let mut p = self.dragon_path(current, t as usize, None).map(PathBox); + if let Some(pb) = p.as_mut() { + pb.0.advance(); + } + if let Some(t) = self.next_target(&mut p) { + *target = Some(t); + } + *path = p.or(Some(PathBox(Path::default()))); + } + } + Phase::Scanning { time } => { + *time += 1; + let near = player.filter(|pp| { + (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2) + <= 400.0 + && (pp.y - pos.y).abs() <= 10.0 + }); + if let Some(pp) = near.filter(|_| !self.creative) { + if *time > 25 { + next = Some(Phase::Attacking { ticks: 0 }); + } else { + let d = self.dragon.as_mut().expect("dragon"); + let head = d.parts[0].0; + let (xd, zd) = (pp.x - head.x, pp.z - head.z); + let delta = wrap64(180.0 - xd.atan2(zd).to_degrees() - f64::from(d.yaw)) + .clamp(-100.0, 100.0); + d.yaw_accel *= 0.8; + let dist = (xd.hypot(zd) as f32 + 1.0).min(40.0); + let rot = xd.hypot(zd) as f32 + 1.0; + d.yaw_accel += delta as f32 * (0.7 / dist / rot); + d.yaw += d.yaw_accel; + } + } else if *time >= 100 { + next = Some(match survival_player { + Some(pp) + if (pp.x - pos.x).powi(2) + + (pp.y - pos.y).powi(2) + + (pp.z - pos.z).powi(2) + <= 150.0 * 150.0 => + { + Phase::Charging { + target: Some(pp), + since: 0, + } + } + _ => Phase::Takeoff { + first: true, + path: None, + target: None, + }, + }); + } + } + Phase::Attacking { ticks } => { + if *ticks == 0 { + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio.play( + "minecraft:entity.ender_dragon.growl", + Some([pos.x, pos.y, pos.z]), + 2.5, + pitch, + ); + } + *ticks += 1; + if *ticks > 40 { + next = Some(Phase::Flaming { ticks: 0 }); + } + } + Phase::Flaming { ticks } => { + *ticks += 1; + if *ticks >= 200 { + let count = self.dragon.as_ref().map_or(0, |d| d.flame_count); + next = Some(if count >= 4 { + Phase::Takeoff { + first: true, + path: None, + target: None, + } + } else { + Phase::Scanning { time: 0 } + }); + } else if *ticks == 10 { + let d = self.dragon.as_ref().expect("dragon"); + let head = d.parts[0].0; + let look = glam::DVec2::new(head.x - pos.x, head.z - pos.z).normalize_or_zero(); + let (x, z) = (head.x + look.x * 2.5, head.z + look.y * 2.5); + let mut y = head.y + 0.5; + while y > 0.0 + && self.res.facts.is_air(self.world.block( + x.floor() as i32, + y.floor() as i32, + z.floor() as i32, + )) + { + y -= 1.0; + } + self.breath_clouds.push(Breath { + at: [x, y.floor() + 1.0, z], + radius: 5.0, + age: 0, + duration: 200, + from_dragon: true, + }); + } + } + Phase::Charging { target, since } => { + if target.is_none() { + next = Some(Phase::Holding { + path: None, + target: None, + clockwise: false, + }); + } else if *since > 0 { + *since += 1; + if *since >= 10 { + next = Some(Phase::Holding { + path: None, + target: None, + clockwise: false, + }); + } + } else { + let dt = far(*target); + if dt < 100.0 || dt > 22500.0 { + *since += 1; + } + } + } + Phase::Dying { target, time } => { + *time += 1; + let t = *target.get_or_insert(Vec3::new( + 0.5, + f64::from(self.motion_blocking_no_leaves(0, 0)), + 0.5, + )); + let dt = (t.x - pos.x).powi(2) + (t.y - pos.y).powi(2) + (t.z - pos.z).powi(2); + let d = self.dragon.as_mut().expect("dragon"); + d.health = if !(100.0..=22500.0).contains(&dt) { + 0.0 + } else { + 1.0 + }; + } + Phase::Hover { target } => { + target.get_or_insert(pos); + } + } + let d = self.dragon.as_mut().expect("dragon"); + d.phase = phase; + if let Some(n) = next { + let strafe = matches!(n, Phase::Strafe { .. }); + d.set_phase(n); + if strafe { + self.strafe_begin(); + } + } + } + /// `getHeadLookVector`. + fn dragon_look(&self) -> [f64; 3] { + let Some(d) = self.dragon.as_ref() else { + return [0.0; 3]; + }; + let pitch = match d.phase { + Phase::Landing { .. } | Phase::Takeoff { .. } => { + let p = self.podium_top(); + let dist = ((p.x - d.position.x).powi(2) + + (p.y - d.position.y).powi(2) + + (p.z - d.position.z).powi(2)) + .sqrt() as f32 + / 4.0; + -6.0 / dist.max(1.0) * 1.5 * 5.0 + } + _ if d.phase.sitting() => -45.0, + _ => 0.0, + }; + super::view_vector(d.yaw, pitch).map(|v| v) + } + /// `EnderDragon.aiStep` (and `tickDeath`) for the dragon. + fn tick_dragon(&mut self) { + let Some(d) = self.dragon.as_mut() else { + return; + }; + d.previous = d.position; + d.previous_yaw = d.yaw; + d.old_flap = d.flap; + d.ticks += 1; + d.hurt_time = (d.hurt_time - 1).max(0); + d.invulnerable = (d.invulnerable - 1).max(0); + for part in &mut d.parts { + part.1 = part.0; + } + if !d.alive() { + self.tick_dragon_death(); + return; + } + // Flapping, growls and the flap sound. + let flap_was = (d.old_flap * std::f32::consts::TAU).cos(); + let v = d.velocity; + let mut flap_speed = 0.2 / ((v.x.hypot(v.z) as f32) * 10.0 + 1.0); + flap_speed *= 2f32.powf(v.y as f32); + d.flap += if d.phase.sitting() { + 0.1 + } else if d.in_wall { + flap_speed * 0.5 + } else { + flap_speed + }; + let flap_now = (d.flap * std::f32::consts::TAU).cos(); + let at = [d.position.x, d.position.y, d.position.z]; + if flap_was <= -0.3 && flap_now >= -0.3 { + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.flap", Some(at), 5.0, pitch); + } + let d = self.dragon.as_mut().expect("dragon"); + if !d.phase.sitting() { + d.growl -= 1; + if d.growl < 0 { + d.growl = 200 + d.random.next_int_bound(200).unwrap_or(0); + let pitch = 0.8 + self.world.random.next_float() * 0.3; + self.audio + .play("minecraft:entity.ender_dragon.growl", Some(at), 2.5, pitch); + } + } + // checkCrystals: heal 1 every 10 ticks from the nearest crystal within 32. + let d = self.dragon.as_mut().expect("dragon"); + if d.nearest_crystal.is_some() && d.ticks % 10 == 0 && d.health < MAX_HEALTH { + d.health += 1.0; + } + if d.random.next_int_bound(10).unwrap_or(1) == 0 { + let p = d.position; + d.nearest_crystal = self + .crystals + .iter() + .enumerate() + .filter(|(_, c)| { + (c.position.x - p.x).abs() <= 32.0 + && (c.position.y - p.y).abs() <= 32.0 + && (c.position.z - p.z).abs() <= 32.0 + }) + .min_by(|a, b| { + let da = (a.1.position.x - p.x).powi(2) + + (a.1.position.y - p.y).powi(2) + + (a.1.position.z - p.z).powi(2); + let db = (b.1.position.x - p.x).powi(2) + + (b.1.position.y - p.y).powi(2) + + (b.1.position.z - p.z).powi(2); + da.total_cmp(&db) + }) + .map(|(i, _)| i); + } + let d = self.dragon.as_mut().expect("dragon"); + d.yaw = wrap(d.yaw); + d.record(); + self.tick_phase(); + // Steering towards the phase's fly target. + let Some(d) = self.dragon.as_mut() else { + return; + }; + if let Some(t) = d.phase.target() { + let (xd, mut yd, zd) = (t.x - d.position.x, t.y - d.position.y, t.z - d.position.z); + let dist2 = xd * xd + yd * yd + zd * zd; + let max = f64::from(d.phase.fly_speed()); + let horizontal = xd.hypot(zd); + if horizontal > 0.0 { + yd = (yd / horizontal).clamp(-max, max); + } + d.velocity.y += yd * 0.01; + d.yaw = wrap(d.yaw); + let aim = glam::DVec3::new(xd, t.y - d.position.y, zd).normalize_or_zero(); + let r = d.yaw.to_radians(); + let dir = glam::DVec3::new(f64::from(r.sin()), d.velocity.y, f64::from(-r.cos())) + .normalize_or_zero(); + let dot = ((dir.dot(aim) as f32 + 0.5) / 1.5).max(0.0); + if xd.abs() > 1.0e-5 || zd.abs() > 1.0e-5 { + let turn = match d.phase { + Phase::Landing { .. } => { + let rot = d.velocity.x.hypot(d.velocity.z) as f32 + 1.0; + rot.min(40.0) / rot + } + _ => { + let rot = d.velocity.x.hypot(d.velocity.z) as f32 + 1.0; + 0.7 / rot.min(40.0) / rot + } + }; + let delta = + wrap(180.0 - xd.atan2(zd).to_degrees() as f32 - d.yaw).clamp(-50.0, 50.0); + d.yaw_accel *= 0.8; + d.yaw_accel += delta * turn; + d.yaw += d.yaw_accel * 0.1; + } + let span = (2.0 / (dist2 + 1.0)) as f32; + let speed = 0.06 * (dot * span + (1.0 - span)); + // moveRelative(speed, (0, 0, -1)). + let r = d.yaw.to_radians(); + d.velocity.x += f64::from(speed * r.sin()); + d.velocity.z += f64::from(-speed * r.cos()); + let step = if d.in_wall { 0.8 } else { 1.0 }; + d.position = Vec3::new( + d.position.x + d.velocity.x * step, + d.position.y + d.velocity.y * step, + d.position.z + d.velocity.z * step, + ); + let actual = + glam::DVec3::new(d.velocity.x, d.velocity.y, d.velocity.z).normalize_or_zero(); + let slide = 0.8 + 0.15 * (actual.dot(dir) + 1.0) / 2.0; + d.velocity = Vec3::new( + d.velocity.x * slide, + d.velocity.y * 0.91, + d.velocity.z * slide, + ); + } + self.place_dragon_parts(); + self.dragon_contacts(); + // The chunks the dragon passes through re-save their entity lists. + if let Some(d) = &self.dragon { + for p in [d.previous, d.position] { + self.world + .modified + .insert((p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4)); + } + } + } + /// The part positions from the yaw and the flight history. + fn place_dragon_parts(&mut self) { + let Some(d) = self.dragon.as_mut() else { + return; + }; + let tilt = + ((d.sample(5).0 - d.sample(10).0) * 10.0) as f32 * (std::f32::consts::PI / 180.0); + let (ct, st) = (tilt.cos(), tilt.sin()); + let r1 = d.yaw.to_radians(); + let (s1, c1) = (r1.sin(), r1.cos()); + let p = d.position; + let set = |d: &mut Dragon, i: usize, x: f32, y: f64, z: f32| { + d.parts[i].0 = Vec3::new(p.x + f64::from(x), p.y + y, p.z + f64::from(z)); + }; + set(d, 2, s1 * 0.5, 0.0, -c1 * 0.5); + set(d, 6, c1 * 4.5, 2.0, s1 * 4.5); + set(d, 7, c1 * -4.5, 2.0, s1 * -4.5); + let r2 = d.yaw.to_radians() - d.yaw_accel * 0.01; + let (s2, c2) = (r2.sin(), r2.cos()); + let y_off = if d.phase.sitting() { + -1.0 + } else { + d.sample(5).0 - d.sample(0).0 + } as f32; + set( + d, + 0, + s2 * 6.5 * ct, + f64::from(y_off + st * 6.5), + -c2 * 6.5 * ct, + ); + set( + d, + 1, + s2 * 5.5 * ct, + f64::from(y_off + st * 5.5), + -c2 * 5.5 * ct, + ); + let p1 = d.sample(5); + for i in 0..3 { + let p0 = d.sample(12 + i * 2); + let rot = d.yaw.to_radians() + wrap(p0.1 - p1.1).to_radians(); + let (ss, cc) = (rot.sin(), rot.cos()); + let dd = (i as f32 + 1.0) * 2.0; + let x = -(s1 * 1.5 + ss * dd) * ct; + let y = p0.0 - p1.0 - f64::from((dd + 1.5) * st) + 1.5; + let z = (c1 * 1.5 + cc * dd) * ct; + set(d, 3 + i, x, y, z); + } + } + /// Wing knockback, head and neck damage, and breaking blocks in the way. + fn dragon_contacts(&mut self) { + let Some(d) = self.dragon.as_ref() else { + return; + }; + let sitting = d.phase.sitting(); + let recently_hurt = d.hurt_time > 0; + let body = d.part_box(2); + let (bc, bz) = ( + (body.min_position().x + body.max_position().x) / 2.0, + (body.min_position().z + body.max_position().z) / 2.0, + ); + let wings = [d.part_box(6), d.part_box(7)]; + let heads = [d.part_box(0), d.part_box(1)]; + let player_box = self.player.as_ref().map(|p| p.bounds()); + let creative = self.creative; + if !recently_hurt && let Some(pb) = player_box.filter(|_| !creative) { + for w in wings { + let zone = w + .inflate(Vec3::new(4.0, 2.0, 4.0)) + .move_by(Vec3::new(0.0, -2.0, 0.0)); + if zone.intersects(pb) { + let pp = self + .player + .as_ref() + .map(|p| p.position) + .unwrap_or(Vec3::ZERO); + let (xd, zd) = (pp.x - bc, pp.z - bz); + let dd = (xd * xd + zd * zd).max(0.1); + if let Some(p) = self.player.as_mut() { + p.velocity.x += xd / dd * 4.0; + p.velocity.y += 0.2; + p.velocity.z += zd / dd * 4.0; + } + if !sitting { + self.hurt_player_by("minecraft:mob_attack", 5.0); + } + } + } + for h in heads { + if h.inflate(Vec3::new(1.0, 1.0, 1.0)).intersects(pb) { + self.hurt_player_by("minecraft:mob_attack", 10.0); + } + } + } + // checkWalls over head, neck and body. + let griefing = self.ui.rules.bool("mob_griefing"); + let mut in_wall = false; + let Some(d) = self.dragon.as_ref() else { + return; + }; + let boxes = [d.part_box(0), d.part_box(1), d.part_box(2)]; + let tags = &self.res.items.block_tags; + let transparent = tags + .get("minecraft:dragon_transparent") + .cloned() + .unwrap_or_default(); + let immune = tags + .get("minecraft:dragon_immune") + .cloned() + .unwrap_or_default(); + let mut removed = Vec::new(); + for b in boxes { + let (lo, hi) = (b.min_position(), b.max_position()); + for x in lo.x.floor() as i32..=hi.x.floor() as i32 { + for y in lo.y.floor() as i32..=hi.y.floor() as i32 { + for z in lo.z.floor() as i32..=hi.z.floor() as i32 { + let state = self.world.block(x, y, z); + let name = &self.res.facts.get(state).name; + if self.res.facts.is_air(state) || transparent.contains(&**name) { + continue; + } + if griefing && !immune.contains(&**name) { + removed.push([x, y, z]); + } else { + in_wall = true; + } + } + } + } + } + let air = self.world.air; + let broke = !removed.is_empty(); + for p in removed { + let _ = self.level_set(p, air); + } + if broke && let Some(d) = self.dragon.as_ref() { + let p = d.parts[0].0; + // Level event 2008: an explosion puff where a block broke. + self.particles.add( + &ParticleOptions::simple(ParticleType::Explosion), + [p.x, p.y, p.z], + [0.0; 3], + ); + } + if let Some(d) = self.dragon.as_mut() { + d.in_wall = in_wall; + } + } + /// `tickDeath`: rising for 200 ticks, explosions, experience, then the + /// exit portal, the egg and a gateway. + fn tick_dragon_death(&mut self) { + let Some(d) = self.dragon.as_mut() else { + return; + }; + d.death_time += 1; + let t = d.death_time; + let p = d.position; + let r = &mut d.random; + let mut off = || { + [ + f64::from((r.next_float() - 0.5) * 8.0), + f64::from((r.next_float() - 0.5) * 4.0), + f64::from((r.next_float() - 0.5) * 8.0), + ] + }; + if (180..=200).contains(&t) { + let o = off(); + self.particles.add( + &ParticleOptions::simple(ParticleType::ExplosionEmitter), + [p.x + o[0], p.y + 2.0 + o[1], p.z + o[2]], + [0.0; 3], + ); + } + let first_kill = !self.fight.previously_killed; + let xp = if first_kill { 12000 } else { 500 }; + let drops = self.ui.rules.bool("mob_drops"); + if t > 150 && t % 5 == 0 && drops { + self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.08) as u32); + } + if t == 1 { + // Level event 1028: the death roar, heard everywhere. + self.audio + .play("minecraft:entity.ender_dragon.death", None, 5.0, 1.0); + } + if let Some(d) = self.dragon.as_mut() { + d.position.y += 0.1; + for part in &mut d.parts { + part.0.y += 0.1; + } + } + if t >= 200 { + if drops { + self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.2) as u32); + } + self.dragon = None; + self.dragon_killed(); + } + } + /// `EnderDragonFight.setDragonKilled`. + fn dragon_killed(&mut self) { + let _ = self.activate_exit_portal(); + if let Some(g) = self.fight.gateways.pop() { + let a = 2.0 * (-std::f64::consts::PI + std::f64::consts::PI / 20.0 * f64::from(g)); + let pos = [ + (96.0 * a.cos()).floor() as i32, + 75, + (96.0 * a.sin()).floor() as i32, + ]; + let _ = self.place_gateway_at(pos); + } + if !self.fight.previously_killed + && let Some(egg) = self + .res + .assets + .registry + .default_state("minecraft:dragon_egg") + { + let y = (0..256) + .rev() + .find(|&y| { + let f = self.res.facts.get(self.world.block(0, y, 0)); + f.full_collision || f.legacy_solid + }) + .map_or(64, |y| y + 1); + let _ = self.level_set([0, y, 0], egg); + } + self.fight.previously_killed = true; + self.fight.killed = true; + self.fight.dirty = true; + self.save_fight(); + } + fn spawn_dragon_fireball(&mut self, at: Vec3, dir: Vec3) { + let l = (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z) + .sqrt() + .max(1.0e-6); + let v = Vec3::new(dir.x / l, dir.y / l, dir.z / l); + self.audio.play( + "minecraft:entity.ender_dragon.shoot", + Some([at.x, at.y, at.z]), + 10.0, + 1.0, + ); + // assignDirectionalMovement: the direction times the acceleration power 0.1. + let velocity = Vec3::new(v.x * 0.1, v.y * 0.1, v.z * 0.1); + self.dragon_fireballs.push(DragonFireball { + position: at, + previous: at, + velocity, + age: 0, + }); + } + /// `DragonFireball` (an AbstractHurtingProjectile): accelerating by its + /// power, bursting into dragon's breath on impact. + pub(super) fn tick_dragon_fireballs(&mut self) { + let mut balls = std::mem::take(&mut self.dragon_fireballs); + let player = self.player.as_ref().map(|p| p.bounds()); + balls.retain_mut(|b| { + b.previous = b.position; + b.age += 1; + let v = b.velocity; + let next = Vec3::new(b.position.x + v.x, b.position.y + v.y, b.position.z + v.z); + // AbstractHurtingProjectile: accelerate along the motion, inertia 0.95. + let l = (v.x * v.x + v.y * v.y + v.z * v.z).sqrt().max(1.0e-9); + b.velocity = Vec3::new( + (v.x + v.x / l * 0.1) * 0.95, + (v.y + v.y / l * 0.1) * 0.95, + (v.z + v.z / l * 0.1) * 0.95, + ); + let hit_block = { + let p = [ + next.x.floor() as i32, + next.y.floor() as i32, + next.z.floor() as i32, + ]; + let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + f.full_collision || f.legacy_solid + }; + let hit_player = player.is_some_and(|pb| { + pb.intersects(Aabb::new( + Vec3::new(next.x - 0.5, next.y - 0.5, next.z - 0.5), + Vec3::new(next.x + 0.5, next.y + 0.5, next.z + 0.5), + )) + }); + if hit_block || hit_player || b.age > 600 { + self.breath_clouds.push(Breath { + at: [next.x, next.y, next.z], + radius: 3.0, + age: 0, + duration: 600, + from_dragon: false, + }); + self.audio.play( + "minecraft:entity.dragon_fireball.explode", + Some([next.x, next.y, next.z]), + 1.0, + 1.0, + ); + return false; + } + b.position = next; + self.particles.add( + &ParticleOptions::simple(ParticleType::DragonBreath), + [next.x, next.y + 0.5, next.z], + [0.0; 3], + ); + true + }); + self.dragon_fireballs.append(&mut balls); + self.tick_breath(); + } + /// The dragon's breath clouds (`AreaEffectCloud` with instant damage at + /// a quarter duration scale): shrinking, puffing particles, harming the player. + fn tick_breath(&mut self) { + let player = self.player.as_ref().map(|p| p.position); + let mut clouds = std::mem::take(&mut self.breath_clouds); + clouds.retain_mut(|c| { + c.age += 1; + if c.age >= c.duration { + return false; + } + if !c.from_dragon { + // DragonFireball's cloud: radius per tick (7 - 3) / duration. + c.radius += (7.0 - 3.0) / c.duration as f32; + } + let r = c.radius; + for _ in 0..((std::f32::consts::PI * r * r) as i32).min(40) { + let a = self.world.random.next_float() * std::f32::consts::TAU; + let d = self.world.random.next_float().sqrt() * r; + let at = [ + c.at[0] + f64::from(a.cos() * d), + c.at[1], + c.at[2] + f64::from(a.sin() * d), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::DragonBreath), + at, + [0.0, 0.0, 0.0], + ); + } + // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. + if c.age >= 20 + && c.age % 20 == 0 + && let Some(pp) = player + && (pp.x - c.at[0]).hypot(pp.z - c.at[2]) <= f64::from(r) + && (pp.y - c.at[1]).abs() < 1.0 + && !self.creative + { + // Instant damage: I (6) from the breath, II (12) from a fireball. + let amount = if c.from_dragon { 6.0 } else { 12.0 }; + self.hurt_player_by("minecraft:indirect_magic", amount); + } + true + }); + self.breath_clouds.append(&mut clouds); + } + /// The boss bar (`BossHealthOverlay`): name and the pink progress bar. + pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) { + let Some(d) = self.dragon.as_ref() else { + return; + }; + if self.dim != Dim::End { + return; + } + let atlas = &self.res.atlas; + let x = (batch.width / 2.0 - 91.0).floor(); + let y = 12.0; + batch.sprite(atlas, "gui/sprites/boss_bar/pink_background", x, y); + let progress = (d.health / MAX_HEALTH).clamp(0.0, 1.0); + batch.sprite_part(atlas, "gui/sprites/boss_bar/pink_progress", x, y, progress); + let name = self.translate("entity.minecraft.ender_dragon", "Ender Dragon"); + let w = HudBatch::text_width(atlas, &name); + batch.text( + atlas, + &name, + (batch.width / 2.0 - w / 2.0).floor(), + y - 9.0, + rgba(255, 255, 255, 255), + true, + ); + } + /// `music.dragon` while the boss bar plays music. + pub(super) fn boss_music(&self) -> bool { + self.dim == Dim::End && self.dragon.is_some() + } +} +pub(super) struct DragonFireball { + position: Vec3, + previous: Vec3, + velocity: Vec3, + age: i32, +} +pub(super) struct Breath { + at: [f64; 3], + radius: f32, + age: i32, + duration: i32, + from_dragon: bool, +} +impl Game<'_> { + /// `EnderDragonRenderer` and `EnderDragonModel.setupAnim`. + pub(super) fn dragon_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + additive: &mut Vec, + ) { + let (Some(d), Some(model)) = (self.dragon.as_ref(), self.dragon_model.as_ref()) else { + return; + }; + let a = alpha as f32; + let sprite = |n: &str| { + self.res + .atlas + .sprites + .get(n) + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + }; + let (Some(skin), Some(eyes)) = ( + sprite("entity/enderdragon/dragon"), + sprite("entity/enderdragon/dragon_eyes"), + ) else { + return; + }; + let pos = glam::DVec3::new( + d.previous.x + (d.position.x - d.previous.x) * alpha, + d.previous.y + (d.position.y - d.previous.y) * alpha, + d.previous.z + (d.position.z - d.previous.z) * alpha, + ); + let h = |delay: usize| d.sample_lerp(delay, a); + let yr = h(7).1; + let rot2 = (h(5).0 - h(10).0) as f32; + let mut base = glam::Mat4::from_translation((pos - camera).as_vec3()) + * glam::Mat4::from_rotation_y((-yr).to_radians()) + * glam::Mat4::from_rotation_x((rot2 * 10.0).to_radians()) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.0, 1.0)) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)); + let rays_base = base * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.0, -2.0)); + // setupAnim. + let flap = (d.old_flap + (d.flap - d.old_flap) * a) * std::f32::consts::TAU; + let mut bounce = (flap - 1.0).sin() + 1.0; + bounce = (bounce * bounce + bounce * 2.0) * 0.05; + base *= + glam::Mat4::from_translation(glam::Vec3::new(0.0, (bounce - 2.0) * 16.0, -48.0) / 16.0) + * glam::Mat4::from_rotation_x((bounce * 2.0).to_radians()); + let mut poses = horizon_client::mobs::anim::Poses::new(model); + poses.get("jaw")[3] = (flap.sin() + 1.0) * 0.2; + let sitting = d.phase.sitting(); + let landing = matches!(d.phase, Phase::Landing { .. } | Phase::Takeoff { .. }); + let egg_dist = { + let p = self.podium_top(); + ((p.x - d.position.x).powi(2) + + (p.y - d.position.y).powi(2) + + (p.z - d.position.z).powi(2)) + .sqrt() + }; + let head_offset = |part: usize, start: (f64, f32), point: (f64, f32)| -> f32 { + if landing { + part as f32 / (egg_dist / 4.0).max(1.0) as f32 + } else if sitting { + part as f32 + } else if part == 6 { + 0.0 + } else { + (point.0 - start.0) as f32 + } + }; + let start = h(6); + let rot2y = wrap(h(5).1 - h(10).1); + let rot = wrap(h(5).1 + rot2y / 2.0); + let deg = std::f32::consts::PI / 180.0; + let (mut xx, mut yy, mut zz) = (0.0f32, 20.0f32, -12.0f32); + for i in 0..5 { + let point = h(5 - i); + let pose = poses.get(&format!("neck{i}")); + let neck_x = (i as f32 * 0.45 + flap).cos() * 0.15; + pose[4] = wrap(point.1 - start.1) * deg * 1.5; + pose[3] = neck_x + head_offset(i, start, point) * deg * 1.5 * 5.0; + pose[5] = -wrap(point.1 - rot) * deg * 1.5; + pose[0] = xx; + pose[1] = yy; + pose[2] = zz; + let (xr, yrr) = (pose[3], pose[4]); + xx -= yrr.sin() * xr.cos() * 10.0; + yy += xr.sin() * 10.0; + zz -= yrr.cos() * xr.cos() * 10.0; + } + let current = h(0); + let head = poses.get("head"); + head[0] = xx; + head[1] = yy; + head[2] = zz; + head[4] = wrap(current.1 - start.1) * deg; + head[3] = wrap(head_offset(6, start, current)) * deg * 1.5 * 5.0; + head[5] = -wrap(current.1 - rot) * deg; + poses.get("body")[5] = -rot2y * 1.5 * deg; + let lw = [0.125 - flap.cos() * 0.2, -0.25, -(flap.sin() + 0.125) * 0.8]; + let lt = ((flap + 2.0).sin() + 0.5) * 0.75; + { + let p = poses.get("left_wing"); + (p[3], p[4], p[5]) = (lw[0], lw[1], lw[2]); + } + poses.get("left_wing_tip")[5] = lt; + { + let p = poses.get("right_wing"); + (p[3], p[4], p[5]) = (lw[0], -lw[1], -lw[2]); + } + poses.get("right_wing_tip")[5] = -lt; + for side in ["left", "right"] { + poses.get(&format!("{side}_hind_leg"))[3] = 1.0 + bounce * 0.1; + poses.get(&format!("{side}_hind_leg_tip"))[3] = 0.5 + bounce * 0.1; + poses.get(&format!("{side}_hind_foot"))[3] = 0.75 + bounce * 0.1; + poses.get(&format!("{side}_front_leg"))[3] = 1.3 + bounce * 0.1; + poses.get(&format!("{side}_front_leg_tip"))[3] = -0.5 - bounce * 0.1; + poses.get(&format!("{side}_front_foot"))[3] = 0.75 + bounce * 0.1; + } + let mut tail_x = 0.0f32; + let (mut xx, mut yy, mut zz) = (0.0f32, 10.0f32, 60.0f32); + let start = h(11); + for i in 0..12 { + let point = h(12 + i); + tail_x += (i as f32 * 0.45 + flap).sin() * 0.05; + let p = poses.get(&format!("tail{i}")); + p[4] = (wrap(point.1 - start.1) * 1.5 + 180.0) * deg; + p[3] = tail_x + (point.0 - start.0) as f32 * deg * 1.5 * 5.0; + p[5] = wrap(point.1 - rot) * deg * 1.5; + p[0] = xx; + p[1] = yy; + p[2] = zz; + let (xr, yrr) = (p[3], p[4]); + yy += xr.sin() * 10.0; + zz -= yrr.cos() * xr.cos() * 10.0; + xx -= yrr.sin() * xr.cos() * 10.0; + } + let l = self.world.light( + d.position.x.floor() as i32, + d.position.y.floor() as i32, + d.position.z.floor() as i32, + ); + let light = (u32::from(l >> 4) * 16) | ((u32::from(l & 15) * 16) << 8); + let death = if d.death_time > 0 { + d.death_time as f32 + a + } else { + 0.0 + }; + // The dissolve is approximated by fading out. + let color = if death > 0.0 { + let alpha = ((1.0 - death / 200.0) * 255.0).clamp(0.0, 255.0) as u32; + alpha << 24 | 0x00FF_FFFF + } else { + 0xFFFF_FFFF + }; + let overlay = u32::from(d.hurt_time > 0); + horizon_client::mobs::render::draw(model, base, &poses, skin, color, light, overlay, out); + // RenderTypes.eyes: the glowing eyes, added on top. + let mut eye_quads = Vec::new(); + horizon_client::mobs::render::draw( + model, + base, + &poses, + eyes, + 0xFFFF_FFFF, + 240 | 240 << 8, + 0, + &mut eye_quads, + ); + for v in &mut eye_quads { + v.layer = 2; + } + additive.extend(eye_quads); + if death > 0.0 { + self.dragon_rays(rays_base, death / 200.0, additive); + } + // The healing beam to the nearest crystal. + if let Some(c) = d.nearest_crystal.and_then(|i| self.crystals.get(i)) { + let age = c.time as f32 + a; + let hh = (age * 0.2).sin() / 2.0 + 0.5; + let bob = f64::from((hh * hh + hh) * 0.4 - 1.4); + let to = glam::DVec3::new(c.position.x, c.position.y + bob, c.position.z); + self.crystal_beam(pos, to - pos, self.ticks as f32 + a, camera, out); + } + } + /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. + fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { + let white = self.res.atlas.font.white(); + let uv = [white.u0, white.v0]; + let over = if t > 0.8 { + ((t - 0.8) / 0.2).min(1.0) + } else { + 0.0 + }; + let inner = (((1.0 - over) * 255.0) as u32) << 24 | 0x00FF_FFFF; + let outer = 0x00FF_00FF; + let mut random = LegacyRandom::new(432); + let mut m = base; + let count = ((t + t * t) / 2.0 * 60.0).floor() as i32; + let half_sqrt3 = 3f32.sqrt() / 2.0; + let tau = std::f32::consts::TAU; + for _ in 0..count { + let mut f = || random.next_float() * tau; + let q1 = glam::Quat::from_rotation_x(f()) + * glam::Quat::from_rotation_y(f()) + * glam::Quat::from_rotation_z(f()); + let (a, b, c) = (f(), f(), f()); + let q2 = glam::Quat::from_rotation_x(a) + * glam::Quat::from_rotation_y(b) + * glam::Quat::from_rotation_z(c + t * std::f32::consts::FRAC_PI_2); + m *= glam::Mat4::from_quat(q1 * q2); + let length = random.next_float() * 20.0 + 5.0 + over * 10.0; + let width = random.next_float() * 2.0 + 1.0 + over * 2.0; + let o = glam::Vec3::ZERO; + let left = glam::Vec3::new(-half_sqrt3 * width, length, -0.5 * width); + let right = glam::Vec3::new(half_sqrt3 * width, length, -0.5 * width); + let bottom = glam::Vec3::new(0.0, length, width); + for (p1, p2) in [(left, right), (right, bottom), (bottom, left)] { + // A triangle as a quad with its last corner repeated. + for (p, c) in [(o, inner), (p1, outer), (p2, outer), (p2, outer)] { + out.push(Vertex { + pos: m.transform_point3(p).to_array(), + uv, + layer: 2, + color: c, + light: 0, + }); + } + } + } + } + /// `submitCrystalBeams`: an eight-sided tube from `from` (+2 up) along + /// `delta`, the beam texture scrolling along it. + fn crystal_beam( + &self, + from: glam::DVec3, + delta: glam::DVec3, + time: f32, + camera: glam::DVec3, + out: &mut Vec, + ) { + let Some(s) = self + .res + .atlas + .sprites + .get("entity/end_crystal/end_crystal_beam") + .copied() + else { + return; + }; + let q = |v: f32| (v * 65535.0).round().clamp(0.0, 65535.0) as u32; + let wrap_light = q(s.v0) | q(s.v1 - s.v0) << 16; + let (dx, dy, dz) = (delta.x as f32, delta.y as f32, delta.z as f32); + let horizontal = (dx * dx + dz * dz).sqrt(); + let length = (dx * dx + dy * dy + dz * dz).sqrt(); + let m = glam::Mat4::from_translation( + (from - camera).as_vec3() + glam::Vec3::new(0.0, 2.0, 0.0), + ) * glam::Mat4::from_rotation_y(-dz.atan2(dx) - std::f32::consts::FRAC_PI_2) + * glam::Mat4::from_rotation_x(-horizontal.atan2(dy) - std::f32::consts::FRAC_PI_2); + let (v0, v1) = (-time * 0.01, length / 32.0 - time * 0.01); + let (mut last_sin, mut last_cos, mut last_u) = (0.0f32, 0.75f32, 0.0f32); + let u = |x: f32| s.u0 + (s.u1 - s.u0) * x; + for i in 1..=8 { + let a = i as f32 * std::f32::consts::TAU / 8.0; + let (sin, cos) = (a.sin() * 0.75, a.cos() * 0.75); + let uu = i as f32 / 8.0; + for (p, uv, c) in [ + ( + glam::Vec3::new(last_sin * 0.2, last_cos * 0.2, 0.0), + [u(last_u), v0], + 0xFF00_0000, + ), + ( + glam::Vec3::new(last_sin, last_cos, length), + [u(last_u), v1], + 0xFFFF_FFFF, + ), + (glam::Vec3::new(sin, cos, length), [u(uu), v1], 0xFFFF_FFFF), + ( + glam::Vec3::new(sin * 0.2, cos * 0.2, 0.0), + [u(uu), v0], + 0xFF00_0000, + ), + ] { + out.push(Vertex { + pos: m.transform_point3(p).to_array(), + uv, + layer: 6, + color: c, + light: wrap_light, + }); + } + (last_sin, last_cos, last_u) = (sin, cos, uu); + } + } + /// Dragon fireballs as the dragon_fireball sprite facing the camera. + pub(super) fn dragon_fireball_geometry( + &self, + camera: glam::DVec3, + alpha: f64, + out: &mut Vec, + ) { + let Some(s) = self + .res + .atlas + .sprites + .get("entity/enderdragon/dragon_fireball") + .copied() + else { + return; + }; + let forward = glam::DVec3::from_array(super::view_vector(self.yaw, self.pitch)); + let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); + let up = right.cross(forward).normalize_or_zero(); + for b in &self.dragon_fireballs { + let p = glam::DVec3::new( + b.previous.x + (b.position.x - b.previous.x) * alpha, + b.previous.y + (b.position.y - b.previous.y) * alpha, + b.previous.z + (b.position.z - b.previous.z) * alpha, + ) - camera; + // DragonFireballRenderer: scale 2, full bright. + let h = 1.0; + for (c, uv) in [ + (p - right * h - up * h, [s.u0, s.v1]), + (p + right * h - up * h, [s.u1, s.v1]), + (p + right * h + up * h, [s.u1, s.v0]), + (p - right * h + up * h, [s.u0, s.v0]), + ] { + out.push(Vertex { + pos: c.as_vec3().to_array(), + uv, + layer: 0, + color: 0xFFFF_FFFF, + light: 240 | 240 << 8, + }); + } + } + } + pub(super) fn fight_ready(&mut self) -> bool { + self.load_fight(); + self.fight.loaded + } + pub(super) fn exit_portal(&self) -> Option<[i32; 3]> { + self.fight.exit_portal + } + pub(super) fn set_exit_portal(&mut self, origin: [i32; 3]) { + if self.fight.exit_portal.is_none() { + self.fight.exit_portal = Some(origin); + self.fight.dirty = true; + } + } +} +/// Saving and loading the dragon and the crystals as chunk entities. +impl Dragon { + pub(super) fn to_nbt(&self, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { + let mut tag = horizon_client::entity_nbt::vehicle_to_nbt( + "minecraft:ender_dragon", + self.position, + self.velocity, + self.yaw, + uuid, + raw, + ); + if let Tag::Compound(map) = &mut tag { + map.insert("Health".into(), Tag::Float(self.health.to_bits())); + map.insert("DragonPhase".into(), Tag::Int(self.phase.id())); + map.insert("DragonDeathTime".into(), Tag::Int(self.death_time)); + map.insert( + "sitting_damage_received".into(), + Tag::Float(self.sitting_damage.to_bits()), + ); + } + tag + } + pub(super) fn from_nbt(tag: &Tag, seed: i64) -> Option { + let (position, velocity, yaw) = horizon_client::entity_nbt::boat_from_nbt(tag)?; + let mut d = Self::new(position, yaw, seed); + d.velocity = velocity; + if let Some(Tag::Float(h)) = tag.get("Health") { + d.health = f32::from_bits(*h); + } + if let Some(Tag::Int(p)) = tag.get("DragonPhase") { + d.phase = Phase::from_id(*p); + } + if let Some(Tag::Int(t)) = tag.get("DragonDeathTime") { + d.death_time = *t; + } + Some(d) + } +} +impl Crystal { + pub(super) fn to_nbt(&self, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { + let mut tag = horizon_client::entity_nbt::vehicle_to_nbt( + "minecraft:end_crystal", + self.position, + Vec3::ZERO, + 0.0, + uuid, + raw, + ); + if let Tag::Compound(map) = &mut tag { + map.insert("ShowBottom".into(), Tag::Byte(i8::from(self.show_bottom))); + if let Some(b) = self.beam { + map.insert("beam_target".into(), Tag::IntArray(b.to_vec())); + } + } + tag + } + pub(super) fn from_nbt(tag: &Tag, time: i32) -> Option { + let (position, _, _) = horizon_client::entity_nbt::boat_from_nbt(tag)?; + Some(Self { + position, + show_bottom: !matches!(tag.get("ShowBottom"), Some(Tag::Byte(0))), + time, + beam: match tag.get("beam_target") { + Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]), + _ => None, + }, + }) + } +} +impl Game<'_> { + /// `Explosion.explode` for crystals (they blow up in turn) and the + /// dragon's parts (explosions always hurt dragons). + pub(super) fn explosion_hits_special(&mut self, center: [f64; 3], radius: f32) { + let diameter = f64::from(radius * 2.0); + let dist = |p: Vec3| { + ((p.x - center[0]).powi(2) + (p.y - center[1]).powi(2) + (p.z - center[2]).powi(2)) + .sqrt() + }; + if let Some(i) = self + .crystals + .iter() + .position(|c| dist(c.position) / diameter <= 1.0) + { + self.destroy_crystal(i, false); + } + if let Some(d) = self.dragon.as_ref() { + let hits: Vec<(usize, f32)> = (0..8) + .filter_map(|i| { + let p = d.parts[i].0; + let r = dist(p) / diameter; + (r <= 1.0).then(|| { + let pow = 1.0 - r; + (i, ((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32) + }) + }) + .collect(); + if let Some(&(part, amount)) = hits.iter().max_by(|a, b| a.1.total_cmp(&b.1)) { + self.hurt_dragon(part, amount, true); + } + } + } +} +impl Game<'_> { + /// The dragon and fight for `horizon-ctl status`. + pub(super) fn dragon_status(&self) -> serde_json::Value { + serde_json::json!({ + "dragon": self.dragon.as_ref().map(|d| serde_json::json!({ + "position": [d.position.x, d.position.y, d.position.z], + "health": d.health, + "phase": d.phase.id(), + "death_time": d.death_time, + })), + "crystals": self.crystals.len(), + "alive_crystals": self.fight.alive_crystals, + "killed": self.fight.killed, + }) + } +} diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d3ed73a85..d32a6dbdb 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -1,7 +1,7 @@ //! The End: End portal frames filled with eyes of ender, End portal and End //! gateway travel, the obsidian arrival platform, the exit portal and the End -//! sky. The ender dragon is not implemented: the fight counts as already won, -//! so the exit portal is active and the first gateway exists. +//! sky. The dragon fight itself lives in game/dragon.rs: the podium is +//! inactive until the dragon dies. use super::{Dim, Game}; use horizon_client::{ Result, environment::Environment, items::ItemStack, mesher::Vertex, motion::PlayerMotion, @@ -343,6 +343,10 @@ impl Game<'_> { /// End portals, End gateways and the exit portal, once per tick. pub(super) fn tick_end(&mut self) -> Result<()> { self.end.gateway_cooldown = self.end.gateway_cooldown.saturating_sub(1); + if self.dim == Dim::End { + self.tick_fight(); + self.tick_dragon_fireballs(); + } self.scan_portals(); self.tick_eyes(); if self.dim == Dim::End { @@ -510,13 +514,16 @@ impl Game<'_> { fn ensure_exit_portal(&mut self) -> Result<()> { if self.travelling.is_some() || !(-1..=0).all(|cz| (-1..=0).all(|cx| self.streaming.is_lit(cx, cz))) + || !self.fight_ready() { return Ok(()); } + let won = self.fight.previously_killed; let gateway = self.first_gateway(); if (0..256).any(|y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") { // The podium exists; the gateway may have been out of range when it was placed. - if self.world.loaded(gateway[0], gateway[2]) + if won + && self.world.loaded(gateway[0], gateway[2]) && &*self.block_name(gateway) != "minecraft:end_gateway" && &*self.block_name([gateway[0], gateway[1] + 2, gateway[2]]) != "minecraft:bedrock" @@ -538,12 +545,31 @@ impl Game<'_> { y -= 1; } let origin = [0, y.max(1), 0]; - self.place_podium(origin)?; - if self.world.loaded(gateway[0], gateway[2]) { + self.set_exit_portal(origin); + self.place_podium(origin, won)?; + if won && self.world.loaded(gateway[0], gateway[2]) { self.place_gateway(gateway)?; } Ok(()) } + /// `spawnExitPortal(true)` after the dragon dies. + pub(super) fn activate_exit_portal(&mut self) -> Result<()> { + let origin = match self.exit_portal() { + Some(o) => o, + None => { + // The rim's level: the top of the bedrock column minus three. + let top = (0..256) + .rev() + .find(|&y| &*self.block_name([0, y, 0]) == "minecraft:bedrock") + .unwrap_or(64); + [0, top - 3, 0] + } + }; + self.place_podium(origin, true) + } + pub(super) fn place_gateway_at(&mut self, pos: [i32; 3]) -> Result<()> { + self.place_gateway(pos) + } /// The first gateway of the shuffled ring (EnderDragonFight constructor /// and spawnNewGateway). @@ -564,7 +590,7 @@ impl Game<'_> { } /// EndPodiumFeature(active).place at `origin` (the portal level). - fn place_podium(&mut self, origin: [i32; 3]) -> Result<()> { + fn place_podium(&mut self, origin: [i32; 3], active: bool) -> Result<()> { for y in origin[1] - 1..=origin[1] + 32 { for z in origin[2] - 4..=origin[2] + 4 { for x in origin[0] - 4..=origin[0] + 4 { @@ -585,8 +611,10 @@ impl Game<'_> { "minecraft:air" } else if !inside_rim { "minecraft:bedrock" - } else { + } else if active { "minecraft:end_portal" + } else { + "minecraft:air" }; self.set_state_named([x, y, z], name, &[])?; } @@ -1065,8 +1093,7 @@ impl Game<'_> { self.eye_geometry(camera, out); } - /// EndCrystalRenderer and EndCrystalModel for the crystals EndSpikeFeature - /// spawns on the spikes (render only; crystals are not entities yet). + /// EndCrystalRenderer and EndCrystalModel for the end crystals. fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let Some(r) = self .res @@ -1077,26 +1104,21 @@ impl Game<'_> { else { return; }; - let age = self.ticks as f32 + self.clock.fraction() as f32; let sin45 = std::f32::consts::FRAC_PI_4.sin(); let axis = glam::Vec3::new(sin45, 0.0, sin45).normalize(); let tilt = glam::Quat::from_axis_angle(axis, std::f32::consts::FRAC_PI_3); - let spin = glam::Quat::from_rotation_y((age * 3.0).to_radians()); - // getY: the bob, in blocks. - let hh = (age * 0.2).sin() / 2.0 + 0.5; - let bob = (hh * hh + hh) * 0.4 - 1.4; // A 8×8×8 model box at texture offset (u, v) of the 64×32 texture. let uv = |u: f32, v: f32, w: f32, h: f32| { let su = |x: f32| r.u0 + (r.u1 - r.u0) * x / 64.0; let sv = |y: f32| r.v0 + (r.v1 - r.v0) * y / 32.0; (su(u), su(u + w), sv(v), sv(v + h)) }; - for spike in horizon_world::worldgen::end_spike::spikes_for_seed(self.level.seed) { - let feet = glam::DVec3::new( - f64::from(spike.center_x) + 0.5, - f64::from(spike.height + 1), - f64::from(spike.center_z) + 0.5, - ); + for crystal in &self.crystals { + let feet = glam::DVec3::new(crystal.position.x, crystal.position.y, crystal.position.z); + let age = crystal.time as f32 + self.clock.fraction() as f32; + let spin = glam::Quat::from_rotation_y((age * 3.0).to_radians()); + let hh = (age * 0.2).sin() / 2.0 + 0.5; + let bob = (hh * hh + hh) * 0.4 - 1.4; let rel = feet - camera; if rel.length_squared() > 256.0 * 256.0 { continue; diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 943d8319e..9185252f1 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -168,6 +168,7 @@ impl Game<'_> { if radius < 1.0e-5 { return; } + self.explosion_hits_special(center, radius); let diameter = f64::from(radius * 2.0); let distance = |p: [f64; 3]| { ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)) diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 110517d6e..6ac336780 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -33,6 +33,10 @@ impl Game<'_> { .name .as_str() }); + // Minecraft.getSituationalMusic: the boss bar's music in the End. + if self.boss_music() { + return (Some(Music::end_boss()), 1.0); + } let dimension = self.dim.id(); let tables = &self.res.music; // Player.isUnderWater: eyes in water. diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 1bb215903..53ac3206d 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -156,6 +156,20 @@ impl Game<'_> { self.carts.push(c); } } + "minecraft:ender_dragon" => { + let seed = self.world.random.next_long(); + if self.dragon.is_none() + && let Some(d) = super::dragon::Dragon::from_nbt(&tag, seed) + { + self.dragon = Some(d); + } + } + "minecraft:end_crystal" => { + let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + if let Some(c) = super::dragon::Crystal::from_nbt(&tag, time) { + self.crystals.push(c); + } + } "minecraft:armor_stand" => { self.next_entity += 1; if let Some(a) = entity_nbt::armor_stand_from_nbt(&tag, self.next_entity) { @@ -326,6 +340,20 @@ impl Game<'_> { out.entry(chunk_of(b.position)).or_default().push(tag); } } + if let Some(d) = &self.dragon + && keys.contains(&chunk_of(d.position)) + { + out.entry(chunk_of(d.position)) + .or_default() + .push(d.to_nbt(random_uuid(), None)); + } + for c in &self.crystals { + if keys.contains(&chunk_of(c.position)) { + out.entry(chunk_of(c.position)) + .or_default() + .push(c.to_nbt(random_uuid(), None)); + } + } for c in &self.carts { if keys.contains(&chunk_of(c.position)) { let uuid = self @@ -402,6 +430,10 @@ impl Game<'_> { } keep }); + self.crystals.retain(|c| !gone(c.position)); + if self.dragon.as_ref().is_some_and(|d| gone(d.position)) { + self.dragon = None; + } self.carts.retain(|c| { let keep = !gone(c.position) || Some(c.id) == riding; if !keep { diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 77151edde..f71b53373 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -240,8 +240,10 @@ impl PlayerMotion { .source::<()>(source, None, None, None) .ok_or("unknown resident damage source")?; let totem_ready = self.health.totem_ready; + let invulnerable = self.invulnerable; let h = &mut self.health; let mut environment = Environment { + invulnerable, rules, source, events: &mut self.events, @@ -293,6 +295,8 @@ impl PlayerMotion { } } pub(crate) struct Environment<'a> { + /// Abilities.invulnerable. + pub(crate) invulnerable: bool, pub(crate) rules: HealthRules, pub(crate) source: DamageSource<'a, ()>, pub(crate) events: &'a mut Vec, @@ -418,7 +422,7 @@ impl ServerDamageEnvironment for Environment<'_> { Ok(self.source.definition().exhaustion) } fn ability_invulnerable(&self) -> bool { - false + self.invulnerable } fn level_is_client(&mut self) -> io::Result { Ok(false) @@ -615,7 +619,7 @@ impl HurtWorld for Environment<'_> { } impl PlayerHurtWorld for Environment<'_> { fn ability_invulnerable(&self) -> bool { - false + self.invulnerable } fn bypasses_invulnerability(&mut self, _: &mut State) -> io::Result { Ok(self.source.in_tag("minecraft:bypasses_invulnerability")) diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index cc46d9f28..90b11f18d 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -124,6 +124,7 @@ impl FoodWorld for TickWorld<'_> { self.events .push(MotionEvent::Health(HealthEvent::StarvationDamage(amount))); let mut environment = Environment { + invulnerable: false, rules: self.rules, source: self .resources diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 91fef14b9..5f87437c2 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -140,6 +140,8 @@ pub struct PlayerMotion { pub jump_trigger_time: i32, /// Abilities.mayfly / flying (creative flight). pub may_fly: bool, + /// Abilities.invulnerable (creative): only damage bypassing invulnerability hurts. + pub invulnerable: bool, pub flying: bool, /// The jump key last tick (LocalPlayer.aiStep's wasJumping). pub was_jumping: bool, @@ -222,6 +224,7 @@ impl PlayerMotion { no_jump_delay: 0, jump_trigger_time: 0, may_fly: false, + invulnerable: false, flying: false, was_jumping: false, glider: false,