diff --git a/crates/horizon-client-core/src/block_entity_nbt.rs b/crates/horizon-client-core/src/block_entity_nbt.rs index 6e214fd61..a4387bf48 100644 --- a/crates/horizon-client-core/src/block_entity_nbt.rs +++ b/crates/horizon-client-core/src/block_entity_nbt.rs @@ -61,6 +61,16 @@ fn f32_tag(v: f32) -> Tag { Tag::Float(v.to_bits()) } +/// `TheEndGatewayBlockEntity.loadAdditional`: BlockPos.CODEC and Level.isInSpawnableBounds. +pub fn gateway_exit(tag: &Tag) -> Option<[i32; 3]> { + let Tag::IntArray(v) = tag else { return None }; + let p: [i32; 3] = v.as_slice().try_into().ok()?; + ((-30_000_000..30_000_000).contains(&p[0]) + && (-20_000_000..20_000_000).contains(&p[1]) + && (-30_000_000..30_000_000).contains(&p[2])) + .then_some(p) +} + /// What a block entity reads and writes, in `saveAdditional` order. struct Fields<'a> { input: &'a Tag, @@ -424,10 +434,7 @@ pub fn canonical(tag: &Tag) -> Option { } "minecraft:end_gateway" => { f.long("Age", 0); - f.keep("exit_portal", |t| { - is_pos(t) - && matches!(t, Tag::IntArray(v) if v[1].abs() <= 30_000_000 && v[0].abs() <= 30_000_000 && v[2].abs() <= 30_000_000) - }); + f.keep("exit_portal", |t| gateway_exit(t).is_some()); if flag(tag.get("ExactTeleport")) == Some(true) { f.put("ExactTeleport", boolean(true)); } diff --git a/crates/horizon-client-core/src/lib.rs b/crates/horizon-client-core/src/lib.rs index ca40141d1..2030165c5 100644 --- a/crates/horizon-client-core/src/lib.rs +++ b/crates/horizon-client-core/src/lib.rs @@ -1,8 +1,9 @@ //! The client's lowest layer, below commands and gameplay: chat text and //! translations, SNBT and NBT paths, text components, the scoreboard, boss //! bars, game rules, block entity NBT tables, and the registry, particle and -//! sound source tables commands name. horizon-client re-exports each module -//! under its old path (`horizon_client::text`, ...). +//! sound source tables commands name, and the `pack.mcmeta` filter regex. +//! horizon-client re-exports each module under its old path +//! (`horizon_client::text`, ...). #![forbid(unsafe_code)] pub mod block_entity_nbt; pub mod bossbar; @@ -14,6 +15,7 @@ pub mod key_display; pub mod lang; pub mod nbt_path; pub mod particle_type; +pub mod pattern; pub mod registries; pub mod scoreboard; pub mod snbt; diff --git a/crates/horizon-client/src/packs/pattern.rs b/crates/horizon-client-core/src/pattern.rs similarity index 100% rename from crates/horizon-client/src/packs/pattern.rs rename to crates/horizon-client-core/src/pattern.rs diff --git a/crates/horizon-client/examples/probe/mob_ai_probe.rs b/crates/horizon-client/examples/probe/mob_ai_probe.rs index 4688a5f45..94578ea38 100644 --- a/crates/horizon-client/examples/probe/mob_ai_probe.rs +++ b/crates/horizon-client/examples/probe/mob_ai_probe.rs @@ -580,7 +580,7 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool { match e { MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0, // ServerExplosion.hurtEntities: within twice the radius every hit does damage. - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, _) => { let d = Vec3::new(at[0], at[1], at[2]) .distance_squared(p.position) .sqrt(); @@ -1050,6 +1050,7 @@ pub fn main() -> horizon_client::Result<()> { off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, @@ -1082,6 +1083,7 @@ pub fn main() -> horizon_client::Result<()> { world: &world, registry, facts: &facts, + fluid_tables: &motion.fluids, movement: &motion.blocks, collision: &collision, data: &data, @@ -1099,6 +1101,7 @@ pub fn main() -> horizon_client::Result<()> { block_tags: &items.block_tags, biomes: &biomes, mob_griefing: true, + mob_drops: true, difficulty: LocalDifficulty::new(s.difficulty, world.day_time, 0, 0.0), end: false, world_seed: 0, diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 6706532b7..62e7f365f 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -703,6 +703,52 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo } true } +/// A damage event as `DamagePredicate` sees it. +#[derive(Clone, Debug, Default)] +pub struct DamageView { + /// The damage type id (`minecraft:arrow`). + pub kind: String, + /// `DamageSource.getDirectEntity` and `getEntity`. + pub direct: Option, + pub source: Option, + /// `DamageSource.isDirect`: the direct entity is the causing one. + pub is_direct: bool, + /// The damage before and after the shield took its share. + pub original: f32, + pub actual: f32, + pub blocked: bool, +} +/// `DamagePredicate`, with its `DamageSourcePredicate` as `type`. +pub fn damage(v: &Value, d: &DamageView, w: &dyn World, origin: [f64; 3]) -> bool { + if v.is_null() { + return true; + } + let by = |key: &str, e: &Option| { + v[key].is_null() || e.as_ref().is_some_and(|e| entity(&v[key], e, w, origin)) + }; + if !range_f(&v["dealt"], f64::from(d.original)) + || !range_f(&v["taken"], f64::from(d.actual)) + || !by("source_entity", &d.source) + || v["blocked"].as_bool().is_some_and(|b| b != d.blocked) + { + return false; + } + let ty = &v["type"]; + let tags_ok = ty["tags"].as_array().into_iter().flatten().all(|t| { + let tag = t["id"].as_str().unwrap_or(""); + let tag = tag.strip_prefix('#').unwrap_or(tag); + w.in_tag("damage_type", tag, &d.kind) == t["expected"].as_bool().unwrap_or(true) + }); + let direct_ok = ty["direct_entity"].is_null() + || d.direct + .as_ref() + .is_some_and(|e| entity(&ty["direct_entity"], e, w, origin)); + let source_ok = ty["source_entity"].is_null() + || d.source + .as_ref() + .is_some_and(|e| entity(&ty["source_entity"], e, w, origin)); + tags_ok && direct_ok && source_ok && ty["is_direct"].as_bool().is_none_or(|b| b == d.is_direct) +} /// The entities a loot-style condition list may refer to. pub struct Entities<'a> { pub this: Option<&'a EntityView>, diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 07548e208..c2123e693 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -36,8 +36,9 @@ enum Animate { spawn_particles: bool, }, /// Leaves: optional falling-leaf particle and chance; a tinted leaf takes - /// the biome foliage colour unless a fixed colour is given (azalea). - Leaves(Option<(T, f32)>, Option), + /// the biome foliage colour unless a fixed colour is given (azalea); and + /// whether they have the poplar ambient sound (`AmbientLeavesBlockSoundPlayer`). + Leaves(Option<(T, f32)>, Option, bool), NetherPortal, EnchantingTable, EndRod([i32; 3]), @@ -48,8 +49,9 @@ enum Animate { CandleCake, BrewingStand, EnderChest, - /// FallingBlock with its dust colour. - Falling(u32), + /// FallingBlock with its dust colour; sand also has the ambient desert sound + /// (`SandBlock.animateTick`). + Falling(u32, bool), /// A beehive or bee nest full of honey (`BeehiveBlock.animateTick`). Beehive, RedstoneOre, @@ -109,17 +111,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { spawn_particles: false, }, "oak_leaves" | "birch_leaves" | "jungle_leaves" | "acacia_leaves" | "dark_oak_leaves" - | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None), - "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None), - "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None), - "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None), - "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None), - "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None), + | "mangrove_leaves" => Animate::Leaves(Some((T::TintedLeaves, 0.01)), None, false), + "cherry_leaves" => Animate::Leaves(Some((T::CherryLeaves, 0.1)), None, false), + "pale_oak_leaves" => Animate::Leaves(Some((T::PaleOakLeaves, 0.02)), None, false), + "red_poplar_leaves" => Animate::Leaves(Some((T::RedPoplarLeaves, 0.01)), None, true), + "orange_poplar_leaves" => Animate::Leaves(Some((T::OrangePoplarLeaves, 0.01)), None, true), + "yellow_poplar_leaves" => Animate::Leaves(Some((T::YellowPoplarLeaves, 0.01)), None, true), // The azalea blocks drop tinted leaves of the fixed colour -9399763. "azalea_leaves" | "flowering_azalea_leaves" => { - Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D)) + Animate::Leaves(Some((T::TintedLeaves, 0.01)), Some(0x0070_922D), false) } - "spruce_leaves" => Animate::Leaves(None, None), + "spruce_leaves" => Animate::Leaves(None, None, false), "nether_portal" => Animate::NetherPortal, "enchanting_table" => Animate::EnchantingTable, "end_rod" => Animate::EndRod(facing()), @@ -128,16 +130,17 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "mycelium" => Animate::Mycelium, "brewing_stand" => Animate::BrewingStand, "ender_chest" => Animate::EnderChest, - "sand" => Animate::Falling(0xDBD3A0), - "red_sand" => Animate::Falling(0xA95821), - "gravel" => Animate::Falling(0x807C7B), + "sand" => Animate::Falling(0xDBD3A0, true), + "red_sand" => Animate::Falling(0xA95821, true), + "gravel" => Animate::Falling(0x807C7B, false), // AnvilBlock/ConcretePowderBlock.getDustColor is the map colour; // DragonEggBlock's is black. - "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7), - "dragon_egg" => Animate::Falling(0x000000), - _ if name.ends_with("_concrete_powder") => Animate::Falling(concrete_powder_color( - name.trim_end_matches("_concrete_powder"), - )), + "anvil" | "chipped_anvil" | "damaged_anvil" => Animate::Falling(0xA7A7A7, false), + "dragon_egg" => Animate::Falling(0x000000, false), + _ if name.ends_with("_concrete_powder") => Animate::Falling( + concrete_powder_color(name.trim_end_matches("_concrete_powder")), + false, + ), "beehive" | "bee_nest" if prop("honey_level").as_deref() == Some("5") => Animate::Beehive, "redstone_ore" | "deepslate_redstone_ore" if lit => Animate::RedstoneOre, "redstone_wire" => { @@ -171,8 +174,8 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { "end_portal" => Animate::EndPortal, "wet_sponge" => Animate::WetSponge, // BrushableBlock has no dust colour of its own, so the dust is the map colour. - "suspicious_sand" => Animate::Falling(0xF7E9A3), - "suspicious_gravel" => Animate::Falling(0x707070), + "suspicious_sand" => Animate::Falling(0xF7E9A3, false), + "suspicious_gravel" => Animate::Falling(0x707070, false), "sculk_sensor" | "calibrated_sculk_sensor" if prop("sculk_sensor_phase").as_deref() == Some("active") => { @@ -239,6 +242,10 @@ pub struct AnimateTables { power_transmitter: Vec, /// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil). dried_ghast_sounds: Vec, + /// `#triggers_ambient_desert_sand_block_sounds` (sand, red sand). + desert_sand_sounds: Vec, + /// `#required_for_poplar_leaf_ambience` (overworld natural logs). + poplar_leaf_logs: Vec, /// `FireBlock.canBurn`: states with ignite odds above zero (none waterlogged). burnable: Vec, /// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`). @@ -314,6 +321,8 @@ impl AnimateTables { power_provider: by_state("minecraft:enchantment_power_provider"), power_transmitter: by_state("minecraft:enchantment_power_transmitter"), dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"), + desert_sand_sounds: by_state("minecraft:triggers_ambient_desert_sand_block_sounds"), + poplar_leaf_logs: by_state("minecraft:required_for_poplar_leaf_ambience"), burnable, ambient, }) @@ -402,6 +411,10 @@ impl AnimateContext<'_> { fn add(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { engine.add(&ParticleOptions::simple(ty), p, v); } +/// `Level.addAlwaysVisibleParticle`: still shown under the Minimal option now and then. +fn add_visible(engine: &mut ParticleEngine, ty: T, p: [f64; 3], v: [f64; 3]) { + engine.add_with(&ParticleOptions::simple(ty), p, v, false, true); +} fn sound(engine: &mut ParticleEngine, name: &'static str, p: [f64; 3], volume: f32, pitch: f32) { engine.sounds.push((name, p, volume, pitch)); } @@ -777,7 +790,7 @@ fn block_animate_tick( } } } - Animate::Leaves(falling, fixed_tint) => { + Animate::Leaves(falling, fixed_tint, poplar) => { let below = [pos[0], pos[1] - 1, pos[2]]; // LeavesBlock.makeDrippingWaterParticles. if (ctx.raining_at)([pos[0], pos[1] + 1, pos[2]]) && next_int(engine.random(), 15) == 1 @@ -789,6 +802,9 @@ fn block_animate_tick( add(engine, T::DrippingWater, p, [0.0; 3]); } } + if poplar { + leaves_ambient_sound(tables, engine, ctx, state, pos); + } // FallingParticlesLeavesBlock.makeFallingLeavesParticles. if let Some((ty, chance)) = falling && engine.random().next_float() < chance @@ -961,7 +977,7 @@ fn block_animate_tick( fy + 1.0 + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::SulfurBubbles, p, [0.0; 3]); + add_visible(engine, T::SulfurBubbles, p, [0.0; 3]); } if next_int(engine.random(), 10) == 0 { let name = "minecraft:block.potent_sulfur.noxious_gas"; @@ -1081,7 +1097,7 @@ fn block_animate_tick( add(engine, T::Portal, p, v); } } - Animate::Falling(color) => { + Animate::Falling(color, sand) => { if next_int(engine.random(), 16) == 0 { let below = ctx.facts.get(ctx.state([pos[0], pos[1] - 1, pos[2]])); // FallingBlock.isFree: air, fire, liquids or replaceable. @@ -1098,6 +1114,14 @@ fn block_animate_tick( ); } } + // AmbientDesertBlockSoundsPlayer.playAmbientSandSounds: only for the air block. + if sand + && ctx.state([pos[0], pos[1] + 1, pos[2]]) == ctx.world.air + && next_int(engine.random(), 2100) == 0 + && sand_sound_nearby(tables, ctx, pos) + { + sound(engine, "minecraft:block.sand.idle", [fx, fy, fz], 1.0, 1.0); + } } Animate::Beehive => { // BeehiveBlock.animateTick: nextInt(1) + 1 attempts. @@ -1215,7 +1239,7 @@ fn block_animate_tick( } Animate::BubbleColumn { drag } => { if drag { - add(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); + add_visible(engine, T::CurrentDown, [fx + 0.5, fy + 0.8, fz], [0.0; 3]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); @@ -1228,7 +1252,7 @@ fn block_animate_tick( ); } } else { - add( + add_visible( engine, T::BubbleColumnUp, [fx + 0.5, fy, fz + 0.5], @@ -1240,7 +1264,7 @@ fn block_animate_tick( fy + f64::from(r.next_float()), fz + f64::from(r.next_float()), ]; - add(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); + add_visible(engine, T::BubbleColumnUp, p, [0.0, 0.04, 0.0]); let r = engine.random(); if next_int(r, 200) == 0 { let (volume, pitch) = (0.2 + r.next_float() * 0.2, 0.9 + r.next_float() * 0.15); @@ -1318,6 +1342,91 @@ fn block_animate_tick( } } } +/// `AmbientLeavesBlockSoundPlayer.playAmbientLeavesSounds` for the poplar leaves: +/// one log and three leaves of the same kind around the block. +fn leaves_ambient_sound( + tables: &AnimateTables, + engine: &mut ParticleEngine, + ctx: &AnimateContext, + state: BlockStateId, + pos: [i32; 3], +) { + if next_int(engine.random(), 300) != 0 { + return; + } + let Some(name) = ctx.registry.state(state).map(|s| &s.name) else { + return; + }; + let (mut logs, mut leaves) = (0, 0); + for d in [[0, -1], [1, 0], [0, 1], [-1, 0]] { + let neighbor = ctx.state([pos[0] + d[0], pos[1], pos[2] + d[1]]); + if tables + .poplar_leaf_logs + .get(neighbor.0 as usize) + .copied() + .unwrap_or(false) + { + logs += 1; + } + if ctx + .registry + .state(neighbor) + .is_some_and(|s| &s.name == name) + { + leaves += 1; + } + if logs == 1 && leaves == 3 { + let p = pos.map(f64::from); + sound(engine, "minecraft:block.poplar_leaves.ambient", p, 1.0, 1.0); + return; + } + } +} +/// `AmbientDesertBlockSoundsPlayer.shouldPlayAmbientSandSound`: sand in the +/// surface column eight blocks away on all four sides. +fn sand_sound_nearby(tables: &AnimateTables, ctx: &AnimateContext, pos: [i32; 3]) -> bool { + let is_sand = |p: [i32; 3]| { + tables + .desert_sand_sounds + .get(ctx.state(p).0 as usize) + .copied() + .unwrap_or(false) + }; + let (mut found, mut checked) = (0, 0); + for d in [[0, -8], [8, 0], [0, 8], [-8, 0]] { + let (x, z) = (pos[0] + d[0], pos[2] + d[1]); + // columnContainsTriggeringBlock. + let surface = ctx.world.world_surface(x, z, |s| ctx.facts.is_air(s)) - 1; + let matches = if (surface - pos[1]).abs() > 5 { + let mut y = pos[1] + 6; + let mut above_air = ctx.is_air([x, y, z]); + y -= 1; + let mut hit = false; + for _ in 0..10 { + if above_air && is_sand([x, y, z]) { + hit = true; + break; + } + above_air = ctx.is_air([x, y, z]); + y -= 1; + } + hit + } else { + ctx.is_air([x, surface + 1, z]) && is_sand([x, surface, z]) + }; + if matches { + found += 1; + if found > 3 { + return true; + } + } + checked += 1; + if 4 - checked + found < 3 { + return false; + } + } + false +} /// `AbstractCandleBlock.addParticlesAndSound`. fn candle(engine: &mut ParticleEngine, p: [f64; 3]) { let r = engine.random(); diff --git a/crates/horizon-client/src/atlas_sources.rs b/crates/horizon-client/src/atlas_sources.rs index 1eea24666..fbed22fd2 100644 --- a/crates/horizon-client/src/atlas_sources.rs +++ b/crates/horizon-client/src/atlas_sources.rs @@ -3,8 +3,8 @@ //! `filter`, `unstitch` and `paletted_permutations` sources run in order //! against the resource tree; a later source replaces an earlier sprite of //! the same id and a filter removes the matching ones. -use crate::packs::pattern::Pattern; use horizon_assets::palette::apply_palette; +use horizon_client_core::pattern::Pattern; use serde_json::Value; use std::{ collections::BTreeMap, diff --git a/crates/horizon-client/src/auth.rs b/crates/horizon-client/src/auth.rs index b899ea5d5..a86992735 100644 --- a/crates/horizon-client/src/auth.rs +++ b/crates/horizon-client/src/auth.rs @@ -179,7 +179,7 @@ fn agent() -> ureq::Agent { } /// The discovery document, fetched once per game (a failure is retried next time). -fn discovery() -> Result, JoinError> { +pub(crate) fn discovery() -> Result, JoinError> { static CACHE: Mutex>> = Mutex::new(None); if let Some(d) = CACHE.lock().unwrap().clone() { return Ok(d); diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index a312fe9f7..db063e3e3 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -736,7 +736,7 @@ pub struct Scene<'a> { /// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer` /// profile → skin): a downloaded `skins/` slot or the profile's /// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve). - pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>, + pub skull: &'a dyn Fn([i32; 3]) -> Option, /// Font glyph cell (none for blank glyphs such as the space) and advance. pub glyph: &'a dyn Fn(char) -> (Option, f32), } @@ -1288,11 +1288,12 @@ impl BlockEntityRenderer { }; // SkullBlockRenderer.getRenderType: the profile's skin when it // resolves, `SKIN_BY_TYPE` (steve) otherwise. - let texture = if *kind == SkullType::Player { - (scene.skull)(pos).unwrap_or(texture) + let skin = if *kind == SkullType::Player { + (scene.skull)(pos) } else { - texture + None }; + let texture = skin.as_deref().unwrap_or(texture); let (Some(model), Some(paint)) = (self.models.get(model), paint(texture, 0xFFFFFF, packed)) else { diff --git a/crates/horizon-client/src/cauldron.rs b/crates/horizon-client/src/cauldron.rs index 03fb0676d..25a709e26 100644 --- a/crates/horizon-client/src/cauldron.rs +++ b/crates/horizon-client/src/cauldron.rs @@ -40,6 +40,8 @@ pub struct Interaction { /// The cauldron's new state. pub block: Option, pub sound: Option<&'static str>, + /// The custom statistic the player earns (`use_cauldron`, ...). + pub stat: Option<&'static str>, } fn state(name: &str, level: Option) -> BlockState { @@ -57,6 +59,7 @@ fn pass() -> Interaction { outcome: Outcome::Pass, block: None, sound: None, + stat: None, } } @@ -117,11 +120,12 @@ fn lowered(cauldron: &BlockState) -> BlockState { } } -fn changed(block: BlockState, sound: Option<&'static str>) -> Interaction { +fn changed(block: BlockState, sound: Option<&'static str>, stat: &'static str) -> Interaction { Interaction { outcome: Outcome::Success, block: Some(block), sound, + stat: Some(stat), } } @@ -179,18 +183,22 @@ pub fn interact( stack.data_mut().dyed_color = None; stack.tidy(); } - return changed(lowered(cauldron), None); + return changed(lowered(cauldron), None, "clean_armor"); } let fill_bucket = |player: &mut dyn Player, new: &str, can_fill: bool, sound| { if !can_fill { return pass(); } filled(player, ItemStack::new(new, 1), true); - changed(state("minecraft:cauldron", None), Some(sound)) + changed( + state("minecraft:cauldron", None), + Some(sound), + "use_cauldron", + ) }; let empty_bucket = |player: &mut dyn Player, block: BlockState, sound| { filled(player, ItemStack::new("minecraft:bucket", 1), true); - changed(block, Some(sound)) + changed(block, Some(sound), "fill_cauldron") }; match item { "minecraft:lava_bucket" => { @@ -199,6 +207,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -221,6 +230,7 @@ pub fn interact( outcome: Outcome::Consume, block: None, sound: None, + stat: None, } } else { empty_bucket( @@ -241,6 +251,7 @@ pub fn interact( changed( state("minecraft:water_cauldron", Some(1)), Some("minecraft:item.bottle.empty"), + "use_cauldron", ) } ("water", "minecraft:bucket") => fill_bucket( @@ -255,7 +266,11 @@ pub fn interact( ItemStack::new("minecraft:potion", 1).with_potion("minecraft:water"), true, ); - changed(lowered(cauldron), Some("minecraft:item.bottle.fill")) + changed( + lowered(cauldron), + Some("minecraft:item.bottle.fill"), + "use_cauldron", + ) } ("water", "minecraft:potion") => { if level == 3 || !water_potion { @@ -266,7 +281,7 @@ pub fn interact( // BlockState.cycle on a 1..=3 property next.properties .insert("level".into(), (level % 3 + 1).to_string()); - changed(next, Some("minecraft:item.bottle.empty")) + changed(next, Some("minecraft:item.bottle.empty"), "use_cauldron") } ("water", name) if name @@ -283,7 +298,7 @@ pub fn interact( cleaned.data_mut().banner_patterns.pop(); cleaned.tidy(); filled(player, cleaned, false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_banner") } ("water", name) if name @@ -292,7 +307,7 @@ pub fn interact( .is_some_and(|c| COLORS.contains(&c)) => { filled(player, held.transmute("minecraft:shulker_box", 1), false); - changed(lowered(cauldron), None) + changed(lowered(cauldron), None, "clean_shulker_box") } ("lava", "minecraft:bucket") => fill_bucket( player, diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index 7cd375343..f3df1ea14 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -2,6 +2,7 @@ //! threads can mesh and light immutable snapshots while the game thread edits //! (copy-on-write through `Arc::make_mut`). use horizon_core::paletted::{PalettedContainer, Strategy}; +use horizon_world::nbt::{Compound, Tag}; use horizon_world::registry::BlockStateId; use std::sync::{Arc, OnceLock}; @@ -155,7 +156,7 @@ pub struct Chunk { /// positions, applied once by LevelChunk.postProcessGeneration. pub postprocess: Vec<[i32; 3]>, /// Saved data Horizon keeps but does not simulate (save.rs). - pub saved: Option>, + pub saved: Option>, /// Entities read from a save (vanilla entity NBT), spawned on arrival. pub entities: Vec, /// Structure starts reaching into this chunk (`structures.References`): @@ -432,3 +433,57 @@ mod tests { } } } + +/// A container's loot table and what Horizon rolled from it. Vanilla keeps +/// `LootTable` and `LootTableSeed` until the container is first opened; +/// Horizon rolls when it generates or loads the chunk, and saves the table +/// again while the container still holds exactly the rolled items. +#[derive(Clone, Debug, PartialEq)] +pub struct RolledLoot { + pub pos: (i32, i32, i32), + pub table: String, + /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). + pub seed: Option, + /// The rolled `Items`. + pub items: Tag, +} +impl RolledLoot { + /// Puts the loot table back in place of `Items` while they are still the + /// roll; false once the container holds anything else. + pub fn restore(&self, map: &mut Compound) -> bool { + if map.get(&"Items".into()) != Some(&self.items) { + return false; + } + map.remove(&"Items".into()); + map.insert("LootTable".into(), Tag::String(self.table.as_str().into())); + if let Some(seed) = self.seed.filter(|s| *s != 0) { + map.insert("LootTableSeed".into(), Tag::Long(seed)); + } + true + } +} + +/// Save data loaded with a chunk that Horizon keeps but does not simulate. +#[derive(Clone, Debug, Default)] +pub struct ChunkExtras { + /// Chunk root keys written back as loaded (structures, PostProcessing, + /// InhabitedTime, blending data, ...). + pub root: Compound, + /// Block entities Horizon does not model. + pub block_entities: Vec, + /// The NBT of the modelled block entities as loaded, to restore the fields and + /// detail Horizon does not model when it saves them (`block_entity_nbt::overlay`). + pub block_entity_sources: Vec<((i32, i32, i32), Tag)>, + /// Every saved block entity's position in the order of the save's list, + /// the order `SerializableChunkData` puts them in the chunk's maps. + pub block_entity_order: Vec<(i32, i32, i32)>, + /// Scheduled ticks (`block_ticks`/`fluid_ticks`): delays relative to the + /// save time. Registered with the level's tick scheduler on arrival and + /// replaced with the scheduler's pending ticks when saving. + pub block_ticks: Vec, + pub fluid_ticks: Vec, + /// Game time written as `LastUpdate`. + pub last_update: i64, + /// Containers still holding their loot table's roll. + pub rolled_loot: Vec, +} diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 7c32bd829..d35a1adfa 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -54,6 +54,27 @@ fn strider_liquid_shape() -> VoxelShape { VoxelShape::from_cube([1, 2, 1], &[true, false]).expect("a valid half-block column") } +// Vanilla scopes this direction to Entity.move while a piston pushes it. +thread_local! { + static PISTON_NOCLIP: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +/// Suppress the moving part of pistons moving in this direction during a push. +pub fn with_piston_noclip( + direction: horizon_core::geometry::Direction, + f: impl FnOnce() -> T, +) -> T { + struct Reset(Option); + impl Drop for Reset { + fn drop(&mut self) { + PISTON_NOCLIP.with(|value| value.set(self.0)); + } + } + let previous = PISTON_NOCLIP.with(|value| value.replace(Some(direction))); + let _reset = Reset(previous); + f() +} + pub struct SceneCollisions<'w, 'r> { pub world: &'w World, pub binding: &'w BlockCollisionRegistry<'r>, @@ -140,8 +161,21 @@ impl> EntityMovementWorld for EntityCo border.collision_shape().map(Some).map_err(io::Error::other) } } -impl EntityCollisions<'_, SceneCollisions<'_, '_>> { - /// `SceneCollisions::resolve` that also stops at the entity boxes. +impl<'a, W> EntityCollisions<'a, W> +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + /// `EntityCollisions` for a body the world border also stops: the border + /// and the body's own x and z (`WorldBorder.isInsideCloseToBorder`). + pub fn with_border(blocks: W, border: &'a BorderGeometry, at: [f64; 2]) -> Self { + Self { + blocks, + entities: &[], + border: Some((border, at)), + } + } + /// `SceneCollisions::resolve` that also stops at the entity boxes and, + /// with a border, at the world border's walls. pub fn resolve( &mut self, bounds: Aabb, @@ -149,12 +183,11 @@ impl EntityCollisions<'_, SceneCollisions<'_, '_>> { max_step: f32, on_ground: bool, ) -> Result { - let context = self.blocks.context(bounds); Ok(resolve_world_movement( self, MovementRequest { entity: EntityIdentity(0), - context, + context: CollisionContext::position(bounds.min_position().y), bounds, movement, max_step, @@ -324,7 +357,7 @@ impl DynamicSupportWorld for SceneCollisions<'_, '_> { return Ok(None); }; pistons - .collision_shape(self, p, piston, None) + .collision_shape(self, p, piston, PISTON_NOCLIP.with(|value| value.get())) .map(Some) .map_err(io::Error::other) } @@ -388,6 +421,42 @@ impl PowderSnowWorld for SceneCollisions<'_, '_> { } } +/// A collision world without blocks: no chunk is resident, so only the +/// world border stops a body. +pub struct EmptyCollisions; + +impl BlockCollisionWorld for EmptyCollisions { + type Error = io::Error; + type Chunk = ChunkPos; + fn collision_chunk(&mut self, _: ChunkPos) -> io::Result> { + Ok(None) + } + fn collision_block(&mut self, _: ChunkPos, _: BlockPos) -> io::Result { + Err(io::Error::other("no chunk is resident")) + } + fn is_suffocating(&mut self, _: ChunkPos, _: CollisionBlock, _: BlockPos) -> io::Result { + Ok(false) + } + fn context_shape( + &mut self, + _: CollisionBlock, + _: BlockPos, + _: &CollisionContext<'_>, + ) -> io::Result { + Ok(VoxelShape::empty()) + } +} + +impl EntityMovementWorld for EmptyCollisions { + type Error = io::Error; + fn entity_collisions(&mut self, _: EntityIdentity, _: Aabb) -> io::Result> { + Ok(Vec::new()) + } + fn movement_border(&mut self, _: EntityIdentity, _: Aabb) -> io::Result> { + Ok(None) + } +} + /// Collision queries over any block lookup (test worlds without chunks): /// every chunk is present, nothing is suffocating, no entities collide. pub struct LookupCollisions<'w, 'r> { @@ -475,3 +544,70 @@ impl PowderSnowWorld for LookupCollisions<'_, '_> { Ok(false) } } + +#[cfg(test)] +mod piston_noclip_tests { + use super::*; + use horizon_core::geometry::Direction; + + #[test] + fn piston_noclip_is_scoped_and_restored_after_unwind() { + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + with_piston_noclip(Direction::East, || { + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + let _ = + std::panic::catch_unwind(|| with_piston_noclip(Direction::West, || panic!("test"))); + assert_eq!( + PISTON_NOCLIP.with(|value| value.get()), + Some(Direction::East) + ); + }); + assert_eq!(PISTON_NOCLIP.with(|value| value.get()), None); + } +} + +#[cfg(test)] +mod border_movement_tests { + use super::*; + + /// A border 10 wide around the origin: its wall's inner face is at x = 5. + fn border() -> BorderGeometry { + BorderGeometry::new([0.0, 0.0], 10.0, 29_999_984).expect("a border") + } + + /// `WorldBorder.isInsideCloseToBorder` and `WorldBorder.getCollisionShape`: + /// a body inside close to the border collides with the border's walls. + #[test] + fn a_body_next_to_the_border_stops_at_its_wall() { + // A body 0.6 wide, 0.4 blocks short of the wall, moved east into it. + let bounds = Aabb::new(Vec3::new(4.0, 0.0, 0.0), Vec3::new(4.6, 1.8, 0.6)); + let border = border(); + let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [4.3, 0.3]); + let moved = collisions + .resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false) + .expect("the movement resolves"); + // The wall stops the body 0.4 blocks short of the whole move. + assert!( + (moved.x - 0.4).abs() < 1.0e-9, + "the body was not stopped by the border: {moved:?}" + ); + } + + /// Away from the border, the same body moves the whole way. + #[test] + fn a_body_away_from_the_border_moves_whole() { + let bounds = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.6, 1.8, 0.6)); + let border = border(); + let mut collisions = EntityCollisions::with_border(EmptyCollisions, &border, [0.3, 0.3]); + let moved = collisions + .resolve(bounds, Vec3::new(0.51, 0.0, 0.0), 0.0, false) + .expect("the movement resolves"); + assert!( + (moved.x - 0.51).abs() < 1.0e-9, + "the body did not move the whole way: {moved:?}" + ); + } +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 956d2b9a4..ed7d09a60 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -98,10 +98,19 @@ pub enum BlockEntity { Campfire(Box), /// `SkullBlockEntity` of every skull and head block. Skull(Skull), + /// `TheEndGatewayBlockEntity`: its age and configured destination. + EndGateway(EndGateway), /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, } +/// `TheEndGatewayBlockEntity`. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct EndGateway { + pub age: i64, + pub exit_portal: Option<[i32; 3]>, + pub exact_teleport: bool, +} /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). #[derive(Clone, Debug, Default, PartialEq)] @@ -190,6 +199,9 @@ impl Skull { #[derive(Clone, Debug)] pub struct SkullSkin { pub download: Option<(String, String)>, + /// `ResolvableProfile.nameOrId` when the profile is `Dynamic` (a name or + /// an id only): the key `skins::Resolver` resolves it by. + pub dynamic: Option, pub fallback: &'static str, } impl SkullSkin { @@ -198,10 +210,21 @@ impl SkullSkin { let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?); Some((url, location)) }); + // A `Dynamic` profile (a name or id only) resolves through the + // services when the skull is drawn. + let dynamic = crate::skins::dynamic_nbt(profile); // DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id. let fallback = crate::skins::profile_uuid_nbt(profile) + .or_else(|| { + crate::skins::nbt_text(profile.get("name")) + .map(|name| horizon_protocol::crypto::offline_uuid(&name)) + }) .map_or("entity/player/slim/steve", crate::tab_list::default_skin); - Self { download, fallback } + Self { + download, + dynamic, + fallback, + } } } /// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every @@ -366,6 +389,9 @@ impl BlockEntity { if is_skull(name) { return Some(Self::Skull(Skull::default())); } + if name == "minecraft:end_gateway" { + return Some(Self::EndGateway(EndGateway::default())); + } if name == "minecraft:daylight_detector" { return Some(Self::DaylightDetector); } @@ -418,6 +444,7 @@ impl BlockEntity { Self::Beehive(_) => "minecraft:beehive", Self::CommandBlock(_) => "minecraft:command_block", Self::Skull(_) => "minecraft:skull", + Self::EndGateway(_) => "minecraft:end_gateway", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", } @@ -436,6 +463,7 @@ impl BlockEntity { | Self::Vault(_) | Self::Beehive(_) | Self::CommandBlock(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => Vec::new(), Self::Lectern(l) => l.book.iter().cloned().collect(), @@ -456,6 +484,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, @@ -480,6 +509,7 @@ impl BlockEntity { | Self::Lectern(_) | Self::Sculk(_) | Self::Banner(_) + | Self::EndGateway(_) | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 16a7a273a..387de78b6 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -214,8 +214,9 @@ impl PlayerEffects { } /// `LivingEntity.tickEffects` (server part) with the omens' effect ticks: /// `omen` answers `BadOmenMobEffect` (every tick) and `RaidOmenMobEffect` - /// (on its last tick). Returns the actions to apply, in order, and - /// whether Raid Omen was newly added. + /// (on its last tick); `absorption_empty` is `AbsorptionMobEffect`'s + /// answer: the effect ends once the absorption is used up. Returns the + /// actions to apply, in order, and whether Raid Omen was newly added. /// /// Bad Omen turning into a new Raid Omen adds an entry to the map being /// iterated: vanilla's iterator then throws a @@ -225,6 +226,7 @@ impl PlayerEffects { pub fn tick_with( &mut self, omen: &mut dyn FnMut(&EffectInstance) -> OmenTick, + absorption_empty: bool, ) -> (Vec, bool) { self.tick_count = self.tick_count.wrapping_add(1); let mut actions = Vec::new(); @@ -247,6 +249,7 @@ impl PlayerEffects { let answer = match e.id { "bad_omen" => omen(e), "raid_omen" if t == 1 => omen(e), + "absorption" if absorption_empty => OmenTick::Remove, _ => OmenTick::Continue, }; match answer { @@ -466,13 +469,13 @@ mod tests { }; // The first tick adds Raid Omen and stops there (the iterator's // ConcurrentModificationException): Bad Omen and Speed stay as they were. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(added); assert_eq!(fx.get("bad_omen").unwrap().duration, 100); assert_eq!(fx.get("speed").unwrap().duration, 50); assert_eq!(fx.get("raid_omen").unwrap().duration, 600); // The second refreshes Raid Omen and drops Bad Omen. - let (_, added) = fx.tick_with(&mut convert); + let (_, added) = fx.tick_with(&mut convert, false); assert!(!added); assert!(fx.get("bad_omen").is_none()); assert_eq!(fx.get("speed").unwrap().duration, 49); @@ -487,9 +490,9 @@ mod tests { seen.push(e.duration); OmenTick::Remove }; - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_some()); - fx.tick_with(&mut watch); + fx.tick_with(&mut watch, false); assert!(fx.get("raid_omen").is_none()); assert_eq!(seen, vec![1]); } diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 2541a4b35..5c8bf689e 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -219,6 +219,13 @@ fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } +// rendertype_outline.fsh: the vertex colour (the team colour; outline vertices carry no +// normal, so no cardinal light) wherever the texture is not fully clear. +@fragment fn fs_outline(in: Out) -> @location(0) vec4 { + if textureSample(atlas, atlas_sampler, in.uv).a == 0.0 { discard; } + return vec4(in.color.rgb, 1.0); +} + fn celestial_color(in: Out) -> vec4 { return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; } @@ -237,6 +244,20 @@ fn celestial_color(in: Out) -> vec4 { return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b)))); } +// RenderPipelines.ENERGY_SWIRL (entity.fsh with EMISSIVE and NO_OVERLAY): the sprite, scrolled by +// the UV and repeated within itself, times the layer colour 0xFF808080, unlit; the pipeline adds +// it to the frame. The light bytes carry the sprite's origin and the colour bytes its size, both +// as breaking::stage_light packs them. +@fragment fn fs_energy_swirl(in: Out) -> @location(0) vec4 { + let bytes = round(in.color * 255.0); + let size = vec2(bytes.x + bytes.y * 256.0, bytes.z + bytes.w * 256.0) / 65535.0; + let color = textureSample(atlas, atlas_sampler, crumbling_uv(in.uv, in.wrap, size, textureDimensions(atlas))); + if color.a < 0.1 { discard; } + let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y), + linear_fog(in.cylindrical, globals.fog.z, globals.fog.w)); + return vec4(mix(color.rgb * (128.0 / 255.0), globals.fog_color.rgb, f * globals.fog_color.a), color.a); +} + // RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). @fragment fn fs_water_mask() -> @location(0) vec4 { return vec4(0.0); diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index b2d1401da..5c3d41ddc 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -577,6 +577,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.insert("anger".into(), Tag::compound(Vec::<(&str, Tag)>::new())); } } + // Armadillo.addAdditionalSaveData: the time left to the next scute. + "minecraft:armadillo" => { + map.insert("scute_time".into(), Tag::Int(m.extra.egg_time)); + } "minecraft:ravager" => { map.insert("AttackTick".into(), Tag::Int(m.extra.counter)); map.insert("StunTick".into(), Tag::Int(m.extra.counter2)); @@ -1198,6 +1202,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - st.vibration = crate::sculk::Data::from_nbt(listener); } } + // Armadillo.readAdditionalSaveData: keeps the constructor's time when absent. + if m.species() == crate::mobs::Species::Armadillo + && let Some(t) = number(tag.get("scute_time")) + { + m.extra.egg_time = t as i32; + } if m.species() == crate::mobs::Species::Ravager { m.extra.counter = number(tag.get("AttackTick")).unwrap_or(0) as i32; m.extra.counter2 = number(tag.get("StunTick")).unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index e900f2844..a381556ca 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -65,6 +65,7 @@ mod functions; mod game_mode; mod gamemode_switcher; mod ghasts; +mod glowing; mod golems; mod growth; mod hand; @@ -132,6 +133,7 @@ mod persist; mod perspective; mod pickups; mod piglins; +mod piston_push; mod player_equip; mod postprocess; mod potions; @@ -1388,6 +1390,8 @@ struct Game<'a> { /// Runs of `entity_vertices` by entity, for a shader pack's per-entity draws; recorded only /// while `pack_ids` is set (game/shader_packs.rs). entity_spans: std::cell::RefCell>, + /// The glowing entities' silhouettes this frame (game/glowing.rs). + glowing_vertices: std::cell::RefCell>, /// The shader pack's entity and block entity ids, while one draws entities. pack_ids: Option, started: Instant, @@ -1607,10 +1611,19 @@ struct Game<'a> { /// Map textures waiting for the next HUD batch to upload them. map_patches: Vec, text_displays: std::collections::HashMap, + /// The fence knots a server tracks to this client, by entity id, at their + /// block (`LeashFenceKnotEntity`). + remote_knots: HashMap, + /// The entity ids a hosted server gives the knots its mobs hang on, by + /// block, while a lead is tied there. + knot_ids: HashMap<[i32; 3], u32>, text_display_vertices: usize, /// Player skin downloads, and which skin each atlas skin slot holds /// (least recently shown first). skin_downloads: RefCell, + /// `ProfileResolver.Cached`: `Dynamic` profiles (name- or id-only heads + /// and mannequins) resolve through the services in the background. + skin_profiles: RefCell, skin_slots: Vec<(String, usize)>, /// Atlas trim slots in use: (sprite name, slot), least recently drawn first. trim_slots: Vec<(String, usize)>, @@ -2512,6 +2525,15 @@ impl Game<'_> { no_physics, &self.res.motion().fluids, ); + // Entity.applyEffectsFromBlocks: bubble columns lift or drag the item. + horizon_client::motion::bubble_column_push( + &self.world, + self.pack.assets.registry, + self.res.facts(), + self.collision, + item.bounds(), + &mut item.velocity, + ); cells.moved(i, item.previous, item.position); // ItemEntity.tick: merge every 2 ticks while moving between // blocks, every 40 otherwise, before the lifetime check. @@ -2782,9 +2804,13 @@ impl Game<'_> { self.process_level_events() } fn attack_block(&mut self, pos: [i32; 3]) -> Result<()> { - self.with_level(|b, level, ticks| { - b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])); + let note = self.with_level(|b, level, ticks| { + b.attack_block(level, ticks, BlockPos::new(pos[0], pos[1], pos[2])) }); + // NoteBlock.attack awards the statistic. + if note { + self.stats.custom("play_noteblock", 1); + } self.process_level_events() } /// Track which chunks are ticking (Ticks needs chunk load/unload). @@ -2980,20 +3006,29 @@ impl Game<'_> { b.run_block_events(level, ticks); b.tick_block_entities(level, ticks); }); + // `PistonMovingBlockEntity.tick` pushes what its block just ran into, + // with the progress it is about to take. + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); + self.process_level_events()?; self.sync_moving_pistons(); - self.process_level_events() + Ok(()) } /// Copies the moving-piston block entities into the world, where the /// collision queries and the renderer read them. fn sync_moving_pistons(&mut self) { - let pistons = &mut self.world.moving_pistons; - pistons.clear(); - pistons.extend( - self.block_ticks - .moving_pistons - .iter() - .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())), - ); + let previous = std::mem::take(&mut self.world.moving_pistons); + let current: Vec<_> = self + .block_ticks + .moving_pistons + .iter() + .map(|(p, piston)| ([p.x, p.y, p.z], piston.shape_state())) + .collect(); + self.world.moving_piston_fallback = previous + .into_iter() + .filter(|(pos, _)| !current.iter().any(|(next, _)| next == pos)) + .collect(); + self.world.moving_pistons = current; } /// `ServerLevel.tick`'s scheduled block then fluid ticks, one at a time: /// the side effects of each (a shrieker summoning a warden, drops, game @@ -3298,6 +3333,8 @@ impl Game<'_> { // Popped as the behaviour emits it (GameLevel::emit). PlayerEffect::DropItem(_) => {} PlayerEffect::EatCake => { + // CakeBlock.eat + self.stats.custom("eat_cake_slice", 1); if let Some(p) = self.player.as_mut() { let food = &mut p.health.food; food.food = (food.food + 2).min(20); @@ -3441,6 +3478,8 @@ impl Game<'_> { self.craft_table = Some(pos); } else if &*name == "minecraft:ender_chest" { self.open_ender_chest(key); + // EnderChestBlock.useWithoutItem + self.stats.custom("open_enderchest", 1); self.container_opener_event(key, true); let at = [ f64::from(key.0) + 0.5, @@ -3992,6 +4031,10 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if self.use_beehive(hit.pos, held.as_ref())? { + self.swing_arm(); + return Ok(true); + } if self.use_campfire_douse(hit.pos, held.as_ref())? { self.swing_arm(); return Ok(true); @@ -4031,6 +4074,20 @@ impl Game<'_> { ) }); self.process_level_events()?; + // NoteBlock.useWithoutItem (tuned) and BellBlock.onHit (rung). + if result == horizon_world::level::InteractionResult::Success { + let name = self + .res + .facts() + .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) + .name + .clone(); + match &*name { + "minecraft:note_block" => self.stats.custom("tune_noteblock", 1), + "minecraft:bell" => self.stats.custom("bell_ring", 1), + _ => {} + } + } if result.consumes_action() { self.swing_arm(); return Ok(true); @@ -5826,6 +5883,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), @@ -6098,6 +6156,7 @@ impl Game<'_> { | BlockEntity::Vault(_) | BlockEntity::Beehive(_) | BlockEntity::CommandBlock(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector | BlockEntity::Campfire(_), @@ -8244,6 +8303,15 @@ impl Game<'_> { None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic), }; let landed = self.hurt_by_player(index, amount, source); + if landed { + let victim = self.mob_entity(&self.mobs[index]); + self.player_hit( + &victim, + creatures::damage_type(source.kind, true), + None, + amount, + ); + } if let Some(p) = self.player.as_mut() { if p.attack_log.len() >= 64 { p.attack_log.remove(0); @@ -9202,6 +9270,9 @@ impl Game<'_> { if result.outcome == Outcome::Pass { return Ok(false); } + if let Some(stat) = result.stat { + self.stats.custom(stat, 1); + } if let Some(block) = result.block && let Ok(new) = registry.resolve(&block) { @@ -9311,6 +9382,8 @@ impl Game<'_> { else { return Ok(false); }; + // BlockTransformer.transformBlock: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", pos, stack); self.level_set(pos, new)?; // BlockTransformer.TransformParticle.send. self.transform_particle(&particle, pos); @@ -9583,6 +9656,8 @@ impl Game<'_> { if let Some(waxed) = old.and_then(|old| self.res.transformers().waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) { + // HoneycombItem.useOn: ITEM_USED_ON_BLOCK before the swap. + self.trigger_block("minecraft:item_used_on_block", hit.pos, stack); self.level_set(hit.pos, state)?; self.level_event_at(3003, hit.pos, 0); self.audio.play( @@ -11224,6 +11299,7 @@ impl Game<'_> { let mut entities = std::mem::take(&mut self.entity_vertices); entities.clear(); self.see_through_vertices.clear(); + self.glowing_vertices.get_mut().clear(); if !title { entities = horizon_client::spans::time("entity_geometry", || { self.entity_geometry(camera, alpha, entities) @@ -11291,6 +11367,7 @@ impl Game<'_> { // map_patches any earlier leaves them a frame behind. hud.patches.append(&mut self.map_patches); let entity_spans = std::mem::take(self.entity_spans.get_mut()); + let glowing = std::mem::take(self.glowing_vertices.get_mut()); let frame = Frame { weather: &weather, weather_time: horizon_client::weather::Time::new(self.world.game_time, alpha as f32), @@ -11357,6 +11434,7 @@ impl Game<'_> { }), entities: &entities, entity_spans: &entity_spans, + glowing: &glowing, dynamic_lights: &self.dynamic_lights, lightning: horizon_client::gfx::lightning::Input { bolts: &bolts, @@ -11412,6 +11490,7 @@ impl Game<'_> { // Restore storage even when rendering fails (for example, a lost surface). self.entity_vertices = entities; *self.entity_spans.get_mut() = entity_spans; + *self.glowing_vertices.get_mut() = glowing; self.see_through_vertices = see_through; result } @@ -13127,6 +13206,7 @@ impl<'a> Game<'a> { luminance: None, see_through_vertices: Vec::new(), entity_spans: Default::default(), + glowing_vertices: Default::default(), pack_ids: None, health_hud: hud_layout::HealthHud::default(), started: now, @@ -13272,12 +13352,15 @@ impl<'a> Game<'a> { dragon_model: prepared.dragon_model, map_patches: Vec::new(), text_displays: Default::default(), + remote_knots: Default::default(), + knot_ids: Default::default(), text_display_vertices: 0, skin_downloads: RefCell::new(horizon_client::skins::Downloader::new( std::env::current_dir() .unwrap_or_default() .join("assets/skins"), )), + skin_profiles: RefCell::new(horizon_client::skins::Resolver::new()), skin_slots: Vec::new(), trim_slots: Vec::new(), cart_models: prepared.cart_models, @@ -14121,6 +14204,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { nether_lighting: false, entities: &[], entity_spans: &[], + glowing: &[], dynamic_lights: &[], clouds: None, lightning: Default::default(), diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index f7bafd767..0f95389f2 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -180,6 +180,14 @@ impl adv::World for View<'_, '_> { "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), "entity_type" => self.0.res.mob_data().entity_has(tag, id), "worldgen/biome" => self.0.res.mob_data().biome_has(tag, id), + "damage_type" => self + .0 + .res + .stations() + .enchantments + .damage_tags + .get(tag) + .is_some_and(|t| t.contains(id)), _ => false, } } @@ -681,6 +689,69 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w) }); } + /// `PlayerHurtEntityTrigger`: the player, the damage and the victim. + pub(super) fn trigger_player_hurt_entity( + &mut self, + victim: &EntityView, + damage: &adv::DamageView, + ) { + let me = self.player_entity(); + let (victim, damage) = (victim.clone(), damage.clone()); + self.trigger("minecraft:player_hurt_entity", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + let vctx = adv::Entities { + this: Some(&victim), + ..pctx + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + && adv::conditions(&c["entity"], &vctx, w) + }); + } + /// The player's hit on `victim` as `LivingEntity.hurtServer` reports it: + /// `kind` damage of `amount` from `direct` (the player's own hand when + /// `None`), nothing blocked. + pub(super) fn player_hit( + &mut self, + victim: &EntityView, + kind: &str, + direct: Option, + amount: f32, + ) { + let me = self.player_entity(); + self.trigger_player_hurt_entity( + victim, + &adv::DamageView { + kind: kind.to_owned(), + is_direct: direct.is_none(), + direct: direct.or_else(|| Some(me.clone())), + source: Some(me), + original: amount, + actual: amount, + blocked: false, + }, + ); + } + /// `EntityHurtPlayerTrigger`: the player and the damage it took. + pub(super) fn trigger_entity_hurt_player(&mut self, damage: &adv::DamageView) { + let me = self.player_entity(); + let damage = damage.clone(); + self.trigger("minecraft:entity_hurt_player", move |c, w| { + let pctx = adv::Entities { + this: Some(&me), + origin: me.position, + tool: None, + block_pos: None, + }; + adv::conditions(&c["player"], &pctx, w) + && adv::damage(&c["damage"], &damage, w, me.position) + }); + } /// A player condition plus one item (`item` key). pub(super) fn trigger_item(&mut self, name: &str, stack: &ItemStack) { let me = self.player_entity(); diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index dba4edfad..ce9410ba5 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -161,7 +161,7 @@ impl Game<'_> { } // Allay.duplicateAllay: entity event 18, three spawnHeartParticle. let id = self.mobs[index].id; - self.particles_around_mob(id, "heart", horizon_client::particles::Burst::ALLAY); + self.mob_event_particles(id, 18); self.audio .play("minecraft:block.amethyst_block.chime", Some(at), 2.0, 1.0); self.consume_held(); diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index b7f7efb1a..e17a8f6a3 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -3,8 +3,10 @@ //! player breaks the hive or fire reaches it. use super::Game; use horizon_client::{ + Result, beehive::{self, Beehive, HiveHost, Release}, containers::BlockEntity, + items::ItemStack, mobs::{Mob, Who, bee}, }; use horizon_core::{ @@ -194,19 +196,139 @@ impl Game<'_> { } self.anger_nearby_bees(at); } + /// `BeehiveBlock.useItemOn` with `held` in the acting hand: shears take + /// the honeycombs and a glass bottle a honey bottle from a full hive + /// (honey level 5), then the honey level resets and, unless a campfire + /// smokes the hive, the bees come out angry. True when it took the click. + pub(super) fn use_beehive(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> Result { + let Some(held) = held else { return Ok(false) }; + let shears = &*held.item == "minecraft:shears"; + if !shears && &*held.item != "minecraft:glass_bottle" { + return Ok(false); + } + let state = self.world.block(pos[0], pos[1], pos[2]); + if !matches!( + &*self.res.facts().get(state).name, + "minecraft:beehive" | "minecraft:bee_nest" + ) { + return Ok(false); + } + let prop = |key: &str| { + self.pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get(key).cloned()) + }; + if prop("honey_level").and_then(|v| v.parse::().ok()) != Some(5) { + return Ok(false); + } + let facing = beehive::facing_step(prop("facing").as_deref()); + let at = self + .player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]); + if shears { + // dropHoneycomb (harvest/beehive), the shear sound, hurtAndBreak. + for stack in self.sequence_loot( + "minecraft:harvest/beehive", + "minecraft:harvest/beehive", + Some(held), + ) { + self.pop_resource(pos, stack); + } + self.audio + .play("minecraft:block.beehive.shear", at, 1.0, 1.0); + self.damage_held(1); + self.post_block_game_event("minecraft:shear", pos, self.sculk_actor(), None); + } else { + // shrink(1), then the honey bottle in the hand, the inventory or + // on the ground. + self.audio.play("minecraft:item.bottle.fill", at, 1.0, 1.0); + let cell = self.held_mut(); + if let Some(s) = cell.as_mut() { + s.count -= 1; + if s.count == 0 { + *cell = None; + } + } + let bottle = ItemStack::new("minecraft:honey_bottle", 1); + if self.held().is_none() { + *self.held_mut() = Some(bottle); + } else if let Some(rest) = self.give(bottle) + && let Some(eye) = self.eye_position() + { + self.spawn_item(rest, eye, [0.0, 0.1, 0.0], 40); + } + self.post_block_game_event("minecraft:fluid_pickup", pos, self.sculk_actor(), None); + } + self.stats.add("used", &held.item, 1); + let smokey = beehive::smokey(&self.mob_world_base(&[]), pos); + let key = (pos[0], pos[1], pos[2]); + if !smokey + && matches!(self.world.block_entities.get(&key), Some(BlockEntity::Beehive(h)) if !h.bees.is_empty()) + { + self.anger_nearby_bees(pos); + } + // resetHoneyLevel. + if let Some(reset) = self.with_props(state, &[("honey_level", "0")]) { + self.level_set(pos, reset)?; + } + if !smokey + && let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) + { + // emptyAllLivingFromHive: the bees within 4 blocks of the player + // go for them. + let released = hive.release_all( + pos, + facing, + None, + Release::Emergency, + &mut GameHive { game: self }, + ); + self.world + .block_entities + .put(key, BlockEntity::Beehive(hive)); + if let Some(p) = self.player_view().map(|p| p.position) { + for m in self.mobs.iter_mut().filter(|m| released.contains(&m.id)) { + if m.distance_sqr(p) <= 16.0 { + m.ai.target = Some(Who::Player); + } + } + } + } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, held); + Ok(true) + } /// `BeehiveBlock.angerNearbyBees`: bees within 8 blocks (6 up and down) - /// without a target go for a player in the same box. - fn anger_nearby_bees(&mut self, at: [i32; 3]) { + /// without a target go for a random player in the same box, the window's + /// own or a guest (`None` is the window's player). + pub(super) fn anger_nearby_bees(&mut self, at: [i32; 3]) { let min = Vec3::new( f64::from(at[0]) - 8.0, f64::from(at[1]) - 6.0, f64::from(at[2]) - 8.0, ); let area = Aabb::new(min, Vec3::new(min.x + 17.0, min.y + 13.0, min.z + 17.0)); - if !self + let mut players: Vec> = Vec::new(); + if self .player_view() .is_some_and(|p| p.bounds.intersects(area)) { + players.push(None); + } + if let Some(host) = self.lan.as_ref() { + players.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .filter(|g| super::lan_mobs::guest_bounds(g).intersects(area)) + .map(|g| Some(g.conn)), + ); + } + if players.is_empty() { return; } let mut bees: Vec = (0..self.mobs.len()) @@ -219,9 +341,20 @@ impl Game<'_> { .collect(); bees.retain(|&i| self.mobs[i].ai.target.is_none()); for i in bees { - // Util.getRandom over the one player. - let _ = self.world.random.next_int_bound(1); + // Util.getRandom over the players. + let pick = self + .world + .random + .next_int_bound(players.len() as i32) + .unwrap_or(0) as usize; self.mobs[i].ai.target = Some(Who::Player); + // The player a mob sees is its guest binding, else the window's. + if let Some(host) = self.lan.as_mut() { + match players[pick] { + Some(conn) => host.mob_players.insert(self.mobs[i].id, conn), + None => host.mob_players.remove(&self.mobs[i].id), + }; + } } } } diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 7790a48f3..a710a273b 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -725,21 +725,38 @@ impl Game<'_> { /// the player head at `pos`. The skin download is started here; while it /// is in flight (or when it cannot be got) the profile's default skin /// stands in. A head with no profile answers None: `SKIN_BY_TYPE`. - pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> { + pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option { let Some(BlockEntity::Skull(skull)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) else { return None; }; let skin = skull.skin.as_ref()?; - if let Some((url, location)) = &skin.download { - self.skin_downloads - .borrow_mut() - .state(skins::Kind::Skin, url); - if self.gui.atlas.sprites.contains_key(location) { + // The texture a packed or resolved `textures` property fetches: the + // download of a static profile, or the one the services answer for a + // `Dynamic` (name- or id-only) profile. + let download = skin.download.clone().or_else(|| { + let key = skin.dynamic.as_ref()?; + let skins::Resolve::Done(Some(profile)) = self.skin_profiles.borrow_mut().state(key) + else { + return None; + }; + let (value, signature) = profile.textures()?; + let url = skins::unpack(&value, signature, &skins::TEXTURE_URIS).skin?; + let location = skins::skin_location(&skins::texture_hash(&url)?); + Some((url, location)) + }); + if let Some((url, location)) = download { + let mut downloads = self.skin_downloads.borrow_mut(); + if self.gui.atlas.sprites.contains_key(&location) { + let _ = downloads.state(skins::Kind::Skin, &url); return Some(location); } + // Its slot was evicted: offer the image again. + if downloads.state(skins::Kind::Skin, &url) == skins::Download::Ready { + downloads.again(&location); + } } - Some(skin.fallback) + Some(skin.fallback.to_owned()) } } diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index f69f1b695..184e97101 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -45,6 +45,10 @@ pub(super) struct CombatTracker { /// The mob exploding now (`ServerExplosion.source`): its team's friendly /// fire decides whom the blast may hurt. pub(super) explosion_source: Option, + /// The blast now going off comes from a primed TNT, creeper, wither + /// skull, wither or TNT minecart, the sources that empty a hive they + /// destroy (`BeehiveBlock.getDrops`). + pub(super) hive_emptying_blast: bool, /// Charged creepers whose blast just went off and that have not dropped /// a head yet (`Creeper.droppedSkulls`): they are gone from the mob list, /// but the mobs they killed still ask for their loot. @@ -131,6 +135,19 @@ impl Game<'_> { self.recheck_combat(); for e in events { let (name, amount) = match e { + // LivingEntity.getDamageAfterMagicAbsorb (Resistance) and + // Player.actuallyHurt (absorption hearts) and + // LivingEntity.hurtServer (the shield, only for an accepted + // hit), in tenths. + MotionEvent::Health(HealthEvent::Statistic { name, amount }) => { + match *name { + "resisted" => self.stats.custom("damage_resisted", *amount), + "absorbed" => self.stats.custom("damage_absorbed", *amount), + "blocked" => self.stats.custom("damage_blocked_by_shield", *amount), + _ => {} + } + continue; + } MotionEvent::Health(HealthEvent::RecordedDamage { source, amount }) => { let Some(d) = self.motion.health.damage.definition(*source) else { continue; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index d3c40c3eb..43cdfa51c 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -2049,8 +2049,7 @@ impl Game<'_> { return false; } self.world.block_entities.insert(key, new); - let state = self.world.block(pos[0], pos[1], pos[2]); - let _ = self.world.set(pos[0], pos[1], pos[2], state); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); true } /// RandomizableContainer.tryLoadLootTable for a tag a command gives a diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 1e1b3456d..20d63f3c8 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -199,6 +199,7 @@ impl Game<'_> { off_hand: None, head: self.armor[0].as_ref().map(|s| s.item.clone()), armor_cover: self.armor.iter().filter(|a| a.is_some()).count() as f32 / 4.0, + invisible: self.potions.effects.get("invisibility").is_some(), spectator: self.spectator(), gold_armor: self.wearing_gold(), hurt_by: self.player_hurt_by(), @@ -415,6 +416,7 @@ impl Game<'_> { world: &self.world, registry: self.pack.assets.registry, facts: self.res.facts(), + fluid_tables: &self.motion.fluids, movement: &self.motion.blocks, collision: self.collision, data: self.res.mob_data(), @@ -432,6 +434,7 @@ impl Game<'_> { block_tags: &self.res.items().block_tags, biomes: self.res.biomes(), mob_griefing: self.ui.rules.bool("mob_griefing"), + mob_drops: self.ui.rules.bool("mob_drops"), end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, @@ -965,6 +968,9 @@ impl Game<'_> { .map_or([0.0; 3], |m| [m.velocity.x, m.velocity.y, m.velocity.z]); self.drown_particles(at, v); } + MobEvent::EntityEvent { mob, event, at } => { + self.lan_entity_event(mob as i32, event, at) + } MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio @@ -1046,7 +1052,7 @@ impl Game<'_> { self.combat.charged_exploders.push(mob); } } - MobEvent::Explode(at, radius) => { + MobEvent::Explode(at, radius, species) => { // The exploding mob causes the damage (Creeper.explodeCreeper). let source_mob = self.combat.explosion_source.or_else(|| { self.mobs @@ -1062,7 +1068,14 @@ impl Game<'_> { self.note_attacker("minecraft:explosion", id); } self.combat.explosion_source = source_mob; - let result = self.explode(at, radius); + // Only a creeper or a wither empties the hives it blows up. + // The creeper is already gone from the list, so the event + // carries its kind. + let result = if matches!(species, Species::Creeper | Species::Wither) { + self.with_hive_emptying_blast(|g| g.explode(at, radius)) + } else { + self.explode(at, radius) + }; self.combat.explosion_source = None; result? } @@ -1303,12 +1316,17 @@ impl Game<'_> { } } MobEvent::AroundSelf { + mob, + event, kind, feet, width, height, burst, - } => self.particles_around(kind, feet, [width, height], burst), + } => { + self.lan_entity_event(mob as i32, event, feet); + self.particles_around(kind, feet, [width, height], burst) + } MobEvent::ParticleAt { kind, at, velocity } => { if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) { let options = horizon_client::particles::ParticleOptions::simple(ty); @@ -1419,6 +1437,22 @@ impl Game<'_> { m.ai.aggressive |= aggressive; } } + MobEvent::ShedScute { mob, at, pitch } => { + // The mob already checked `shouldDropLoot` (a baby, `mob_drops`). + let table = "minecraft:gameplay/armadillo_shed"; + let drops = self.sequence_loot(table, table, None); + for d in drops { + self.spawn_at_location(Vec3::new(at[0], at[1], at[2]), 0.0, d); + } + self.audio.play( + "minecraft:entity.armadillo.scute_drop", + Some(at), + 1.0, + pitch, + ); + let ctx = self.who_context(Some(Who::Mob(mob)), None); + self.post_game_event("minecraft:entity_place", at, ctx); + } MobEvent::GiftLoot { mob, table, at } => { // Turtle.ageBoundaryReached: only with mob loot on. if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops") @@ -1547,6 +1581,8 @@ impl Game<'_> { q.extra.in_love = 0; } let q = self.mobs.iter().find(|m| m.id == partner).cloned(); + // Animal.finalizeSpawnChildFromBreeding: entity event 18 for the parent. + self.mob_event_particles(parent, 18); // Sniffer.spawnChildFromBreeding: an egg instead of a baby. if p.species() == Species::Sniffer { self.lay_sniffer_egg(&p); @@ -1819,6 +1855,10 @@ impl Game<'_> { let (xd, zd) = from.map_or((0.0, 0.0), |from| { (from[0] - player.position.x, from[2] - player.position.z) }); + // dealDefaultKnockback's `indicateDamage`, unless blocked. + if o.blocked <= 0.0 { + player.health.indicate_damage(xd, zd, player.yaw); + } self.knock_back_player(f64::from(0.4_f32), xd, zd); if let Some(p) = self.player.as_mut() && let Some(r) = p.hurt_log.last_mut() @@ -1831,6 +1871,23 @@ impl Game<'_> { self.thorns(a); } } + // LivingEntity.hurtServer: ENTITY_HURT_PLAYER, unless it returned + // early (invulnerable, or inside the hurt cooldown). + if outcome.hurt || outcome.sound { + let source = attacker + .or(owner) + .and_then(|id| self.mobs.iter().find(|m| m.id == id)) + .map(|m| self.mob_entity(m)); + self.trigger_entity_hurt_player(&horizon_client::advancements::DamageView { + kind: damage_type.to_owned(), + direct: source.clone().filter(|_| !projectile), + is_direct: !projectile, + source, + original: amount, + actual: amount - outcome.blocked, + blocked: outcome.blocked > 0.0, + }); + } if raised { self.after_block(outcome, amount, attacker, projectile); } @@ -2063,6 +2120,21 @@ impl Game<'_> { if super::remote_projectiles::has_smoke_trail(&p.kind) { trails.push(p.position); } + // ThrownEnderpearl.onAboveBubbleColumn / onInsideBubbleColumn. + if keep && hit == Hit::None && matches!(p.kind, ProjectileKind::EnderPearl) { + let (at, h) = (p.position, 0.125); + horizon_client::motion::bubble_column_push( + w.world, + w.registry, + w.facts, + w.collision, + Aabb::new( + Vec3::new(at.x - h, at.y, at.z - h), + Vec3::new(at.x + h, at.y + 2.0 * h, at.z + h), + ), + &mut p.velocity, + ); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -2488,6 +2560,24 @@ impl Game<'_> { .is_some_and(|m| m.damage(amount, source)); if p.owner == Some(Who::Player) { self.last_hurt_by_player.insert(id, self.lan_acting); + if hurt && let Some(m) = self.mobs.iter().find(|m| m.id == id) { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let spectral = p.arrow.as_ref().is_some_and(|a| { + &*a.pickup_item.item == "minecraft:spectral_arrow" + }); + let direct = horizon_client::advancements::EntityView { + kind: if spectral { + "minecraft:spectral_arrow" + } else { + "minecraft:arrow" + } + .into(), + position: [p.position.x, p.position.y, p.position.z], + ..Default::default() + }; + self.player_hit(&victim, "minecraft:arrow", Some(direct), amount); + } } hurt } @@ -2531,6 +2621,7 @@ impl Game<'_> { }; m.damage(amount, source); } + self.thrown_break_event(p.id, atp); self.item_burst(atp, "minecraft:snowball"); } (ProjectileKind::Egg, hit) => { @@ -2556,6 +2647,7 @@ impl Game<'_> { } } } + self.thrown_break_event(p.id, atp); self.item_burst(atp, "minecraft:egg"); } (ProjectileKind::EnderPearl, hit) => { @@ -2805,10 +2897,17 @@ impl Game<'_> { } Ok(()) } + /// `Snowball`/`ThrownEgg.onHit`: entity event 3 for the guests, before the + /// projectile is discarded (the clients lose it when the tracker next runs). + fn thrown_break_event(&mut self, id: u32, at: [f64; 3]) { + if id != 0 { + self.lan_entity_event(id as i32, 3, at); + } + } /// `Snowball`/`ThrownEgg.handleEntityEvent(3)`: eight crumbs of the /// thrown item where it broke, at rest for a snowball, scattered by the /// client entity's random (the particle engine's here) for an egg. - fn item_burst(&mut self, at: [f64; 3], item: &str) { + pub(super) fn item_burst(&mut self, at: [f64; 3], item: &str) { let options = self.item_particle(&horizon_client::items::ItemStack::new(item, 1)); let egg = item != "minecraft:snowball"; for _ in 0..8 { @@ -2844,6 +2943,10 @@ impl Game<'_> { if self.name_mob(index) { return Ok(true); } + if self.spawn_egg_offspring(index) { + self.swing_arm(); + return Ok(true); + } { let item = self.held().map(|h| h.item.to_string()).unwrap_or_default(); if self.interact_leash(index, &item) { @@ -3098,14 +3201,8 @@ impl Game<'_> { m.ai.target = None; m.extra.sitting = true; } - // TamableAnimal.spawnTamingParticles. - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -3172,13 +3269,8 @@ impl Game<'_> { m.extra.sitting = true; } eat = eating_sound(m, &mut self.world.random); - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -3226,13 +3318,8 @@ impl Game<'_> { m.extra.tame = true; m.extra.owner = self.level.player_uuid.or(Some([0, 0, 0, 1])); } - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); if tamed { let view = self.mob_entity(&self.mobs[index]); self.trigger_entity("minecraft:tame_animal", "entity", &view); @@ -3263,6 +3350,11 @@ impl Game<'_> { Some(sound) => { consume = true; eat = sound; + // Animal.setInLove: entity event 18 (a baby that + // only grew is not in love). + if self.mobs[index].extra.in_love > 0 { + self.mob_event_particles(self.mobs[index].id, 18); + } } // Animal.mobInteract still consumes the client click when // an adult cannot breed, without swinging or taking food. @@ -3459,6 +3551,45 @@ impl Game<'_> { } Ok(true) } + /// `Mob.checkAndHandleImportantInteractions` with a spawn egg of mob + /// `index`'s own kind (`SpawnEggItem.spawnOffspringFromSpawnEgg`): a baby + /// at the mob's feet, taking the parent's variant as `getBreedOffspring` + /// does, and one egg used. False (PASS) when the mob has no baby form. + fn spawn_egg_offspring(&mut self, index: usize) -> bool { + let Some(stack) = self.held().cloned() else { + return false; + }; + let parent = &self.mobs[index]; + if !parent.alive() + || stack.item.strip_suffix("_spawn_egg") != Some(parent.kind.id.as_str()) + || !horizon_client::mobs::drops::can_be_baby(parent.species()) + // WanderingTrader.getBreedOffspring returns null: no offspring, the + // click carries on to trading. + || parent.species() == Species::WanderingTrader + { + return false; + } + let (kind, at) = ( + parent.kind.id.clone(), + [parent.position.x, parent.position.y, parent.position.z], + ); + let (species, variant, color) = + (parent.species(), parent.extra.variant, parent.extra.color); + let target = self.mob_entity(&self.mobs[index]); + let Some(id) = self.spawn_mob(&kind, at, true) else { + return false; + }; + if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) { + horizon_client::mobs::finalize::set_baby(child, true); + child.extra.variant = variant; + if species == Species::Sheep { + child.extra.color = color; + } + } + self.trigger_item_entity("minecraft:player_interacted_with_entity", &stack, &target); + self.consume_held(); + true + } fn use_spawn_egg(&mut self, stack: &ItemStack) -> Result { let Some(hit) = self.pick() else { return Ok(false); @@ -3590,8 +3721,10 @@ impl Game<'_> { let scale = self.view_scale(); for mob in &self.mobs { let entity_start = out.len(); - // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. - if mob.invisible { + let outline = self.mob_outline(mob); + // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws (and + // the outline of a glowing mob, LivingEntityRenderer.getRenderType). + if mob.invisible && outline.is_none() { continue; } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; @@ -3660,9 +3793,18 @@ impl Game<'_> { out, ); self.mob_block_geometry(mob, camera, alpha, packed, out); + if let Some(rgb) = outline { + self.mark_outline(&out[entity_start..], rgb); + if mob.invisible { + out.truncate(entity_start); + continue; + } + } // Glowing outlines and a guardian's beam remain visible independently // of whether the body is hidden behind terrain. - if !mob.glowing && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() { + if outline.is_none() + && horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none() + { self.cull_entity_vertices(out, entity_start); } // GuardianRenderer: the laser to the locked target. @@ -3710,7 +3852,15 @@ impl Game<'_> { super::pickups::Taken::Arrow(a) => Some((&**a, super::pickups::position(p, alpha))), _ => None, }); + // A glowing projectile's outline: what it drew up to the next one. + let mut glowing = None; for (a, at) in live.chain(taken) { + if let Some((start, rgb)) = glowing.take() { + self.mark_outline(&out[start..], rgb); + } + if a.id != 0 && self.entity_glowing(a.id) { + glowing = Some((out.len(), super::glowing::team_color(self.mob_team(a.id)))); + } let p = glam::DVec3::from_array(at) - camera; let c = p.as_vec3(); let light = self.world.light( @@ -3842,6 +3992,9 @@ impl Game<'_> { }); } } + if let Some((start, rgb)) = glowing { + self.mark_outline(&out[start..], rgb); + } } } /// `Bucketable.getBucketItemStack` and `getPickupSound` of a mob that a water diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index bd324d437..da7e56ac4 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -27,6 +27,8 @@ 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; +/// `Mob.getAmbientSoundInterval`. +const AMBIENT_INTERVAL: i32 = 80; #[derive(Default)] pub(super) struct Fight { @@ -270,6 +272,8 @@ pub(super) struct Dragon { flame_count: i32, sitting_damage: f32, growl: i32, + /// `Mob.ambientSoundTime`. + ambient_time: i32, ticks: i32, /// DragonFlightHistory: (y, yRot) samples, newest at `head`. history: [(f64, f32); 64], @@ -397,6 +401,7 @@ impl Dragon { flame_count: 0, sitting_damage: 0.0, growl: 100, + ambient_time: 0, ticks: 0, history: [(position.y, yaw); 64], head: 0, @@ -989,6 +994,8 @@ impl Game<'_> { }; let hurt = d.hurt(part, damage, counts, arrow); if hurt == (Hurt::Landed { full: true }) { + // Mob.playHurtSound: the ambient sound clock starts again. + d.ambient_time = -AMBIENT_INTERVAL; let at = [d.position.x, d.position.y, d.position.z]; let pitch = 0.8 + self.world.random.next_float() * 0.3; self.audio @@ -1661,6 +1668,24 @@ impl Game<'_> { self.tick_dragon_death(); return; } + // Mob.baseTick: the ambient sound, rarer right after one. + let roll = d.random.next_int_bound(1000).unwrap_or(999); + let waited = d.ambient_time; + d.ambient_time += 1; + if roll < waited { + d.ambient_time = -AMBIENT_INTERVAL; + let at = [d.position.x, d.position.y, d.position.z]; + // LivingEntity.getVoicePitch, from the dragon's own random. + let r = &mut d.random; + let pitch = (r.next_float() - r.next_float()) * 0.2 + 1.0; + self.audio.play( + "minecraft:entity.ender_dragon.ambient", + Some(at), + 5.0, + pitch, + ); + } + let d = self.dragon.as_mut().expect("dragon"); // Flapping, growls and the flap sound. let flap_was = (d.old_flap * std::f32::consts::TAU).cos(); let v = d.velocity; @@ -2140,10 +2165,12 @@ impl Game<'_> { c.at[1], c.at[2] + f64::from(a.sin() * d), ]; - self.particles.add( + self.particles.add_with( &ParticleOptions::simple(ParticleType::DragonBreath), at, [0.0, 0.0, 0.0], + false, + true, ); } // AreaEffectCloud: after its 20-tick wait, every 20 ticks per entity. diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index bb0f3789d..68edeedbf 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -5,6 +5,7 @@ use super::{Dim, Game}; use horizon_client::{ Result, + containers::{BlockEntity, EndGateway}, environment::Environment, items::ItemStack, mesher::Vertex, @@ -27,14 +28,64 @@ const GATEWAY_Y: i32 = 75; const GATEWAY_FILE: &str = "horizon-end-gateways.json"; /// A gateway teleport waiting for its destination chunks. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) enum GatewayJob { /// TheEndGatewayBlockEntity.findOrCreateValidTeleportPos from this gateway. - Find { gateway: [i32; 3] }, + /// `exact` is the gateway's own `ExactTeleport`, read while its chunk is loaded. + Find { gateway: [i32; 3], exact: bool }, /// A known exit (exact, or findExitPosition around it). Known { exit: [i32; 3], exact: bool }, } +impl GatewayJob { + /// TheEndGatewayBlockEntity.getPortalPosition, with legacy save fallbacks. + fn for_gateway( + gateway: [i32; 3], + entity: Option<&BlockEntity>, + legacy: Option<([i32; 3], bool)>, + ) -> Self { + let configured = match entity { + Some(BlockEntity::EndGateway(g)) => g.exit_portal.map(|exit| (exit, g.exact_teleport)), + _ => None, + }; + match configured.or(legacy) { + Some((exit, exact)) => Self::Known { exit, exact }, + // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. + None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => Self::Known { + exit: END_SPAWN, + exact: true, + }, + None => Self::Find { + gateway, + exact: exact_teleport(entity), + }, + } + } +} + +/// `TheEndGatewayBlockEntity.exactTeleport` of the block entity at a gateway +/// (false without one). +fn exact_teleport(entity: Option<&BlockEntity>) -> bool { + matches!(entity, Some(BlockEntity::EndGateway(g)) if g.exact_teleport) +} + +/// Moves an exit that only the side file knew into the gateway's block entity, unless the block +/// entity has its own; true when it took the saved one. +fn adopt_saved_exit(entity: &mut EndGateway, (exit, exact): ([i32; 3], bool)) -> bool { + if entity.exit_portal.is_some() { + return false; + } + entity.exit_portal = Some(exit); + entity.exact_teleport = exact; + true +} + +/// The end of `getPortalPosition`: the exit itself when the teleport is exact, +/// else the spot [`Game::resolve_gateway`] finds around it (`findExitPosition`). +fn exit_target(exit: [i32; 3], exact: bool, find: impl FnOnce([i32; 3]) -> [i32; 3]) -> [i32; 3] { + if exact { exit } else { find(exit) } +} + #[derive(Default)] pub(super) struct EndState { /// Gateway position -> (exit, exact teleport); loaded lazily from the save. @@ -761,6 +812,11 @@ impl Game<'_> { } } } + self.world + .block_entities + .get_or_insert_with((origin[0], origin[1], origin[2]), || { + BlockEntity::EndGateway(Default::default()) + }); Ok(()) } @@ -782,8 +838,7 @@ impl Game<'_> { self.end.exits.as_mut().expect("loaded exits") } - fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { - self.gateway_exits().insert(gateway, (exit, exact)); + fn save_gateway_exits(&mut self) -> Result<()> { let list: Vec<_> = self .gateway_exits() .iter() @@ -795,6 +850,35 @@ impl Game<'_> { Ok(()) } + /// Drops a gateway's entry from the side file: its block entity is the source of truth. + fn forget_gateway_exit(&mut self, gateway: [i32; 3]) -> Result<()> { + if self.gateway_exits().remove(&gateway).is_some() { + self.save_gateway_exits()?; + } + Ok(()) + } + + fn set_gateway_exit(&mut self, gateway: [i32; 3], exit: [i32; 3], exact: bool) -> Result<()> { + // TheEndGatewayBlockEntity.setExitPosition (also EndGatewayFeature.knownExit). + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + // The gateway's chunk can be unloaded by now (travel waits for the destination): the + // exit then waits in the side file until the gateway is used again (`gateway_job`). + if self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + g.exit_portal = Some(exit); + g.exact_teleport = exact; + self.world.modified.insert(chunk); + return self.forget_gateway_exit(gateway); + } + self.gateway_exits().insert(gateway, (exit, exact)); + self.save_gateway_exits() + } + /// EndGatewayBlock.entityInside and TheEndGatewayBlockEntity.getPortalPosition: /// travel within the End, waiting for the destination chunks to load. fn enter_gateway(&mut self, gateway: [i32; 3]) -> Result<()> { @@ -814,25 +898,39 @@ impl Game<'_> { /// its exit, or the search for one, and the spot to load before either /// is resolved ([`Game::resolve_gateway`]). pub(super) fn gateway_job(&mut self, gateway: [i32; 3]) -> (GatewayJob, Vec3) { - let known = self.gateway_exits().get(&gateway).copied(); - let job = match known { - Some((exit, exact)) => GatewayJob::Known { exit, exact }, - // Worldgen return gateways (end_gateway_return) lead exactly to the End spawn. - None if f64::from(gateway[0]).hypot(f64::from(gateway[2])) > 512.0 => { - GatewayJob::Known { - exit: END_SPAWN, - exact: true, - } + let mut known = self.gateway_exits().get(&gateway).copied(); + // Once the gateway's chunk is loaded its block entity is the source of truth: an exit the + // side file kept for it moves there, and the entry is dropped, so removing or replacing + // the exit (`/data remove block`) is not undone by an old entry. + let key = (gateway[0], gateway[1], gateway[2]); + let chunk = (gateway[0] >> 4, gateway[2] >> 4); + if let Some(saved) = known + && self.world.chunks.contains_key(&chunk) + && let BlockEntity::EndGateway(g) = self + .world + .block_entities + .get_or_insert_with(key, || BlockEntity::EndGateway(Default::default())) + { + if adopt_saved_exit(g, saved) { + self.world.modified.insert(chunk); } - None => GatewayJob::Find { gateway }, - }; + known = None; + let _ = self.forget_gateway_exit(gateway); + } + let job = GatewayJob::for_gateway( + gateway, + self.world + .block_entities + .get(&(gateway[0], gateway[1], gateway[2])), + known, + ); let destination = match job { GatewayJob::Known { exit, .. } => Vec3::new( f64::from(exit[0]) + 0.5, f64::from(exit[1]), f64::from(exit[2]) + 0.5, ), - GatewayJob::Find { gateway } => { + GatewayJob::Find { gateway, .. } => { let d = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero() * 1024.0; @@ -889,12 +987,10 @@ impl Game<'_> { [p[0], p[1] + 1, p[2]] }; match job { - GatewayJob::Known { exit, exact } => Ok(bottom_center(if exact { - exit - } else { - find_exit(self, exit) - })), - GatewayJob::Find { gateway } => { + GatewayJob::Known { exit, exact } => Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))), + GatewayJob::Find { gateway, exact } => { // findExitPortalXZPosTentative over the loaded chunks. let dir = glam::DVec2::new(f64::from(gateway[0]), f64::from(gateway[2])) .normalize_or_zero(); @@ -954,8 +1050,11 @@ impl Game<'_> { let exit = [tallest[0], tallest[1] + 10, tallest[2]]; self.place_gateway(exit)?; self.set_gateway_exit(exit, gateway, false)?; - self.set_gateway_exit(gateway, exit, false)?; - Ok(bottom_center(find_exit(self, exit))) + // setExitPosition keeps the gateway's own exactTeleport. + self.set_gateway_exit(gateway, exit, exact)?; + Ok(bottom_center(exit_target(exit, exact, |e| { + find_exit(self, e) + }))) } } } @@ -1252,3 +1351,96 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::containers::EndGateway; + + #[test] + fn a_saved_exit_moves_into_a_gateway_without_one() { + let saved = ([8, 100, 0], true); + let mut bare = EndGateway::default(); + assert!(adopt_saved_exit(&mut bare, saved)); + assert_eq!(bare.exit_portal, Some([8, 100, 0])); + assert!(bare.exact_teleport); + // The block entity's own exit wins over a stale entry. + let mut own = EndGateway { + exit_portal: Some([1, 2, 3]), + ..Default::default() + }; + assert!(!adopt_saved_exit(&mut own, saved)); + assert_eq!(own.exit_portal, Some([1, 2, 3])); + assert!(!own.exact_teleport); + } + + #[test] + fn a_new_exit_keeps_the_gateways_exact_teleport() { + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + let plain = BlockEntity::EndGateway(EndGateway::default()); + assert!(exact_teleport(Some(&exact))); + assert!(!exact_teleport(Some(&plain))); + assert!(!exact_teleport(None)); + assert!(!exact_teleport(Some(&BlockEntity::DaylightDetector))); + let exit = [8, 100, 0]; + // Exact: the exit itself, nothing is searched for. + assert_eq!(exit_target(exit, true, |_| panic!("searched")), exit); + assert_eq!( + exit_target(exit, false, |e| [e[0], e[1] + 11, e[2]]), + [8, 111, 0] + ); + } + + #[test] + fn end_gateway_job_prefers_block_entity_then_legacy_then_heuristic() { + let gateway = [702, 100, 0]; + let exit = [8, 100, 0]; + for exact in [true, false] { + let entity = BlockEntity::EndGateway(EndGateway { + exit_portal: Some(exit), + exact_teleport: exact, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(gateway, Some(&entity), Some((END_SPAWN, !exact))), + GatewayJob::Known { exit, exact }, + ); + } + let empty = BlockEntity::EndGateway(EndGateway::default()); + for entity in [None, Some(&empty)] { + assert_eq!( + GatewayJob::for_gateway(gateway, entity, Some((exit, false))), + GatewayJob::Known { exit, exact: false } + ); + assert_eq!( + GatewayJob::for_gateway(gateway, entity, None), + GatewayJob::Known { + exit: END_SPAWN, + exact: true + } + ); + let nearby = [96, 75, 0]; + let exact = BlockEntity::EndGateway(EndGateway { + exact_teleport: true, + ..Default::default() + }); + assert_eq!( + GatewayJob::for_gateway(nearby, Some(&exact), None), + GatewayJob::Find { + gateway: nearby, + exact: true + } + ); + assert_eq!( + GatewayJob::for_gateway(nearby, entity, None), + GatewayJob::Find { + gateway: nearby, + exact: false + } + ); + } + } +} diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index b2191aa9f..79e68c8e4 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -307,6 +307,12 @@ impl Game<'_> { ) { outcome = o; + // dealDefaultKnockback's `indicateDamage` points at the blast + // (the source position), not the no-direction fallback. + if o.knockback && o.blocked <= 0.0 { + p.health + .indicate_damage(center[0] - feet[0], center[2] - feet[2], p.yaw); + } } if !spectator && !(creative && flying) { p.velocity = Vec3::new( @@ -490,6 +496,15 @@ impl Game<'_> { ); } } + /// Runs an explosion whose source empties the hives it destroys + /// (`BeehiveBlock.getDrops`: primed TNT, creeper, wither skull, wither, + /// TNT minecart). + pub(super) fn with_hive_emptying_blast(&mut self, blast: impl FnOnce(&mut Self) -> R) -> R { + self.combat.hive_emptying_blast = true; + let result = blast(self); + self.combat.hive_emptying_blast = false; + result + } /// `Level.explode` on the server: positions, entities, blocks, fire; then /// the client's explosion sound. pub(super) fn server_explode( @@ -606,6 +621,22 @@ impl Game<'_> { // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. let key = (pos[0], pos[1], pos[2]); + let is_hive = matches!(&*name, "minecraft:beehive" | "minecraft:bee_nest"); + // BeehiveBlock.getDrops: the bees of a hive blown up by TNT, a + // creeper, a wither skull, a wither or a TNT minecart come out. + if is_hive && self.combat.hive_emptying_blast { + let facing = self + .pack + .assets + .registry + .state(state) + .and_then(|s| s.properties.get("facing").cloned()); + self.empty_hive( + pos, + horizon_client::beehive::facing_step(facing.as_deref()), + horizon_client::beehive::Release::Emergency, + ); + } if let Some(entity) = self.world.block_entities.get(&key).cloned() { let custom = self.world.block_names.get(&key).cloned(); self.pending.record(pos, &entity, &name, custom); @@ -638,6 +669,10 @@ impl Game<'_> { } self.pending.clear(pos); self.level_set(pos, self.world.air)?; + // BeehiveBlock.onExplosionHit: the bees about turn on the player. + if is_hive { + self.anger_nearby_bees(pos); + } // TntBlock.wasExploded: new PrimedTnt (its push drawn first), then // getRandomShortFuse(80); no game event. if is_tnt && self.ui.rules.bool("tnt_explodes") { diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 5aa540fcd..f66fd4d3a 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -62,11 +62,56 @@ impl Rocket { item, } } - /// One tick of a server's client: the previous position, then `step`. - pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + /// One tick of a server's client: the rocket flies on by itself between + /// the server's updates (a rocket that follows an entity is placed by the + /// caller). + pub(super) fn remote_step(&mut self, scene: &mut SceneCollisions) { self.previous = self.position; + if self.attached_to.is_none() { + self.free_flight(scene); + } self.life += 1; - self.position = step(self.position); + } + /// `FireworkRocketEntity.tick` for a rocket attached to no entity: speed + /// up (an angled one keeps its motion) and rise, then move. True when a + /// block stopped it. + fn free_flight(&mut self, scene: &mut SceneCollisions) -> bool { + let h = 0.125; + let bounds = Aabb::new( + Vec3::new(self.position.x - h, self.position.y, self.position.z - h), + Vec3::new( + self.position.x + h, + self.position.y + 2.0 * h, + self.position.z + h, + ), + ); + let wanted = if self.angled { + self.velocity + } else { + Vec3::new( + self.velocity.x * 1.15, + self.velocity.y + 0.04, + self.velocity.z * 1.15, + ) + }; + let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) else { + return false; + }; + let blocked = (moved.x - wanted.x).abs() > 1e-7 + || (moved.y - wanted.y).abs() > 1e-7 + || (moved.z - wanted.z).abs() > 1e-7; + let horizontal = (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; + self.position = Vec3::new( + self.position.x + moved.x, + self.position.y + moved.y, + self.position.z + moved.z, + ); + self.velocity = if horizontal { + Vec3::new(self.velocity.x, wanted.y, self.velocity.z) + } else { + wanted + }; + blocked } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { @@ -191,46 +236,14 @@ impl Game<'_> { r.velocity = p.velocity; } } else { - // Not shot at an angle: accelerate (unless blocked sideways) and rise. let mut scene = SceneCollisions { world: &self.world, binding: self.collision, subject: None, }; - let h = 0.125; - let bounds = Aabb::new( - Vec3::new(r.position.x - h, r.position.y, r.position.z - h), - Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h), - ); - let wanted = if r.angled { - r.velocity - } else { - Vec3::new( - r.velocity.x * 1.15, - r.velocity.y + 0.04, - r.velocity.z * 1.15, - ) - }; - if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) { - let blocked = (moved.x - wanted.x).abs() > 1e-7 - || (moved.y - wanted.y).abs() > 1e-7 - || (moved.z - wanted.z).abs() > 1e-7; - if r.angled && blocked { - // hitTargetOrDeflectSelf: explode on the block. - r.life = r.lifetime; - } - let horizontal = - (moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7; - r.position = Vec3::new( - r.position.x + moved.x, - r.position.y + moved.y, - r.position.z + moved.z, - ); - r.velocity = if horizontal { - Vec3::new(r.velocity.x, wanted.y, r.velocity.z) - } else { - wanted - }; + if r.free_flight(&mut scene) && r.angled { + // hitTargetOrDeflectSelf: explode on the block. + r.life = r.lifetime; } } let at = [r.position.x, r.position.y, r.position.z]; @@ -383,7 +396,12 @@ impl Game<'_> { /// lit at the rocket's light probe. pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let orientation = glam::Mat4::from_quat(self.camera_orientation()); - for r in self.rockets.iter().filter(|r| !r.attached) { + // shouldRender: not while attached to an entity (`isAttachedToEntity`). + for r in self + .rockets + .iter() + .filter(|r| !r.attached && r.attached_to.is_none()) + { // FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks; // EntityRenderer.shouldRender: its 0.25 box in the view. if !self.standing_entity_in_view( diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 95e2e1e6e..364f89189 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -114,7 +114,7 @@ impl Game<'_> { living: Some(HurtBob { hurt_time: p.health.hurt_animation_time as f32 - partial, hurt_duration: hurt.hurt_duration, - hurt_dir: 0.0, + hurt_dir: p.health.hurt_dir, death_time: self.death_time().map(|t| t as f32 + partial), }), player: Some(( diff --git a/crates/horizon-client/src/game/glowing.rs b/crates/horizon-client/src/game/glowing.rs new file mode 100644 index 000000000..8c78dbd77 --- /dev/null +++ b/crates/horizon-client/src/game/glowing.rs @@ -0,0 +1,53 @@ +//! Glowing entities (`EntityRenderer.extractRenderState`'s outlineColor): which entities +//! appear glowing, in which team colour, and their silhouettes for the renderer's entity +//! outline (`OutlineBufferSource`). +use super::{Game, Vertex}; +use horizon_client::{mobs::Mob, scoreboard as sb}; + +/// `Entity.getTeamColor`: the team's colour, else white. +pub(super) fn team_color(team: Option<&sb::Team>) -> u32 { + team.and_then(|t| t.color.as_deref()) + .and_then(sb::team_color_rgb) + .unwrap_or(0xFF_FFFF) +} + +impl Game<'_> { + /// `Entity.isCurrentlyGlowing` of an entity that is not living (an item, a projectile): + /// its `Glowing` tag, or shared flag 6 as a server sent it. + pub(super) fn entity_glowing(&self, id: u32) -> bool { + self.remote_glowing(id).unwrap_or_else(|| { + self.persist_raw(id) + .and_then(|t| horizon_client::save::number(t.get("Glowing"))) + .is_some_and(|b| b != 0) + }) + } + + /// `Minecraft.shouldEntityAppearGlowing` of a mob or another player, with its outline + /// colour (`getTeamColor`; another player's team goes by name). + pub(super) fn mob_outline(&self, m: &Mob) -> Option { + if !m.is_currently_glowing() { + return None; + } + let team = if &*m.kind.id == "minecraft:player" { + let names = self.remote_player_names(); + let name = names.into_iter().find(|(id, _)| *id == m.id); + name.and_then(|(_, name)| self.score.board.players_team(&name)) + } else { + self.mob_team(m.id) + }; + Some(team_color(team)) + } + + /// Adds one glowing entity's geometry to the outline pass in `rgb`, the textures' + /// alpha kept (`OutlineBufferSource`'s team-coloured copy of each draw). + pub(super) fn mark_outline(&self, vertices: &[Vertex], rgb: u32) { + let color = horizon_client::mobs::render::abgr(rgb); + self.glowing_vertices + .borrow_mut() + .extend(vertices.iter().map(|v| Vertex { + color, + normal: [0; 4], + ..*v + })); + } +} diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 7d81c971d..df40ff377 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -420,6 +420,8 @@ impl Game<'_> { s.flags.published.store(0, Ordering::Relaxed); } if let Some(mut host) = self.lan.take() { + // PlayerList.removeAll: the owner and every guest leave the game. + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b6b7e2fb7..f6edd746e 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -129,6 +129,7 @@ pub(super) struct Host<'a> { banners: &'a horizon_client::banner::Banners, sprites: &'a HashMap, skins: &'a RefCell, + profiles: &'a RefCell, } impl SpecialHost for Host<'_> { fn banner_texture(&self, pattern: &str) -> Option { @@ -144,14 +145,14 @@ impl SpecialHost for Host<'_> { fn player_skin(&self, profile: &Value) -> Option { // SkullBlockRenderer.getPlayerSkin: SkinManager.getInsecureSkinInformation // accepts a texture property without a signature, unlike the tab list. - let url = horizon_client::skins::profile_skin_url(profile)?; - let location = - horizon_client::skins::skin_location(&horizon_client::skins::texture_hash(&url)?); - let _ = self - .skins - .borrow_mut() - .state(horizon_client::skins::Kind::Skin, &url); - self.sprites.contains_key(&location).then_some(location) + // A `Dynamic` profile (a name or id only) resolves through the + // services (`PlayerSkinRenderCache.getOrDefault`). + Some(horizon_client::skins::head_skin( + profile, + &mut self.profiles.borrow_mut(), + &mut self.skins.borrow_mut(), + |location| self.sprites.contains_key(location), + )) } } @@ -194,6 +195,7 @@ impl Game<'_> { banners: &self.res.stations().banners, sprites: &self.gui.atlas.sprites, skins: &self.skin_downloads, + profiles: &self.skin_profiles, } } /// The client level as item models read it: worked out once a frame (a @@ -405,7 +407,12 @@ impl Game<'_> { ) { self.submit_item_world(&state, copy, vertex_light(packed), out); } - self.cull_entity_vertices(out, entity_start); + if self.entity_glowing(item.id) { + let rgb = super::glowing::team_color(self.mob_team(item.id)); + self.mark_outline(&out[entity_start..], rgb); + } else { + self.cull_entity_vertices(out, entity_start); + } } } } diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index c3ed75ebb..87f91895e 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -79,6 +79,7 @@ impl Game<'_> { if !self.creative { self.consume_held(); } + self.stats.custom("play_record", 1); self.world.block_entities.insert( (pos[0], pos[1], pos[2]), BlockEntity::Jukebox(Jukebox { @@ -90,6 +91,8 @@ impl Game<'_> { self.set_has_record(pos, true); self.start_song(pos, &song); self.jukebox_changed(pos); + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, stack); true } /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9ea4fe7c9..d91de60f0 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -92,6 +92,33 @@ pub(super) struct LanHost { states: lan::entity::States, } +impl LanHost { + /// `PlayerList.remove`: `player.awardStat(Stats.LEAVE_GAME)` before the + /// player is saved. Once per guest, however often they are saved. + pub(super) fn award_leave_game(&mut self, conn: u32) { + if let Some(play) = self.play.get_mut(&conn) + && !play.left_game + { + play.left_game = true; + play.stats.custom("leave_game", 1); + } + } + + /// `PlayerList.removeAll`: every player who joined leaves with the world. + pub(super) fn award_leave_game_to_all(&mut self) { + let conns: Vec = self + .hub + .guests + .iter() + .filter(|g| g.placed) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.award_leave_game(conn); + } + } +} + /// The player who owns an integrated server's world: a guest whose state is /// the world's own player (`players/data/.dat`), as in /// single player. @@ -162,12 +189,22 @@ fn mob_meta( m: &Mob, hub: &Hub, player_entity: Option, + game_time: i64, meta: &mut Vec<(u8, i32, Value)>, defaults: &mut Vec<(u8, i32, Value)>, ) { let kind = m.kind.id.as_str(); - if m.fire_ticks > 0 { - meta.push((0, serializer::BYTE, Value::Byte(1))); + // Entity.DATA_SHARED_FLAGS_ID: on fire 0x01, glowing 0x40 + // (LivingEntity.updateGlowingStatus). + let shared = i8::from(m.fire_ticks > 0) | i8::from(m.is_currently_glowing()) << 6; + if shared != 0 { + meta.push((0, serializer::BYTE, Value::Byte(shared))); + } + // Entity.DATA_POSE: the pose the species keeps in its own fields (a + // pose back at standing goes out by the entity's own default). + let pose = horizon_client::mobs::sync::pose_id(m); + if pose != 0 { + meta.push((6, serializer::POSE, Value::Id(i32::from(pose)))); } if let Some(name) = &m.custom_name { meta.push(( @@ -398,6 +435,41 @@ fn mob_meta( } defaults.push((17, serializer::BYTE, Value::Byte(0))); } + // Warden.CLIENT_ANGER_LEVEL: the heartbeat's pace. + "minecraft:warden" => { + let anger = e.warden.as_ref().map_or(0, |w| w.client_anger); + if anger != 0 { + meta.push((16, serializer::INT, Value::Int(anger))); + } + defaults.push((16, serializer::INT, Value::Int(0))); + } + // Sniffer.DATA_STATE (after AgeableMob's two). + "minecraft:sniffer" => { + if e.variant != 0 { + meta.push(( + 18, + serializer::SNIFFER_STATE, + Value::Id(i32::from(e.variant)), + )); + } + defaults.push((18, serializer::SNIFFER_STATE, Value::Id(0))); + } + // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID (16 + // for none). + "minecraft:shulker" => { + if e.variant3 != 0 { + meta.push((16, serializer::DIRECTION, Value::Id(i32::from(e.variant3)))); + } + defaults.push((16, serializer::DIRECTION, Value::Id(0))); + if e.counter != 0 { + meta.push((17, serializer::BYTE, Value::Byte(e.counter as i8))); + } + defaults.push((17, serializer::BYTE, Value::Byte(0))); + if e.color != 16 { + meta.push((18, serializer::BYTE, Value::Byte(e.color as i8))); + } + defaults.push((18, serializer::BYTE, Value::Byte(16))); + } // Enderman.DATA_CARRY_STATE. "minecraft:enderman" => { if let Some(state) = e.carried { @@ -410,6 +482,18 @@ fn mob_meta( } _ => {} } + // Camel.DASH and LAST_POSE_CHANGE_TICK (after AbstractHorse's flags). + if horizon_client::mobs::camel::is_camel(m.species()) { + if e.flag2 { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + let tick = horizon_client::mobs::camel::synced_pose_tick(m, game_time); + if tick != 0 { + meta.push((20, serializer::LONG, Value::Long(tick))); + } + defaults.push((20, serializer::LONG, Value::Long(0))); + } } /// What a client shakes a mob by: Entity.DATA_TICKS_FROZEN (7), whose full @@ -728,6 +812,7 @@ impl Game<'_> { let Some(mut host) = self.lan.take() else { return; }; + host.award_leave_game_to_all(); for g in &host.hub.guests { self.save_guest(&host, g); } @@ -935,7 +1020,7 @@ impl Game<'_> { out.clear(); for m in self.mobs.iter().filter(|m| !m.removed) { // The lead's holder: the player the mob sees (a guest, else the - // host) or another mob. A fence knot isn't an entity here. + // host), another mob or a fence knot (game/lan_entities.rs). let player_entity = mob_players .get(&m.id) .and_then(|conn| hub.guest(*conn)) @@ -944,7 +1029,7 @@ impl Game<'_> { let leash = m.extra.leash.and_then(|h| match h { Holder::Player => player_entity, Holder::Mob(id) => Some(id as i32), - Holder::Knot(_) => None, + Holder::Knot(p) => self.knot_ids.get(&p).map(|&id| id as i32), }); let e = out.add(m.id as i32, entity_uuid(m.id), m.kind.id.as_str()); e.position = [m.position.x, m.position.y, m.position.z]; @@ -952,7 +1037,14 @@ impl Game<'_> { e.on_ground = m.on_ground; e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; - mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); + mob_meta( + m, + hub, + player_entity, + self.world.game_time, + &mut e.meta, + &mut e.defaults, + ); mob_freeze_meta(m, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); @@ -964,6 +1056,10 @@ impl Game<'_> { e.position = [d.position.x, d.position.y, d.position.z]; e.on_ground = d.on_ground; e.velocity = [d.velocity.x, d.velocity.y, d.velocity.z]; + // Entity.DATA_SHARED_FLAGS_ID: glowing 0x40 (the Glowing tag). + if self.entity_glowing(d.id) { + e.meta.push((0, serializer::BYTE, Value::Byte(0x40))); + } e.meta.push((8, serializer::ITEM_STACK, Value::Item(stack))); } for o in &self.orbs { @@ -1143,6 +1239,9 @@ impl Game<'_> { } } self.lan_crafting_left(&mut host, &mut guest); + if guest.placed { + host.award_leave_game(guest.conn); + } self.save_guest(&host, &guest); host.models.remove(&guest.conn); host.play.remove(&guest.conn); @@ -1620,7 +1719,12 @@ impl Game<'_> { out, ); self.held_item_geometry(m, camera, alpha, packed, true, out); - if !m.glowing { + // LivingEntity.isCurrentlyGlowing: the guest's Glowing effect. + let guest = host.hub.guest(*conn); + if m.glowing || guest.is_some_and(|g| g.effects.get("glowing").is_some()) { + let team = guest.and_then(|g| self.score.board.players_team(&g.name)); + self.mark_outline(&out[entity_start..], super::glowing::team_color(team)); + } else { self.cull_entity_vertices(out, entity_start); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index f9a61f280..807ce9cf5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -74,6 +74,9 @@ pub(super) struct GuestPlay { potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, + /// `Stats.LEAVE_GAME` is counted: a guest is saved more than once on the + /// way out, the statistic is awarded once (`LanHost::award_leave_game`). + pub(super) left_game: bool, last_inventory: u64, /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). pub(super) portal: horizon_client::nether_portal::PortalState, @@ -681,6 +684,13 @@ impl Game<'_> { g.sprinting = false; } m.sprinting = false; + // ServerPlayer.indicateDamage: the hit's direction to the player. + if let Some(yaw) = m.health.indicated_dir.take() { + g.send(&C::HurtAnimation(play::HurtAnimation { + id: g.entity_id, + yaw, + })); + } let teleported = std::mem::take(&mut m.teleported); let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); @@ -982,6 +992,20 @@ impl Game<'_> { // The pause between two blocks is the client's (MultiPlayerGameMode's // destroyDelay); the server digs from the START it receives. play.destroy_delay = 0; + // ServerPlayerGameMode.handleBlockBreakAction: a survival START + // attacks the block at once, so a tap released in the same tick + // still plays a note. The dig is marked begun for tick_mining. + let pos = a.pos; + self.as_guest(host, conn, |g| { + if g.may_build() && !g.creative { + let _ = g.attack_block(pos); + g.mining = Some(Mining { + pos, + progress: 0.0, + ticks: 0, + }); + } + }); } 1 => {} 3 => { diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index db6235c4d..839390529 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -576,16 +576,18 @@ impl Game<'_> { /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let play = host.play.remove(&g.conn); + // The guest's play state stays: their statistics are awarded and saved + // after this (`HostEvent::Left`), which removes it. + let play = host.play.get_mut(&g.conn); let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; if let Some(play) = play { - if let Some((_, _, menu, _)) = play.crafting.table { + if let Some((_, _, menu, _)) = play.crafting.table.take() { grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); } // A workstation's inputs too. - if let Some(station) = &play.station { - grid.extend(super::lan_stations::station_inputs(station)); + if let Some(station) = play.station.take() { + grid.extend(super::lan_stations::station_inputs(&station)); } } if grid.is_empty() { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index f5e35631d..ecfa0aea5 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -225,6 +225,16 @@ impl Game<'_> { } out.push(e); } + for (p, &id) in &self.knot_ids { + // LeashFenceKnotEntity.getAddEntityPacket: the fence's block. + out.push(state( + id, + "minecraft:leash_knot", + p.map(f64::from), + 0.0, + false, + )); + } for p in &self.paintings { let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false); // Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its @@ -270,6 +280,24 @@ impl Game<'_> { /// Gives the entities Horizon keeps without an id one (`Entity.id`, from /// the same counter as the rest) before they are first tracked. pub(super) fn lan_assign_ids(&mut self) { + // LeashFenceKnotEntity: one per fence post with a lead on it + // (`notifyLeasheeRemoved` discards it once the last lead is gone). + let knots: Vec<[i32; 3]> = self + .mobs + .iter() + .filter(|m| !m.removed) + .filter_map(|m| match m.extra.leash { + Some(horizon_client::mobs::leash::Holder::Knot(p)) => Some(p), + _ => None, + }) + .collect(); + self.knot_ids.retain(|p, _| knots.contains(p)); + for p in knots { + self.knot_ids.entry(p).or_insert_with(|| { + self.next_entity += 1; + self.next_entity + }); + } let next = &mut self.next_entity; let mut give = |id: &mut u32| { if *id == 0 { diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 973e645d0..096bdcf6a 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -358,6 +358,7 @@ mod tests { off_hand: None, head: None, armor_cover: 0.0, + invisible: false, spectator: false, gold_armor: false, hurt_by: None, diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 5554d6f21..aa5981e0b 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -247,14 +247,10 @@ impl Game<'_> { return; }; let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); - // ClientLevel.addParticle: the camera's 32 blocks unless the packet - // (`force`) or the type overrides the limiter. + // ClientLevel.addParticle: the camera's 32 blocks and the Particles + // option, unless the packet or the type overrides the limiter. let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { - if p.override_limiter { - particles.create(&options, at, v); - } else { - particles.add(&options, at, v); - } + particles.add_with(&options, at, v, p.override_limiter, p.always_show); }; if p.count == 0 { add( diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index aa969305f..937fa28f4 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -267,6 +267,30 @@ impl Game<'_> { } else { Default::default() }; + // ServerPlayer.awardKillScore: the blow that kills a player. + if hurt { + let died = match victim { + // A totem that fired is applied on the next tick_totem, so the + // victim is still at zero health but is not dying. + Victim::Host => self + .player + .as_ref() + .is_some_and(|p| p.health.dead_or_dying() && !p.health.totem_used), + Victim::Guest(conn) => host + .hub + .guest(conn) + .and_then(|g| g.motion.as_deref()) + .is_some_and(|p| p.health.dead_or_dying() && !p.health.totem_used), + }; + if died { + match s.attacker { + Some(conn) => { + self.as_guest(host, conn, |g| g.stats.custom("player_kills", 1)); + } + None => self.stats.custom("player_kills", 1), + } + } + } if hurt && (s.crit || s.magic) { let target = match victim { Victim::Host => self.player.as_ref().map(|p| (host.host_entity, p)), diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 8a5c0bed8..7c6fb5598 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -12,19 +12,17 @@ use horizon_world::registry::BlockStateId; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { - self.particles - .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); + self.particles.block_teleportation(pos, data, [16, 8, 16]); } /// Event 2016: `Shulker.teleportSomewhere`'s particles between the /// shell's old and new cells. pub(super) fn shulker_teleport_particles(&mut self, pos: [i32; 3], data: i32) { - self.particles - .block_teleportation(pos, data, [8, 8, 8], self.settings.particles); + self.particles.block_teleportation(pos, data, [8, 8, 8]); } /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { self.particles - .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); + .block_teleportation(pos, data, [127, 127, 127]); } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index b0c10e34b..ab316c4c6 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -66,6 +66,8 @@ pub(super) struct Parked { tnts: Vec, hoppers: HashMap<(i32, i32, i32), machines::HopperState>, mobs: Vec, + /// The entity ids of the level's fence knots (`knot_ids`). + knot_ids: HashMap<[i32; 3], u32>, projectiles: Vec, dropped: Vec, orbs: Vec, @@ -170,6 +172,7 @@ impl Game<'_> { tnts: Vec::new(), hoppers: HashMap::new(), mobs: Vec::new(), + knot_ids: HashMap::new(), projectiles: Vec::new(), dropped: Vec::new(), orbs: Vec::new(), @@ -223,6 +226,7 @@ impl Game<'_> { swap(&mut self.tnts, &mut p.tnts); swap(&mut self.hoppers, &mut p.hoppers); swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.knot_ids, &mut p.knot_ids); swap(&mut self.creatures.projectiles, &mut p.projectiles); swap(&mut self.dropped, &mut p.dropped); swap(&mut self.orbs, &mut p.orbs); diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 8a3ac2745..921244e6d 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -16,7 +16,7 @@ pub(super) struct Bolt { flashes: i32, seed: i64, visual_only: bool, - /// Mooshrooms switch colour once per bolt. + /// Mooshrooms and copper golems change once per bolt. converted: Vec, } impl Game<'_> { @@ -278,6 +278,13 @@ impl Game<'_> { } self.strike_rod(b.at); } + // LightningBolt.tick runs clearCopperOnLightningStrike for + // every server bolt, a skeleton trap's visual one included; + // a client's copy of a server bolt (spawn_remote_bolt) only + // flashes. + if self.remote.is_none() { + self.bolt_clear_copper(b.at); + } } b.life -= 1; if b.life < 0 { @@ -334,6 +341,16 @@ impl Game<'_> { self.level_event_at(3002, p, axis); } } + /// `LightningBolt.clearCopperOnLightningStrike` at the block the bolt struck. + fn bolt_clear_copper(&mut self, at: [f64; 3]) { + let p = BlockPos::new( + at[0].floor() as i32, + (at[1] - 1.0e-6).floor() as i32, + at[2].floor() as i32, + ); + self.with_level(|b, level, ticks| b.lightning_clear_copper(level, ticks, p)); + let _ = self.process_level_events(); + } /// `thunderHit` for entities within 3 blocks (up to 9 above). fn thunder_hit(&mut self, b: &mut Bolt) { let at = b.at; @@ -393,6 +410,17 @@ impl Game<'_> { continue; } Species::Creeper => m.extra.charged = true, + // CopperGolem.thunderHit (after Entity.thunderHit's fire and + // damage): once per bolt, an oxidized golem goes back one step + // and its weathering timer (or wax, -2) is reset to -1. + Species::CopperGolem if !b.converted.contains(&m.id) => { + b.converted.push(m.id); + if m.extra.variant > 0 { + m.extra.vector[0] = -1.0; + m.extra.variant = + horizon_client::mobs::copper_golem::weather_previous(m.extra.variant); + } + } _ => {} } // Entity.thunderHit: burning (8 seconds) and 5 lightning damage. diff --git a/crates/horizon-client/src/game/llamas.rs b/crates/horizon-client/src/game/llamas.rs index 1ce518f31..080343952 100644 --- a/crates/horizon-client/src/game/llamas.rs +++ b/crates/horizon-client/src/game/llamas.rs @@ -25,11 +25,13 @@ impl Game<'_> { }; let m = &mut self.mobs[index]; let mut used = false; + let mut loved = false; if item == "minecraft:hay_block" && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; used = true; + loved = true; } if m.health < m.attrs.max_health { m.health = (m.health + heal).min(m.attrs.max_health); @@ -57,6 +59,10 @@ impl Game<'_> { if !used { return false; } + // Animal.setInLove: entity event 18. + if loved { + self.mob_event_particles(self.mobs[index].id, 18); + } self.llama_sound(index, "entity.llama.eat", 1.0); self.consume_held(); true diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index bb936744b..78dbfe66b 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -626,46 +626,8 @@ impl Game<'_> { /// `HopperBlockEntity.suckInItems`: from the container above, or item entities. fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool { let above = (pos.0, pos.1 + 1, pos.2); - let c = self.containers(); - if let Some(source) = c.view(above, false) { - if let Kind::Composter(level) = source.kind { - if level != 8 { - return false; - } - // tryTakeInItemFromSlot on the OutputContainer: removeItem calls - // its setChanged, which empties the composter, and so does the - // second setChanged after the move or, when the hopper has no - // room, the setItem putting the bone meal back into the detached - // container (whose bone meal is lost with it). - let bone_meal = c.bone_meal.clone(); - let at = BlockPos::new(above.0, above.1, above.2); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - let moved = self.add_item(None, hopper, bone_meal, None).is_none(); - self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); - self.world.modified.insert((above.0 >> 4, above.2 >> 4)); - return moved; - } - let source_hopper = (source.kind == Kind::Hopper).then_some(above); - for slot in source.slots_for_face(Some(Direction::Down)) { - let c = self.containers(); - let Some(stack) = c.get(&source, slot) else { - continue; - }; - if !c.can_take(&source, slot, stack, Direction::Down) { - continue; - } - let Some(one) = self.take_one(&source, slot) else { - continue; - }; - match self.add_item(source_hopper, hopper, one, None) { - None => { - self.view_changed(&source); - return true; - } - Some(rest) => self.put_back(&source, slot, rest), - } - } - return false; + if let Some(took) = self.suck_from_container(above, hopper) { + return took; } let above_state = self.world.block(above.0, above.1, above.2); let blocked = self.res.facts().get(above_state).full_collision @@ -695,6 +657,56 @@ impl Game<'_> { { return false; } + self.suck_item_entities(hopper, min, max) + } + /// The container half of `HopperBlockEntity.suckInItems`: one item from the + /// container at `above`, through its bottom face. `None` when there is no + /// container there. + fn suck_from_container(&mut self, above: Pos, hopper: &View) -> Option { + let c = self.containers(); + let source = c.view(above, false)?; + if let Kind::Composter(level) = source.kind { + if level != 8 { + return Some(false); + } + // tryTakeInItemFromSlot on the OutputContainer: removeItem calls + // its setChanged, which empties the composter, and so does the + // second setChanged after the move or, when the hopper has no + // room, the setItem putting the bone meal back into the detached + // container (whose bone meal is lost with it). + let bone_meal = c.bone_meal.clone(); + let at = BlockPos::new(above.0, above.1, above.2); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + let moved = self.add_item(None, hopper, bone_meal, None).is_none(); + self.with_level(|b, level, ticks| b.composter_empty(level, ticks, at)); + self.world.modified.insert((above.0 >> 4, above.2 >> 4)); + return Some(moved); + } + let source_hopper = (source.kind == Kind::Hopper).then_some(above); + for slot in source.slots_for_face(Some(Direction::Down)) { + let c = self.containers(); + let Some(stack) = c.get(&source, slot) else { + continue; + }; + if !c.can_take(&source, slot, stack, Direction::Down) { + continue; + } + let Some(one) = self.take_one(&source, slot) else { + continue; + }; + match self.add_item(source_hopper, hopper, one, None) { + None => { + self.view_changed(&source); + return Some(true); + } + Some(rest) => self.put_back(&source, slot, rest), + } + } + Some(false) + } + /// The item half of `HopperBlockEntity.suckInItems` (`getItemsAtAndAbove`): + /// adds the item entities that meet the box, until one is taken whole. + fn suck_item_entities(&mut self, hopper: &View, min: [f64; 3], max: [f64; 3]) -> bool { let mut i = 0; while i < self.dropped.len() { let b = self.dropped[i].bounds(); @@ -719,6 +731,66 @@ impl Game<'_> { } false } + /// `MinecartHopper.tick`'s `tryConsumeItems` (`suckInItems`) for an enabled + /// hopper minecart: one item from the container above, else the item + /// entities over it or touching it, each tick without a cooldown. + pub(super) fn hopper_cart_suck(&mut self, cart: &mut super::minecarts::Minecart) { + // The cart's slots are edited as a container under the placeholder key + // its menu uses; when that menu is open the placeholder is the live copy. + let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, cart.id as i32); + let open = self.world.block_entities.contains_key(&key); + if !open { + let items = BlockEntity::Chest(std::mem::take(&mut cart.items)); + self.world.block_entities.insert(key, items); + } + let size = self + .world + .block_entities + .get(&key) + .map_or(0, |e| e.slots().len()); + let view = View { + parts: vec![(key, size)], + kind: Kind::Generic, + }; + let p = cart.position; + // getLevelY is the cart's y + 0.5, so the container is the block at + // y + 1.5, and Hopper.SUCK_AABB (moved by getLevel - 0.5) starts 11/16 + // above the cart. + let above = ( + p.x.floor() as i32, + (p.y + 1.5).floor() as i32, + p.z.floor() as i32, + ); + let took = match self.suck_from_container(above, &view) { + Some(took) => took, + None => self.suck_item_entities( + &view, + [p.x - 0.5, p.y + 11.0 / 16.0, p.z - 0.5], + [p.x + 0.5, p.y + 2.0, p.z + 0.5], + ), + }; + if !took { + // The cart's own box, inflated by 0.25 sideways. + let b = cart.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + self.suck_item_entities( + &view, + [lo.x - 0.25, lo.y, lo.z - 0.25], + [hi.x + 0.25, hi.y, hi.z + 0.25], + ); + } + // The cart's own items stay the one source of truth: a menu copy that + // is still around (open, or left by a guest's close) gets the pulled + // items back into `cart.items`, so reopening never restores a stale copy. + let slots = if open { + self.world.block_entities.get(&key).cloned() + } else { + self.world.block_entities.remove(&key) + }; + if let Some(BlockEntity::Chest(items)) = slots { + cart.items = items; + } + } // ---- dispensers and droppers ---- diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 01a7c9497..ebe0f42b0 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -73,7 +73,7 @@ pub(super) struct Minecart { pub yaw: f32, pub previous_yaw: f32, pub flipped: bool, - on_ground: bool, + pub(super) on_ground: bool, horizontal_collision: bool, fall_distance: f64, pub hurt_time: i32, @@ -558,7 +558,6 @@ impl Game<'_> { // applyGravity c.velocity.y -= if self.cart_in_water(c) { 0.005 } else { 0.04 }; let pos = self.rail_block(c.position); - let fall_speed = c.velocity; if let Some(rail) = self.rail(pos[0], pos[1], pos[2]) { self.move_along_track(c, pos, &rail, intent); if &*rail.name == "minecraft:activator_rail" { @@ -600,22 +599,26 @@ impl Game<'_> { } } CartKind::Tnt => { - let speed = fall_speed.x * fall_speed.x + fall_speed.z * fall_speed.z; + // MinecartTNT.tick: the fuse and the collision check are separate. if c.fuse > 0 { c.fuse -= 1; let at = [c.position.x, c.position.y + 0.5, c.position.z]; self.particles .add(&ParticleOptions::simple(ParticleType::Smoke), at, [0.0; 3]); - } else if c.fuse == 0 || (c.horizontal_collision && speed >= 0.01) { + } else if c.fuse == 0 { + // explode(horizontalDistanceSqr()): a rising cart's + // vertical speed adds nothing. let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; - let speed = if c.fuse == 0 && c.velocity.y > 0.0 { - c.velocity.y * c.velocity.y - } else { - speed - }; self.explode_cart(c, speed); return false; } + if c.horizontal_collision { + let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z; + if speed >= f64::from(0.01_f32) { + self.explode_cart(c, speed); + return false; + } + } } _ => {} } @@ -659,51 +662,9 @@ impl Game<'_> { // The cart is the explosion's source: it is gone before the blast // looks for entities, so it can't hit itself. self.carts.retain(|x| x.id != c.id); - let _ = self.server_explode(at, power, BlockInteraction::Destroy, false); - } - /// `MinecartHopper.suckInItems`: items above, into the five slots. - fn hopper_cart_pickup(&mut self, c: &mut Minecart) { - if !c.enabled { - return; - } - let p = c.position; - let zone = Aabb::new( - Vec3::new(p.x - 0.5, p.y - 0.5 + 0.0, p.z - 0.5), - Vec3::new(p.x + 0.5, p.y + 1.5, p.z + 0.5), - ); - let mut i = 0; - while i < self.dropped.len() { - let e = &self.dropped[i]; - if e.pickup_delay > 0 || !zone.contains(e.position) { - i += 1; - continue; - } - let mut stack = e.stack.clone(); - for slot in c.items.iter_mut() { - match slot { - None => { - *slot = Some(stack.clone()); - stack.count = 0; - } - Some(s) if s.same_item_same_components(&stack) => { - let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack); - let moved = stack.count.min(max.saturating_sub(s.count)); - s.count += moved; - stack.count -= moved; - } - _ => {} - } - if stack.count == 0 { - break; - } - } - if stack.count == 0 { - self.dropped.remove(i); - } else { - self.dropped[i].stack = stack; - i += 1; - } - } + let _ = self.with_hive_emptying_blast(|g| { + g.server_explode(at, power, BlockInteraction::Destroy, false) + }); } /// `AbstractMinecart.push` from each player walking into a cart /// (`LivingEntity.pushEntities`): the window's player and every server @@ -837,8 +798,8 @@ impl Game<'_> { } let mut c = self.carts[i].clone(); let alive = self.tick_cart(&mut c, [0.0; 2]); - if c.kind == CartKind::Hopper { - self.hopper_cart_pickup(&mut c); + if c.kind == CartKind::Hopper && c.enabled { + self.hopper_cart_suck(&mut c); } let Some(i) = self.carts.iter().position(|c| c.id == id) else { continue; diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa0052bc5..617d86aaa 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -228,10 +228,12 @@ impl Game<'_> { return false; } let mut used = false; + let mut loved = false; if love && m.extra.tame && m.extra.age == 0 && m.extra.in_love <= 0 { m.extra.in_love = 600; m.extra.love_player = true; used = true; + loved = true; } if m.health < m.attrs.max_health && heal > 0.0 { m.health = (m.health + heal).min(m.attrs.max_health); @@ -251,6 +253,7 @@ impl Game<'_> { // eating(): the mouth opens and the horse eats. m.anim.v[2] = 1.0; let at = m.center(); + let id = m.id; let sound = match m.species() { Species::Camel => "minecraft:entity.camel.eat", Species::CamelHusk => "minecraft:entity.camel_husk.eat", @@ -260,6 +263,10 @@ impl Game<'_> { }; let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; self.audio.play(sound, Some(at), 1.0, pitch); + // Animal.setInLove: entity event 18. + if loved { + self.mob_event_particles(id, 18); + } self.consume_held(); true } @@ -465,14 +472,16 @@ impl Game<'_> { m.extra.owner = owner; m.persistent = true; // AbstractHorse.tameWithName: entity event 7, spawnTamingParticles(true). - self.particles_around_mob( - mob, - "heart", - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(mob, 7); } } - MobEvent::Buck { mob } if self.riding == Some(mob) => self.dismount_mount(), + MobEvent::Buck { mob } => { + if self.riding == Some(mob) { + self.dismount_mount(); + } + // RunAroundLikeCrazyGoal.tick: entity event 6, smoke. + self.mob_event_particles(mob, 6); + } _ => {} } } diff --git a/crates/horizon-client/src/game/moving_pistons.rs b/crates/horizon-client/src/game/moving_pistons.rs index 17247850e..e1bdf89d0 100644 --- a/crates/horizon-client/src/game/moving_pistons.rs +++ b/crates/horizon-client/src/game/moving_pistons.rs @@ -14,7 +14,9 @@ impl Game<'_> { out: &mut Vec, ) { let partial = alpha as f32; - for &(p, piston) in &self.world.moving_pistons { + let mut states = self.world.moving_pistons.clone(); + states.extend(self.world.moving_piston_fallback.iter().copied()); + for (p, piston) in states { let Some((block, base)) = self.moving_piston_blocks(piston, partial) else { continue; }; diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index e7f16ca18..5e384db98 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -85,13 +85,8 @@ impl Game<'_> { m.ai.target = None; } let sound = nautilus::eat_sound(m); - let kind = if tamed { "heart" } else { "smoke" }; // TamableAnimal.spawnTamingParticles (entity event 7 or 6). - self.particles_around_mob( - self.mobs[index].id, - kind, - horizon_client::particles::Burst::TAMING, - ); + self.mob_event_particles(self.mobs[index].id, if tamed { 7 } else { 6 }); self.nautilus_sound(index, sound); if tamed { let view = self.mob_entity(&self.mobs[index]); @@ -145,6 +140,8 @@ impl Game<'_> { let sound = nautilus::eat_sound(m); self.use_nautilus_food(item); self.nautilus_sound(index, sound); + // Animal.setInLove: entity event 18. + self.mob_event_particles(self.mobs[index].id, 18); return true; } false diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 2d5c6b05c..4daa03902 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -452,6 +452,7 @@ impl Game<'_> { let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); + let start = out.len(); horizon_client::mobs::render::render_with( m, alpha as f32, @@ -465,6 +466,15 @@ impl Game<'_> { self.player_elytra_geometry(m, camera, alpha as f32, packed, out); self.spin_attack_geometry(m, camera, alpha as f32, packed, out); self.held_item_geometry(m, camera, alpha, packed, true, out); + // LivingEntity.isCurrentlyGlowing: the Glowing effect. A server's client is + // in its team by its profile name. + if self.potions.effects.get("glowing").is_some() { + let team = match &self.remote { + Some(r) => self.score.board.players_team(&r.profile_name), + None => self.player_team(), + }; + self.mark_outline(&out[start..], super::glowing::team_color(team)); + } } /// `extractEntityInInventoryFollowsMouse`: the player in the box /// `[x0, x1) x [y0, y1)`, `size` pixels per block, turned toward the diff --git a/crates/horizon-client/src/game/piston_push.rs b/crates/horizon-client/src/game/piston_push.rs new file mode 100644 index 000000000..6bbf1cb39 --- /dev/null +++ b/crates/horizon-client/src/game/piston_push.rs @@ -0,0 +1,573 @@ +//! `PistonMovingBlockEntity.moveCollidedEntities` and `moveStuckEntities` for +//! the entities the game moves itself: the players and the mobs. +//! +//! The geometry is in [`horizon_world::piston_push`]; this file supplies the +//! bodies and applies the movement the way `Entity.move(MoverType.PISTON, …)` +//! does: limited to 0.51 blocks per tick per axis (`Entity.limitPistonMovement`), +//! then run through the block collision scan, so a pushed entity stops at a +//! wall instead of passing through it. +//! +use super::Game; +use horizon_client::collisions::{EntityCollisions, SceneCollisions, with_piston_noclip}; +use horizon_core::geometry::{Aabb, Direction, Vec3, border::BorderGeometry}; +use horizon_core::position::BlockPos; +use horizon_world::{ + block_collision_scan::BlockCollisionWorld, level::pistons::MovingPiston, + piston_movement::PistonMovement, piston_push, world_movement::EntityMovementWorld, +}; + +/// What one piston asks for this tick: where it is, its state, and the progress +/// `moveCollidedEntities` runs at (before the tick stores it). +pub(super) type Push = (BlockPos, MovingPiston, f32); + +/// Which entity was pushed, so its storage can be reached after the world +/// borrow ends. +#[derive(Clone, Copy, Hash, PartialEq, Eq)] +enum Target { + Player, + Guest(u32), + Mob(usize), + Item(usize), + Boat(usize), + Cart(usize), + ArmorStand(usize), +} + +/// `Entity.getStepHeight` of each body, read before the push. +struct StepHeights { + player: f32, + guests: std::collections::HashMap, +} + +/// What the push needs from one entity. +#[derive(Clone, Copy)] +struct Body { + bounds: Aabb, + position: Vec3, + on_ground: bool, + step_height: f32, + /// Standing on the piston's own block (`Entity.isSupportedBy`). + supported: bool, +} + +impl Game<'_> { + /// Push whatever this tick's moving pistons ran into, in the order the + /// pistons ticked: vanilla pushes from each block entity's own tick. + pub(super) fn push_piston_entities(&mut self, pushes: Vec) { + let mut accumulators = std::collections::HashMap::new(); + for push in pushes { + self.push_for_piston(push, &mut accumulators); + } + } + + fn push_for_piston( + &mut self, + (pos, piston, new_progress): Push, + accumulators: &mut std::collections::HashMap, + ) { + let delta_progress = f64::from(new_progress - piston.progress); + if delta_progress <= 0.0 { + return; + } + let Some(bindings) = self.collision.pistons() else { + return; + }; + let Ok(state) = bindings.collision_related_state(piston.shape_state()) else { + return; + }; + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + let Ok(shape) = self + .collision + .collision_shape(&mut scene, state, [pos.x, pos.y, pos.z]) + else { + return; + }; + if shape.is_empty() { + return; + } + let movement = piston.movement_direction(); + let boxes: Vec = shape.boxes().to_vec(); + let facts = self.res.facts(); + let slime = &*facts.get(piston.moved_state).name == "minecraft:slime_block"; + let honey = &*facts.get(piston.moved_state).name == "minecraft:honey_block"; + // `moveStuckEntities` asks the moved state's own top for its box. + let sticky_top = if honey { + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + self.collision + .collision_shape(&mut scene, piston.moved_state, [pos.x, pos.y, pos.z]) + .ok() + .and_then(|s| s.bounds()) + .map_or(0.0, |b| b.max_position().y) + } else { + 0.0 + }; + + let steps = self.push_step_heights(); + let search = shape.bounds().map(|bounds| { + piston_push::movement_search_area( + piston_push::move_by_position_and_progress(pos, bounds, piston.shape_state()), + movement, + delta_progress, + ) + }); + let targets = self.push_targets(); + for &target in &targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + let amount = piston_push::collided_amount( + &boxes, + pos, + piston.shape_state(), + new_progress, + movement, + body.bounds, + ); + if slime && search.is_some_and(|area| area.intersects(body.bounds)) { + self.bounce(target, movement); + } + if amount > 0.0 { + let step = piston_push::step_vector(movement); + let before = body.bounds; + self.move_pushed( + target, + before, + [body.position.x, body.position.z], + body.step_height, + body.on_ground, + step.scale(amount), + movement, + accumulators, + ); + // `fixEntityWithinPistonBase`: a retracting source piston drags + // an entity that is still inside its own block. + if !piston.extending + && piston.source + && let Some(after) = self.push_body(target, pos, &steps) + && let Some(fix) = piston_push::fix_within_piston_base( + pos, + after.bounds, + movement, + delta_progress, + ) + { + let back = piston_push::step_vector(movement.opposite()); + self.move_pushed( + target, + after.bounds, + [after.position.x, after.position.z], + after.step_height, + after.on_ground, + back.scale(fix), + movement, + accumulators, + ); + } + } + } + // Vanilla selects honey passengers after all collided entities have moved. + if honey && movement.normal()[1] == 0 { + let area = piston_push::sticky_area(pos, piston.shape_state(), sticky_top); + for target in targets { + let Some(body) = self.push_body(target, pos, &steps) else { + continue; + }; + if piston_push::sticky_entity_selected( + area, + body.bounds, + horizon_world::level::data::PushReaction::PushPull, + body.on_ground, + body.supported, + body.position, + ) { + self.move_pushed( + target, + body.bounds, + [body.position.x, body.position.z], + body.step_height, + body.on_ground, + piston_push::step_vector(movement).scale(delta_progress), + movement, + accumulators, + ); + } + } + } + } + + /// `Entity.getStepHeight` for each body, read once: the attribute lookup + /// needs the mutable body, and the push only needs the number. + fn push_step_heights(&mut self) -> StepHeights { + let player = self + .player + .as_mut() + .and_then(|p| p.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + let mut guests = std::collections::HashMap::new(); + if let Some(host) = self.lan.as_mut() { + for g in &mut host.hub.guests { + let step = g + .motion + .as_mut() + .and_then(|m| m.attribute("minecraft:step_height").ok()) + .map_or(0.6, |v| v as f32); + guests.insert(g.conn, step); + } + } + StepHeights { player, guests } + } + + /// The entities a moving block can run into: the window's player, the LAN + /// guests in the level, then the mobs. + fn push_targets(&self) -> Vec { + let mut targets = Vec::new(); + if self.player.is_some() { + targets.push(Target::Player); + } + if let Some(host) = self.lan.as_ref() { + targets.extend( + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| Target::Guest(g.conn)), + ); + } + targets.extend((0..self.mobs.len()).map(Target::Mob)); + targets.extend((0..self.dropped.len()).map(Target::Item)); + targets.extend((0..self.boats.len()).map(Target::Boat)); + targets.extend((0..self.carts.len()).map(Target::Cart)); + targets.extend((0..self.armor_stands.len()).map(Target::ArmorStand)); + targets + } + + /// What the push needs from one entity, or `None` when it is not pushed: + /// removed, dead, a spectator, or an armor-stand marker. + fn push_body(&self, target: Target, pos: BlockPos, steps: &StepHeights) -> Option { + let at = [pos.x, pos.y, pos.z]; + match target { + Target::Player => { + let p = self.player.as_ref()?; + if p.spectator { + return None; + } + Some(Body { + bounds: p.bounds(), + position: p.position, + on_ground: p.ground.on_ground, + step_height: steps.player, + supported: p.ground.supporting_block == Some(pos), + }) + } + Target::Guest(conn) => { + let host = self.lan.as_ref()?; + let g = host.hub.guests.iter().find(|g| g.conn == conn)?; + if g.dead || g.game_mode == 3 { + return None; + } + let p = g.position; + Some(Body { + bounds: Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + 1.8, p[2] + 0.3), + ), + position: Vec3::new(p[0], p[1], p[2]), + on_ground: g.on_ground, + step_height: steps.guests.get(&conn).copied().unwrap_or(0.6), + supported: g + .motion + .as_ref() + .is_some_and(|m| m.ground.supporting_block == Some(pos)), + }) + } + Target::Mob(i) => { + let m = &self.mobs[i]; + if m.removed || !m.alive() { + return None; + } + Some(Body { + bounds: m.bounds(), + position: m.position, + on_ground: m.on_ground, + step_height: m.kind.step_height as f32, + supported: m.supporting == Some(at), + }) + } + Target::Item(i) => { + let entity = &self.dropped[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Boat(i) => { + let entity = &self.boats[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::Cart(i) => { + let entity = &self.carts[i]; + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + Target::ArmorStand(i) => { + let entity = &self.armor_stands[i]; + if entity.marker { + return None; + } + Some(Body { + bounds: entity.bounds(), + position: entity.position, + on_ground: entity.on_ground, + step_height: 0.0, + supported: false, + }) + } + } + } + + /// `Entity.move(MoverType.PISTON, movement)` for one pushed entity: the + /// per-tick piston limit, then the block and world border collision scan. + fn move_pushed( + &mut self, + target: Target, + before: Aabb, + at: [f64; 2], + step_height: f32, + on_ground: bool, + movement: Vec3, + piston_direction: Direction, + accumulators: &mut std::collections::HashMap, + ) { + let Some(limited) = self.limit_piston(target, movement, accumulators) else { + return; + }; + // `limitPistonMovement` returns zero once the tick's budget is spent. + if limited == Vec3::ZERO { + return; + } + let resolved = with_piston_noclip(piston_direction, || { + pushed_movement( + SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }, + self.border.geometry(), + at, + before, + limited, + step_height, + on_ground, + ) + .unwrap_or(Vec3::ZERO) + }); + if resolved.length_squared() <= 1.0e-7 + && limited.length_squared() - resolved.length_squared() >= 1.0e-7 + { + return; + } + self.apply_push(target, resolved); + } + + /// `Entity.limitPistonMovement`: each axis may travel at most 0.51 blocks + /// per game tick, and a move touches only its first non-zero axis. + fn limit_piston( + &mut self, + target: Target, + movement: Vec3, + accumulators: &mut std::collections::HashMap, + ) -> Option { + let time = self.world.game_time; + let limit = |state: &mut PistonMovement| state.limit(movement, || Ok::(time)).ok(); + match target { + Target::Player => { + let p = self.player.as_mut()?; + limit(&mut p.piston) + } + Target::Guest(conn) => { + let host = self.lan.as_mut()?; + let g = host.hub.guests.iter_mut().find(|g| g.conn == conn)?; + limit(&mut g.motion.as_deref_mut()?.piston) + } + Target::Mob(i) => limit(&mut self.mobs[i].piston), + _ => limit(accumulators.entry(target).or_default()), + } + } + + fn apply_push(&mut self, target: Target, movement: Vec3) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.position = p.position.add_vector(movement); + } + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + { + // The body and the hub's copy of its position move together: + // `leave_guest` writes the body back over the hub's. + for (slot, delta) in g.position.iter_mut().zip(movement.components()) { + *slot += delta; + } + if let Some(m) = g.motion.as_deref_mut() { + m.position = m.position.add_vector(movement); + } + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.position = m.position.add_vector(movement); + } + Target::Item(i) => { + self.dropped[i].position = self.dropped[i].position.add_vector(movement) + } + Target::Boat(i) => self.boats[i].position = self.boats[i].position.add_vector(movement), + Target::Cart(i) => self.carts[i].position = self.carts[i].position.add_vector(movement), + Target::ArmorStand(i) => { + self.armor_stands[i].position = self.armor_stands[i].position.add_vector(movement) + } + } + } + + /// `causeBounce`: a slime block sets the velocity along the movement axis. + fn bounce(&mut self, target: Target, movement: Direction) { + match target { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.velocity = piston_push::bounce_velocity(movement, p.velocity); + } + } + Target::Mob(i) => { + let m = &mut self.mobs[i]; + m.velocity = piston_push::bounce_velocity(movement, m.velocity); + } + Target::Guest(conn) => { + if let Some(host) = self.lan.as_mut() + && let Some(guest) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && let Some(motion) = guest.motion.as_deref_mut() + { + motion.velocity = piston_push::bounce_velocity(movement, motion.velocity); + } + } + Target::Item(i) => { + self.dropped[i].velocity = + piston_push::bounce_velocity(movement, self.dropped[i].velocity) + } + Target::Boat(i) => { + self.boats[i].velocity = + piston_push::bounce_velocity(movement, self.boats[i].velocity) + } + Target::Cart(i) => { + self.carts[i].velocity = + piston_push::bounce_velocity(movement, self.carts[i].velocity) + } + Target::ArmorStand(i) => { + self.armor_stands[i].velocity = + piston_push::bounce_velocity(movement, self.armor_stands[i].velocity) + } + } + } +} + +/// `Entity.move(MoverType.PISTON, movement)` for a pushed body: the movement +/// it makes. The world's blocks stop it, and so does the world border: +/// `Entity.collectCollidersIgnoringWorldBorder` adds the border's walls when +/// the body is inside close to the border, as ordinary movement does. +fn pushed_movement( + blocks: W, + border: &BorderGeometry, + at: [f64; 2], + before: Aabb, + movement: Vec3, + step_height: f32, + on_ground: bool, +) -> horizon_client::Result +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + EntityCollisions::with_border(blocks, border, at).resolve( + before, + movement, + step_height, + on_ground, + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::collisions::EmptyCollisions; + + /// A border 10 wide around the origin: its wall's inner face is at x = 5. + fn border() -> BorderGeometry { + BorderGeometry::new([0.0, 0.0], 10.0, 29_999_984).expect("a border") + } + + /// `Entity.collectCollidersIgnoringWorldBorder`: the border's walls stop a + /// pushed body that is inside close to the border. + #[test] + fn a_pushed_body_stops_at_the_world_border() { + // A body 0.6 wide, 0.4 blocks short of the wall, pushed east into it. + let before = Aabb::new(Vec3::new(4.0, 0.0, 0.0), Vec3::new(4.6, 1.8, 0.6)); + let border = border(); + let moved = pushed_movement( + EmptyCollisions, + &border, + [4.3, 0.3], + before, + Vec3::new(0.51, 0.0, 0.0), + 0.0, + false, + ) + .expect("the push resolves"); + // The wall stops the body 0.4 blocks short of the whole push. + assert!( + (moved.x - 0.4).abs() < 1.0e-9, + "the body was not stopped by the border: {moved:?}" + ); + } + + /// Away from the border, the same push moves the whole way. + #[test] + fn a_pushed_body_moves_whole_away_from_the_border() { + let before = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(0.6, 1.8, 0.6)); + let border = border(); + let moved = pushed_movement( + EmptyCollisions, + &border, + [0.3, 0.3], + before, + Vec3::new(0.51, 0.0, 0.0), + 0.0, + false, + ) + .expect("the push resolves"); + assert!( + (moved.x - 0.51).abs() < 1.0e-9, + "the body did not move the whole push: {moved:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 5efac4927..a87a15254 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -478,8 +478,10 @@ impl Game<'_> { } // The omens act from inside the effect tick (BadOmenMobEffect, // RaidOmenMobEffect). + let absorption_empty = player.health.absorption() <= 0.0; let mut effects = std::mem::take(&mut self.potions.effects); - let (actions, raid_omen_added) = effects.tick_with(&mut |e| self.omen_tick(e)); + let (actions, raid_omen_added) = + effects.tick_with(&mut |e| self.omen_tick(e), absorption_empty); self.potions.effects = effects; if raid_omen_added { self.raid_omen_added(); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index e41aca43b..117352e10 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -186,6 +186,9 @@ pub(super) struct Remote { online_mode: bool, /// Player entities in the level: entity id to profile UUID. level_players: HashMap, + /// Entities with shared flag 6 (`Entity.isCurrentlyGlowing` on a client); mobs keep + /// theirs in `Mob::glowing`. + glowing: std::collections::HashSet, /// The local player's profile UUID (always in the level). profile: u128, /// The local player's profile name: its score holder and team member. @@ -483,6 +486,7 @@ impl Game<'_> { listed: Default::default(), online_mode: false, level_players: HashMap::new(), + glowing: Default::default(), profile: 0, profile_name: String::new(), destroying: None, @@ -1430,6 +1434,13 @@ impl Game<'_> { { return; } + // So does a firework rocket: its own tick flies it on. + if path.is_some() + && let Some(f) = self.rockets.iter_mut().find(|f| f.id == id as u32) + { + f.position = Vec3::new(position[0], position[1], position[2]); + return; + } // A dragon fireball keeps Entity's NO_OP InterpolationHandler too: // the server's position replaces its own at once. if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { @@ -1488,7 +1499,9 @@ impl Game<'_> { self.remove_remote_dragon(id); self.remove_remote_object(id as u32); self.remove_remote_projectile(id as u32); + self.persist.uuids.remove(&(id as u32)); if let Some(r) = self.remote.as_mut() { + r.glowing.remove(&id); r.entities.remove(&id); r.lerps.remove(&id); r.stepped.remove(&id); @@ -1805,6 +1818,11 @@ impl Game<'_> { r.level_players.remove(&p.id); } } + // Entity.getTeam: a mob is on a team by its UUID. + self.persist.uuids.insert( + p.id as u32, + horizon_client::lan::playerdata::uuid_ints(p.uuid), + ); self.spawn_entity(p.id, &kind, p.position, rotation); // Entity.recreateFromPacket: setDeltaMovement(packet.getMovement()). self.remote_motion(p.id, p.velocity); @@ -1896,7 +1914,8 @@ impl Game<'_> { } C::SetPassengers(p) => self.remote_set_passengers(p.vehicle, &p.passengers), // ClientPacketListener.handleEntityLinkPacket: who holds a mob's - // lead (this player, another player or a mob), for the rope. + // lead (this player, another player, a mob or a fence knot), for + // the rope. C::SetEntityLink(p) => { let me = self.remote.as_ref().map(|r| r.entity_id); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.source as u32) { @@ -1904,7 +1923,12 @@ impl Game<'_> { m.extra.leash = match p.dest { 0 => None, d if Some(d) == me => Some(Holder::Player), - d => Some(Holder::Mob(d as u32)), + d => match self.remote_knots.get(&(d as u32)) { + Some(&block) => Some(Holder::Knot(block)), + // Not a known knot yet: kept by id until the knot + // arrives (game/remote_objects.rs). + None => Some(Holder::Mob(d as u32)), + }, }; } } @@ -1923,7 +1947,10 @@ impl Game<'_> { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { for (index, _, value) in &p.values { match (index, value) { - (0, Value::Byte(flags)) => m.invisible = flags & 0x20 != 0, + (0, Value::Byte(flags)) => { + m.invisible = flags & 0x20 != 0; + m.glowing = flags & 0x40 != 0; + } (2, Value::OptText(name)) => { let text = name.as_ref().map(horizon_client::entity_nbt::name_text); m.custom_name = @@ -1940,6 +1967,15 @@ impl Game<'_> { } } } + if let Some((_, _, Value::Byte(flags))) = p.values.iter().find(|v| v.0 == 0) + && let Some(r) = self.remote.as_mut() + { + if flags & 0x40 != 0 { + r.glowing.insert(p.id); + } else { + r.glowing.remove(&p.id); + } + } self.remote_mob_data(p.id, &p.values); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) && m.species() == horizon_client::mobs::Species::Creeper @@ -2164,8 +2200,9 @@ impl Game<'_> { } C::HurtAnimation(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + // Player.animateHurt: the tilt turns around the yaw. if let Some(pl) = self.player.as_mut() { - pl.health.animate_hurt(); + pl.health.animate_hurt_dir(p.yaw); } } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; @@ -2202,6 +2239,10 @@ impl Game<'_> { { m.health = 0.0; } + // The events that start a mob's animation (the warden's). + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + horizon_client::mobs::sync::entity_event(m, p.event as u8); + } // LivingEntity.handleEntityEvent 60: the poof as the dead body goes. if p.event == 60 && let Some(m) = self.mobs.iter().find(|m| m.id == p.id as u32) @@ -2212,6 +2253,37 @@ impl Game<'_> { if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + // Mob.handleEntityEvent 20: the spawn poof. + if p.event == 20 && self.mobs.iter().any(|m| m.id == p.id as u32) { + self.poof_particles(p.id as u32); + } + // Villager 12, 13 and 14, TamableAnimal and AbstractHorse 6 and + // 7, Animal and Allay 18: the particles about the mob. + if matches!(p.event, 6 | 7 | 12 | 13 | 14 | 18) { + self.entity_event_particles(p.id as u32, p.event); + } + // Snowball and ThrownEgg.handleEntityEvent 3: the crumbs where + // the projectile is (the server removes it right after). + if p.event == 3 { + let crumbs = self + .creatures + .projectiles + .iter() + .find(|pr| pr.id == p.id as u32) + .and_then(|pr| { + let item = match pr.kind { + horizon_client::projectiles::ProjectileKind::Snowball => { + "minecraft:snowball" + } + horizon_client::projectiles::ProjectileKind::Egg => "minecraft:egg", + _ => return None, + }; + Some(([pr.position.x, pr.position.y, pr.position.z], item)) + }); + if let Some((at, item)) = crumbs { + self.item_burst(at, item); + } + } if p.event == super::combat::DROWN_EVENT { self.remote_drown(p.id); } @@ -2899,7 +2971,7 @@ impl Game<'_> { resolved.push((uuid, skin)); } } - resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.show_skin(skin)); + resolved.retain(|(_, skin)| !skin.starts_with("skins/") || self.again_skin(skin)); let Some((level, skins, own)) = self.remote.as_mut().map(|r| { r.skins = resolved.into_iter().collect(); ( @@ -2938,11 +3010,9 @@ impl Game<'_> { .iter() .filter(|m| &*m.kind.id == "minecraft:mannequin" && m.profile.is_some()) .map(|m| { - let t = m - .profile - .as_ref() - .and_then(|p| p.properties.iter().find(|p| p.name == "textures")); - let textures = t.map_or_else(Default::default, |t| { + let profile = m.profile.as_ref(); + let t = profile.and_then(|p| p.properties.iter().find(|p| p.name == "textures")); + let textures = if let Some(t) = t { let signature = if t.signature.is_some() { horizon_client::skins::Signature::Signed } else { @@ -2953,7 +3023,30 @@ impl Game<'_> { signature, &horizon_client::skins::TEXTURE_URIS, ) - }); + } else { + // `ResolvableProfile.resolveProfile`: no `textures` and + // only a name or an id resolves through the services. + let key = profile.and_then(|p| match (&p.name, p.uuid) { + (Some(name), None) => { + Some(horizon_client::skins::NameOrId::Name(name.clone())) + } + (None, Some(id)) => Some(horizon_client::skins::NameOrId::Id(id)), + _ => None, + }); + key.and_then(|key| match self.skin_profiles.borrow_mut().state(&key) { + horizon_client::skins::Resolve::Done(Some(profile)) => { + profile.textures().map(|(value, signature)| { + horizon_client::skins::unpack( + &value, + signature, + &horizon_client::skins::TEXTURE_URIS, + ) + }) + } + _ => None, + }) + .unwrap_or_default() + }; (m.id, textures) }) .collect(); @@ -2968,7 +3061,7 @@ impl Game<'_> { resolved.push((id, skin)); } for (id, skin) in resolved { - let skin = skin.filter(|s| !s.starts_with("skins/") || self.show_skin(s)); + let skin = skin.filter(|s| !s.starts_with("skins/") || self.again_skin(s)); if let Some(mob) = self .mobs .iter_mut() @@ -3018,6 +3111,10 @@ impl Game<'_> { self.skin_slots.push(e); true } + /// `show_skin`, or — its slot evicted — the image queued for upload again. + fn again_skin(&mut self, location: &str) -> bool { + self.show_skin(location) || self.skin_downloads.borrow_mut().again(location) + } /// ChatType decoration: `chat.translation_key` with sender/content parameters. /// ChatType.Bound.decorate: the chat type's translation, with the /// sender, the target and the message as its parameters, in its style. @@ -3121,6 +3218,8 @@ impl Game<'_> { p.velocity = v; } else if let Some(b) = self.dragon_fireballs.iter_mut().find(|b| b.id == id as u32) { b.velocity = v; + } else if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id as u32) { + r.velocity = v; } else if let Some(p) = self .remote .as_mut() @@ -3234,6 +3333,15 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; + // AbstractSignEditScreen.tick: the editor closes once its sign is removed. + if let Some(edit) = &self.sign_edit + && !matches!( + self.world.block_entities.get(&edit.pos), + Some(BlockEntity::Sign(_)) + ) + { + self.close_sign_editor(); + } self.track_experience_display(); // Leaving a slot clears its bundle's selection here and on the server. self.tick_bundle_hover(); @@ -3289,6 +3397,8 @@ impl Game<'_> { self.with_level(|b, level, ticks| { b.client_tick_block_entities(level, ticks); }); + let pushes = std::mem::take(&mut self.block_ticks.piston_pushes); + self.push_piston_entities(pushes); self.sync_moving_pistons(); self.tick_hand(); self.tick_particles(); @@ -3607,6 +3717,7 @@ impl Game<'_> { m.fluids = fluids; } } + let game_time = self.world.game_time; let Some(r) = self.remote.as_mut() else { return; }; @@ -3730,6 +3841,8 @@ impl Game<'_> { if m.species() == horizon_client::mobs::Species::Bat { horizon_client::mobs::bat::setup_animation_states(m); } + // The animation states a server computes in its own `ai_step`. + horizon_client::mobs::sync::client_tick(m, game_time); } for o in self.orbs.iter_mut().filter(|_| running) { o.previous = o.position; @@ -4331,6 +4444,16 @@ impl Game<'_> { if self.keys.contains(&KeyCode::ShiftLeft) && hands_full { return (false, DryUse::default()); } + // BeehiveBlock.useItemOn: shears or a glass bottle on a full hive + // (honey level 5) is SUCCESS, so the click ends after UseItemOn and + // no UseItem follows (the server does the harvest, see `use_beehive`). + if held.is_some_and(|s| matches!(&*s.item, "minecraft:shears" | "minecraft:glass_bottle")) + && self + .hive_state(hit.pos) + .is_some_and(|(honey, _)| honey == Some(5)) + { + return (true, DryUse::default()); + } use horizon_core::geometry::Direction; let face = match hit.face { [0, 1, 0] => Direction::Up, @@ -5394,6 +5517,11 @@ impl Game<'_> { batch.text(atlas, message, (w - tw) / 2.0, 85.0, u32::MAX, true); } } + /// Shared flag 6 of an entity on a server's client (`None` without a server). + pub(super) fn remote_glowing(&self, id: u32) -> Option { + let r = self.remote.as_ref()?; + Some(r.glowing.contains(&(id as i32))) + } /// Status for `horizon-ctl status`. /// The other players' entities in the level and their names (from the /// player list). diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index d6e4372f6..f85a96119 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -4,7 +4,7 @@ //! own simulation, which a client of a server doesn't run. use super::Game; use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES}; -use horizon_client::mobs::{Mob, Species, Who, bat, tame}; +use horizon_client::mobs::{Mob, Species, Who, bat, camel, sniffer, sync, tame}; use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_protocol::entity_data::{Particle, ParticleData, Value}; use horizon_protocol::registry::Builtin; @@ -27,6 +27,8 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti // client, which draws the flames. A client doesn't count the // fire down: the flag goes off when the server's fire is out. (0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1), + // Entity.DATA_POSE: the pose the species animates by. + (6, Value::Id(pose)) => sync::set_pose(m, (*pose).clamp(0, 17) as u8), // LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the // off hand 2. The flag starts and stops the use; the client ticks // the count itself (a bow's pull follows it). @@ -100,6 +102,29 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti (Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => { m.extra.size = (*size).clamp(1, 127); } + // Warden.CLIENT_ANGER_LEVEL: the heartbeat's pace. + (Species::Warden, 16, Value::Int(anger)) => { + if let Some(st) = m.extra.warden.as_mut() { + st.client_anger = *anger; + } + } + // Sniffer.DATA_STATE (after AgeableMob's two): the animation + // follows it in `sync::client_tick`. + (Species::Sniffer, 18, Value::Id(state)) => { + sniffer::set_state(m, (*state).clamp(0, 6) as u8); + } + // Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID. + (Species::Shulker, 16, Value::Id(face)) => m.extra.variant3 = (*face).clamp(0, 5) as u8, + (Species::Shulker, 17, Value::Byte(peek)) => m.extra.counter = i32::from(*peek), + (Species::Shulker, 18, Value::Byte(color)) => m.extra.color = *color as u8, + // Camel.DASH and LAST_POSE_CHANGE_TICK (after AbstractHorse's + // flags). + (Species::Camel | Species::CamelHusk, 19, Value::Bool(dashing)) => { + camel::set_dashing(m, *dashing); + } + (Species::Camel | Species::CamelHusk, 20, Value::Long(tick)) => { + camel::set_synced_pose_tick(m, *tick); + } // Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's // IS_CELEBRATING takes 16). (Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging, diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs index 05b1a2b9e..7f484c35f 100644 --- a/crates/horizon-client/src/game/remote_objects.rs +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -1,9 +1,10 @@ -//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! Boats, minecarts, armor stands, item frames, paintings and fence knots on a server's //! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, //! `handleSetEquipment`): the server simulates them, the client places them //! where it says and interpolates their moves like a mob's. use super::Game; use horizon_client::entities::{ArmorStand, Cushion, ItemFrame, Painting}; +use horizon_client::mobs::leash::Holder; use horizon_core::geometry::Vec3; use horizon_protocol::entity_data::Value; use std::sync::Arc; @@ -24,7 +25,17 @@ impl Game<'_> { let at = Vec3::new(position[0], position[1], position[2]); let block = position.map(|v| v.floor() as i32); self.remove_remote_object(id); - if kind == "minecraft:text_display" { + if kind == "minecraft:leash_knot" { + // A lead that came before its knot waits as a mob holder with the + // knot's id (handleEntityLinkPacket's delayed holder); now it can + // be tied to the fence. + self.remote_knots.insert(id, block); + for m in &mut self.mobs { + if m.extra.leash == Some(Holder::Mob(id)) { + m.extra.leash = Some(Holder::Knot(block)); + } + } + } else if kind == "minecraft:text_display" { self.text_displays.insert( id as i32, super::text_displays::RemoteTextDisplay::new(position, yaw), @@ -304,6 +315,7 @@ impl Game<'_> { /// Every object a server sent (a new connection, level or dimension). pub(super) fn clear_remote_objects(&mut self) { self.text_displays.clear(); + self.remote_knots.clear(); self.carts.clear(); self.boats.clear(); self.armor_stands.clear(); @@ -314,6 +326,7 @@ impl Game<'_> { pub(super) fn remove_remote_object(&mut self, id: u32) { self.text_displays.remove(&(id as i32)); + self.remote_knots.remove(&id); self.carts.retain(|c| c.id != id); self.boats.retain(|b| b.id != id); self.armor_stands.retain(|a| a.id != id); diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 06270e4f0..00d4abaed 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -3,8 +3,11 @@ //! and `handleSetEntityData`): the server simulates them, the client draws //! them where it says and interpolates their moves. use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector}; -use horizon_client::particles::{ParticleOptions, ParticleType}; use horizon_client::projectiles::{Hit, Projectile, ProjectileKind, ProjectileWorld}; +use horizon_client::{ + collisions::SceneCollisions, + particles::{ParticleOptions, ParticleType}, +}; use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; use horizon_protocol::entity_data::Value; use horizon_world::registry::BlockStateId; @@ -71,7 +74,8 @@ pub(super) fn cloud_client_tick( ]; (particle.clone(), v) }; - particles.add(&options, at, velocity); + // `addAlwaysVisibleParticle`. + particles.add_with(&options, at, velocity, false, true); } } @@ -444,31 +448,58 @@ impl Game<'_> { let id = t.id; t.remote_step(|at| step(id, at)); } - // FireworkRocketEntity.tick: a rocket attached to the gliding local - // player boosts it client-side too (attachedToEntity.isFallFlying). + // FireworkRocketEntity.tick: a rocket attached to an entity follows it + // and boosts it client-side too (attachedToEntity.isFallFlying), and + // every rocket leaves its spark trail on a client. let me = self .remote .as_ref() .and_then(|r| u32::try_from(r.entity_id).ok()); - for r in &mut self.rockets { - let id = r.id; - r.remote_step(|at| step(id, at)); - if me.is_some() - && r.attached_to == me - && let Some(p) = self.player.as_mut() - && p.fall_flying - { - let look = view_vector(self.yaw, self.pitch); - let m = p.velocity; - p.velocity = Vec3::new( - m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, - m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, - m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, - ); - r.position = p.position; - r.velocity = p.velocity; + let mut rockets = std::mem::take(&mut self.rockets); + for r in &mut rockets { + r.remote_step(&mut SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }); + if let Some(target) = r.attached_to { + if me == Some(target) { + if let Some(p) = self.player.as_mut() { + if p.fall_flying { + let look = view_vector(self.yaw, self.pitch); + let m = p.velocity; + p.velocity = Vec3::new( + m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5, + m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5, + m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5, + ); + } + r.position = p.position; + r.velocity = p.velocity; + } + } else if let Some(m) = self.mobs.iter().find(|m| m.id == target) { + // Another player's motion is not known here: its step. + r.velocity = Vec3::new( + m.position.x - r.previous.x, + m.position.y - r.previous.y, + m.position.z - r.previous.z, + ); + r.position = m.position; + } } + let g = |g: &mut horizon_core::random::LegacyRandom| g.next_gaussian() * 0.05; + let v = [ + g(&mut self.world.random), + -r.velocity.y * 0.5, + g(&mut self.world.random), + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Firework), + [r.position.x, r.position.y, r.position.z], + v, + ); } + self.rockets = rockets; for c in &mut self.crystals { c.time += 1; c.position = step(c.id, c.position); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 8085cefee..fecb58615 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -245,6 +245,7 @@ impl Game<'_> { 1.0, ); } + self.particles.particle_level = self.settings.particles; if let Some(e) = eye { self.particles.camera = e; } @@ -295,7 +296,8 @@ impl Game<'_> { let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); let radius = self.settings.weather_radius; let diameter = 2 * radius + 1; - let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; + let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32 + / if self.settings.particles == 1 { 2 } else { 1 }; let mut rain_position = None; for _ in 0..count { let x = block[0] + random.next_int_bound(diameter).unwrap_or(0) - radius; @@ -310,6 +312,11 @@ impl Game<'_> { } let below = top - 1; rain_position = Some([x, below, z]); + // The Minimal option stops at the first spot that rains (the + // rain sound still plays there). + if self.settings.particles >= 2 { + break; + } let (bx, bz) = (random.next_double(), random.next_double()); let state = world.block(x, below, z); let f = facts.get(state); diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index 3d946ce7b..c26314513 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -21,6 +21,9 @@ pub(super) struct SignEditor { pub line: usize, /// The line being edited (`AbstractSignEditScreen`'s text field). edit: EditBox, + /// `AbstractSignEditScreen.messages`: the side's lines as edited, sent + /// when the editor closes, even if the sign is gone by then. + lines: [String; 4], } fn sign_box() -> EditBox { @@ -185,11 +188,19 @@ impl Game<'_> { } /// `SignBlock.openTextEdit` for the front side after placement. pub(super) fn open_sign_editor(&mut self, pos: (i32, i32, i32), front: bool) { + // Minecraft.setScreen: the editor already open is removed first. + self.close_sign_editor(); + let lines = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Sign(sign)) if front => sign.front.lines.clone(), + Some(BlockEntity::Sign(sign)) => sign.back.lines.clone(), + _ => Default::default(), + }; self.sign_edit = Some(SignEditor { pos, front, line: 0, edit: sign_box(), + lines, }); self.sign_load(); self.keys.clear(); @@ -202,14 +213,11 @@ impl Game<'_> { pub(super) fn close_sign_editor(&mut self) { if let Some(edit) = self.sign_edit.take() { if self.remote.is_some() { - if let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) { - let side = if edit.front { &sign.front } else { &sign.back }; - self.send(S::SignUpdate(play::SignUpdate { - pos: [edit.pos.0, edit.pos.1, edit.pos.2], - lines: side.lines.clone(), - front: edit.front, - })); - } + self.send(S::SignUpdate(play::SignUpdate { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + lines: edit.lines, + front: edit.front, + })); } else { self.mark_block_entity_updated(edit.pos); } @@ -358,7 +366,8 @@ impl Game<'_> { edit.edit.set_value(&text); } } - /// The box's text onto the sign, when it still fits the line. + /// The box's text onto the editor's lines and the sign + /// (`AbstractSignEditScreen.setMessage`), when it still fits the line. fn sign_write(&mut self) { let Some(edit) = self.sign_edit.as_ref() else { return; @@ -367,6 +376,9 @@ impl Game<'_> { if !self.sign_fits(&value) { return; } + if let Some(edit) = self.sign_edit.as_mut() { + edit.lines[line].clone_from(&value); + } let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get_mut(&pos) else { return; }; diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 5dd907afb..a3761cf7a 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -257,8 +257,17 @@ impl Game<'_> { let Some(m) = self.mobs.iter().find(|m| m.id == id) else { return; }; - let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); + let at = m.position; self.lan_entity_event(id as i32, 20, [at.x, at.y, at.z]); + self.poof_particles(id); + } + /// `Mob.handleEntityEvent` 20 (`spawnAnim` on a client): the poof about + /// mob `id`. + pub(super) fn poof_particles(&mut self, id: u32) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let (at, w, h) = (m.position, f64::from(m.width()), f64::from(m.height())); let options = ParticleOptions::simple(ParticleType::Poof); for _ in 0..20 { let r = self.particles.level_random(); diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 177e3bf80..567067cc2 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -178,7 +178,9 @@ impl Game<'_> { ]; self.tnts.remove(i); count -= 1; - self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?; + self.with_hive_emptying_blast(|g| { + g.server_explode(center, 4.0, BlockInteraction::Destroy, false) + })?; } else { i += 1; } diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 9d6b3f9c5..a5104ee12 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -32,6 +32,8 @@ pub(super) struct ThrownTrident { pub(super) no_physics: bool, returning: u32, creative_only: bool, + /// The guest that threw it (`Projectile.getOwner`); `None` for the host. + guest: Option, } impl ThrownTrident { /// A trident a server sent (`handleAddEntity`): placed and moved by it. @@ -51,6 +53,7 @@ impl ThrownTrident { no_physics: false, returning: 0, creative_only: false, + guest: None, } } /// One tick of a server's client: the previous position, then `step`. @@ -302,11 +305,33 @@ impl Game<'_> { no_physics: false, returning: 0, creative_only: self.creative, + guest: self.lan_acting, }); self.player_projectile_shot(); self.audio .play("minecraft:item.trident.throw", at, 1.0, 1.0); } + /// The thrower's `PLAYER_HURT_ENTITY` for a trident hit: run as the + /// guest that threw it, and not at all once they have left. + fn thrower_hit( + &mut self, + guest: Option, + victim: &horizon_client::advancements::EntityView, + direct: horizon_client::advancements::EntityView, + damage: f32, + ) { + let Some(conn) = guest.filter(|c| self.lan_acting != Some(*c)) else { + self.player_hit(victim, "minecraft:trident", Some(direct), damage); + return; + }; + let Some(mut host) = self.lan.take() else { + return; + }; + self.as_guest(&mut host, conn, |g| { + g.player_hit(victim, "minecraft:trident", Some(direct), damage) + }); + self.lan = Some(host); + } pub(super) fn tick_tridents(&mut self) { let Some(eye) = self.eye_position() else { return; @@ -394,6 +419,18 @@ impl Game<'_> { { self.channel_lightning(at); } + if hurt_at.is_some() + && let Some(m) = self.mobs.iter().find(|m| m.id == id) + { + // LivingEntity.hurtServer: PLAYER_HURT_ENTITY. + let victim = self.mob_entity(m); + let direct = horizon_client::advancements::EntityView { + kind: "minecraft:trident".into(), + position: [t.position.x, t.position.y, t.position.z], + ..Default::default() + }; + self.thrower_hit(t.guest, &victim, direct, damage); + } self.audio.play( "minecraft:item.trident.hit", Some([t.position.x, t.position.y, t.position.z]), diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index f3edfddb3..18430daf6 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -169,6 +169,8 @@ impl Game<'_> { self.consume_held(); } } + // ServerPlayerGameMode.useItemOn: the action was consumed. + self.trigger_block("minecraft:item_used_on_block", pos, &stack); Ok(true) } fn vault_events(&mut self, key: Pos, events: Vec) -> Result<()> { diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index c04b18604..36c79f893 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -148,7 +148,7 @@ impl Game<'_> { // VillagerMakeLove: entity event 13 for the partner, then the parent. for i in [ib, ia] { let id = self.mobs[i].id; - self.villager_particles(id, "angry_villager"); + self.mob_event_particles(id, 13); } return; }; @@ -173,12 +173,31 @@ impl Game<'_> { child.extra.bed = Some(bed); } // VillagerMakeLove.giveBirth: entity event 12 for the child. - self.villager_particles(id, "heart"); + self.mob_event_particles(id, 12); } - /// `Villager.handleEntityEvent` 12, 13, 14 and 42: - /// `AbstractVillager.addParticlesAroundSelf`. - pub(super) fn villager_particles(&mut self, id: u32, kind: &'static str) { - self.particles_around_mob(id, kind, horizon_client::particles::Burst::VILLAGER); + /// `Level.broadcastEntityEvent` of an event whose `handleEntityEvent` + /// draws particles about the mob (villager 12, 13 and 14, taming 6 and 7, + /// love 18): the guests get the byte, and this game draws it as its own + /// client would. + pub(super) fn mob_event_particles(&mut self, id: u32, event: i8) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let at = [m.position.x, m.position.y, m.position.z]; + self.lan_entity_event(id as i32, event, at); + self.entity_event_particles(id, event); + } + /// `handleEntityEvent(event)`'s particles about mob `id` + /// (`Villager`, `TamableAnimal`, `AbstractHorse`, `Animal`, `Allay`). + pub(super) fn entity_event_particles(&mut self, id: u32, event: i8) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + if let Some((kind, burst)) = + horizon_client::particles::entity_event_burst(&m.kind.id, event as u8) + { + self.particles_around_mob(id, kind, burst); + } } /// `particles::around_self` about mob `id`. pub(super) fn particles_around_mob( @@ -315,7 +334,7 @@ impl Game<'_> { } // Villager.setLastHurtByMob: entity event 13. for id in angry { - self.villager_particles(id, "angry_villager"); + self.mob_event_particles(id, 13); } } /// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a @@ -370,7 +389,7 @@ impl Game<'_> { gossip::REPUTATION_CHANGE_PER_TRADE, ); // Villager.customServerAiStep after a trade: entity event 14. - self.villager_particles(id, "happy_villager"); + self.mob_event_particles(id, 14); } /// `Villager.getPlayerReputation` of the local player. pub(super) fn villager_reputation(&self, id: u32) -> i32 { diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index 8084425ca..789e5cf68 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -130,7 +130,7 @@ impl Game<'_> { if let Some(id) = owner { self.note_attacker("minecraft:explosion", id); } - self.explode(at, 1.0) + self.with_hive_emptying_blast(|g| g.explode(at, 1.0)) } } /// Wither skulls drawn as the skull model, blue when dangerous. diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index a98637b5a..d9ff16cde 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -35,10 +35,11 @@ fn entity_shader() -> String { #[cfg(test)] mod crumbling_tests; mod entity_batch; +mod entity_outline; mod weather; use entity_batch::EntityBatch; pub use entity_batch::{ - SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, + ENERGY_SWIRL_OVERLAY, SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, }; @@ -265,6 +266,9 @@ pub struct Frame<'a> { pub nether_lighting: bool, /// Camera-relative entity geometry textured from the shared atlas. pub entities: &'a [Vertex], + /// The glowing entities' silhouettes in their team colours (`OutlineBufferSource`), + /// outlined through walls after the hand. + pub glowing: &'a [Vertex], /// Runs of `entities` by entity, while a shader pack draws them (`pack_draw::EntitySpan`). pub entity_spans: &'a [pack_draw::EntitySpan], pub weather: &'a [crate::weather::Vertex], @@ -407,6 +411,8 @@ pub struct Renderer { cloud_uniform: wgpu::Buffer, cloud_group: wgpu::BindGroup, additive_pipeline: wgpu::RenderPipeline, + /// `RenderPipelines.ENERGY_SWIRL`: additive, unlit, the sprite repeated within itself. + energy_swirl_pipeline: wgpu::RenderPipeline, lightning_pipeline: wgpu::RenderPipeline, lightning: lightning::Renderer, see_through_pipeline: wgpu::RenderPipeline, @@ -414,6 +420,8 @@ pub struct Renderer { celestial_buffer: wgpu::Buffer, end_sky: end_sky::EndSky, stars: stars::Stars, + /// The glowing entities' outline (`LevelRenderer.entityOutlineTarget`). + entity_outline: entity_outline::EntityOutline, panorama: panorama::Panorama, /// `RenderPipelines.WORLD_BORDER` and its buffers. border_pipeline: wgpu::RenderPipeline, @@ -1893,6 +1901,27 @@ impl Renderer { alpha_blend, false, ); + // RenderPipelines.ENERGY_SWIRL: BlendFunction.ADDITIVE (one, one), no culling; no depth + // writes either: vanilla sorts the quads far to near, so every face passes the test. + let one_one = wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::One, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }; + let energy_swirl_pipeline = entity_pipeline_with( + "Energy swirls", + None, + false, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + wgpu::BlendState { + color: one_one, + alpha: one_one, + }, + false, + "fs_energy_swirl", + wgpu::ColorWrites::ALL, + ); let lightning_attributes = wgpu::vertex_attr_array![6=>Float32x3]; let lightning_vertex = [ entity_vertex[0].clone(), @@ -2345,6 +2374,11 @@ impl Renderer { let uploads = upload::Uploads::new(&device); let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); let stars = stars::Stars::new(&device, config.format.remove_srgb_suffix()); + let entity_outline = entity_outline::EntityOutline::new( + &device, + (&entity_shader, &entity_layout, &entity_vertex), + config.format.remove_srgb_suffix(), + ); let panorama = panorama::Panorama::new( &device, &queue, @@ -2410,6 +2444,7 @@ impl Renderer { cloud_uniform, cloud_group, additive_pipeline, + energy_swirl_pipeline, lightning_pipeline, lightning: lightning::Renderer::new(), see_through_pipeline, @@ -2417,6 +2452,7 @@ impl Renderer { celestial_buffer, end_sky: end_sky::EndSky::default(), stars, + entity_outline, panorama, border_pipeline, border_group, @@ -4041,6 +4077,7 @@ impl Renderer { crumbling_quads, translucent_crumbling_quads, water_mask_quads, + swirl_quads, shadow_quads, translucent_particle_quads, translucent_item_quads, @@ -4052,6 +4089,7 @@ impl Renderer { + crumbling_quads + translucent_crumbling_quads + water_mask_quads + + swirl_quads + shadow_quads + translucent_particle_quads + translucent_item_quads; @@ -4115,6 +4153,13 @@ impl Renderer { bytemuck::cast_slice(all_entities), ); } + self.entity_outline.prepare( + &self.device, + &mut self.uploads, + &mut encoder, + frame.glowing, + [self.config.width, self.config.height], + ); if let Some((rotation, brightness)) = frame.stars { self.stars.prepare( &mut self.uploads, @@ -4142,7 +4187,8 @@ impl Renderer { } else { lightning::QUADS }) - .max(weather_quads); + .max(weather_quads) + .max(frame.glowing.len() as u32 / 4); if max_quads > self.index_quads { self.index_quads = max_quads.next_power_of_two(); self.indices = Self::quad_indices(&self.device, self.index_quads); @@ -4633,6 +4679,21 @@ impl Renderer { self.lightning.draw(&mut pass, &frame.lightning); pass.set_bind_group(0, &self.group, &[]); } + if swirl_quads > 0 { + pass.set_pipeline(&self.energy_swirl_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..swirl_quads * 6, + ((entity_quads + + crumbling_quads + + translucent_crumbling_quads + + water_mask_quads) + * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if additive_quads > 0 { pass.set_pipeline(&self.additive_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -4884,6 +4945,13 @@ impl Renderer { 0..1, ); } + // GameRenderer.render: LevelRenderer.blitEntityOutline after the level and the hand. + self.entity_outline.draw( + &mut encoder, + &view_target, + &self.entity_group, + &self.indices, + ); if !frame.screen.is_empty() { let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, @@ -5316,7 +5384,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1, 0, 1, 1, 0]); + assert_eq!(counts, [4, 1, 1, 0, 0, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 08d749b54..a3c114783 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -3,13 +3,18 @@ use super::Vertex; /// Entity materials by a quad's overlay (`Vertex::layer`), in draw order: /// ordinary entities, breaking cracks (11), translucent breaking cracks (12), -/// the boat water mask (13, `RenderPipelines.WATER_MASK`), entity shadows -/// (14, `RenderPipelines.ENTITY_SHADOW`) and translucent-layer particles (15, -/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) +/// the boat water mask (13, `RenderPipelines.WATER_MASK`), energy swirls +/// (34, `RenderPipelines.ENERGY_SWIRL`), entity shadows (14, +/// `RenderPipelines.ENTITY_SHADOW`), translucent-layer particles (15, drawn +/// after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) /// and translucent item quads (32, drawn without depth writes). -const MATERIALS: usize = 7; +const MATERIALS: usize = 8; /// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). pub const WATER_MASK_OVERLAY: u32 = 13; +/// The overlay of energy swirl quads (`RenderTypes.energySwirl`: the charged creeper's and the +/// powered wither's armour). The light bytes carry the sprite's origin and the colour bytes its +/// size (`breaking::stage_light`), the UV the scrolled position in the sprite. +pub const ENERGY_SWIRL_OVERLAY: u32 = 34; /// The overlay of entity shadow quads (`RenderTypes.entityShadow`). pub const SHADOW_OVERLAY: u32 = 14; /// The overlay of translucent-layer particles (`SingleQuadParticle.Layer.translucent`). @@ -49,9 +54,10 @@ impl EntityBatch { 11 => 1, 12 => 2, WATER_MASK_OVERLAY => 3, - SHADOW_OVERLAY => 4, - TRANSLUCENT_PARTICLE_OVERLAY => 5, - TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 6, + ENERGY_SWIRL_OVERLAY => 4, + SHADOW_OVERLAY => 5, + TRANSLUCENT_PARTICLE_OVERLAY => 6, + TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 7, _ => 0, }; self.buckets[material][counts[material]] = index; @@ -103,12 +109,13 @@ mod tests { ) -> (Vec, [u32; MATERIALS]) { let mut combined = Vec::with_capacity(entities.len() + additive.len() + hand.len()); let mut counts = [0; MATERIALS]; - for (i, layer) in [0, 11, 12, 13, 14, 15].into_iter().enumerate() { + for (i, layer) in [0, 11, 12, 13, 34, 14, 15].into_iter().enumerate() { for quad in entities.as_chunks::<4>().0 { let material = match quad[0].layer { 11 => 11, 12 => 12, 13 => 13, + 34 => 34, 14 => 14, 15 => 15, _ => 0, diff --git a/crates/horizon-client/src/gfx/entity_outline.rs b/crates/horizon-client/src/gfx/entity_outline.rs new file mode 100644 index 000000000..748622019 --- /dev/null +++ b/crates/horizon-client/src/gfx/entity_outline.rs @@ -0,0 +1,311 @@ +//! The entity outline (`LevelRenderer.entityOutlineTarget`): the glowing entities' +//! silhouettes in their team colours, drawn without depth so walls do not hide them +//! (`RenderTypes.outline`), the `entity_outline` post chain over them (`entity_sobel`, then +//! `entity_outline_box_blur` across and up), and `LevelRenderer.blitEntityOutline` onto +//! the frame after the hand. +use super::Vertex; + +/// `entityOutlineTarget`'s `GpuFormat.RGBA8_UNORM`. +const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm; + +struct Targets { + size: [u32; 2], + /// `entityOutlineTarget`. + outline: wgpu::TextureView, + /// The chain's `swap` target. + swap: wgpu::TextureView, + /// What each pass reads: the outline (nearest), swap (bilinear), the outline + /// (bilinear), swap (nearest). + groups: [wgpu::BindGroup; 4], +} + +pub(super) struct EntityOutline { + silhouette: wgpu::RenderPipeline, + /// Sobel, blur across, blur up (into `FORMAT`) and the blended blit (onto the frame). + passes: [wgpu::RenderPipeline; 4], + layout: wgpu::BindGroupLayout, + nearest: wgpu::Sampler, + bilinear: wgpu::Sampler, + vertices: wgpu::Buffer, + capacity: u64, + quads: u32, + targets: Option, +} + +impl EntityOutline { + /// `entity` draws the silhouettes with the entity shader's vertex stage and + /// `fs_outline`; `format` is the frame's. + pub(super) fn new( + device: &wgpu::Device, + entity: ( + &wgpu::ShaderModule, + &wgpu::PipelineLayout, + &[Option], + ), + format: wgpu::TextureFormat, + ) -> Self { + let (entity_shader, entity_layout, entity_vertex) = entity; + // RenderPipelines.OUTLINE_NO_CULL: no depth test, the colour replaced. + let silhouette = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Entity outline silhouettes"), + layout: Some(entity_layout), + vertex: wgpu::VertexState { + module: entity_shader, + entry_point: Some("vs_entity"), + compilation_options: Default::default(), + buffers: entity_vertex, + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: entity_shader, + entry_point: Some("fs_outline"), + compilation_options: Default::default(), + targets: &[Some(FORMAT.into())], + }), + multiview_mask: None, + cache: None, + }); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Entity outline"), + source: wgpu::ShaderSource::Wgsl(include_str!("entity_outline.wgsl").into()), + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Entity outline bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Entity outline"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pass = |entry: &str, target: wgpu::ColorTargetState| { + device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some(entry), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_quad"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some(entry), + compilation_options: Default::default(), + targets: &[Some(target)], + }), + multiview_mask: None, + cache: None, + }) + }; + // BlendFunction.ENTITY_OUTLINE_BLIT over the colour only (write mask 7). + let blit = wgpu::ColorTargetState { + format, + blend: Some(wgpu::BlendState { + color: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::SrcAlpha, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, + operation: wgpu::BlendOperation::Add, + }, + alpha: wgpu::BlendComponent { + src_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::One, + operation: wgpu::BlendOperation::Add, + }, + }), + write_mask: wgpu::ColorWrites::COLOR, + }; + let sampler = |label, filter| { + device.create_sampler(&wgpu::SamplerDescriptor { + label: Some(label), + mag_filter: filter, + min_filter: filter, + ..Default::default() + }) + }; + Self { + silhouette, + passes: [ + pass("fs_sobel", FORMAT.into()), + pass("fs_blur_x", FORMAT.into()), + pass("fs_blur_y", FORMAT.into()), + pass("fs_blit", blit), + ], + layout, + nearest: sampler("Entity outline nearest", wgpu::FilterMode::Nearest), + bilinear: sampler("Entity outline bilinear", wgpu::FilterMode::Linear), + vertices: Self::vertex_buffer(device, 256), + capacity: 256, + quads: 0, + targets: None, + } + } + + fn vertex_buffer(device: &wgpu::Device, capacity: u64) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Entity outline vertices"), + size: capacity * std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + } + + /// Uploads this frame's silhouettes (`LevelRenderer.currentFrameRendersEntityOutline` + /// when there are any) and sizes the targets like the window. + pub(super) fn prepare( + &mut self, + device: &wgpu::Device, + uploads: &mut super::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + silhouettes: &[Vertex], + size: [u32; 2], + ) { + self.quads = (silhouettes.len() / 4) as u32; + if self.quads == 0 { + return; + } + let vertices = silhouettes.len() as u64; + if vertices > self.capacity { + self.capacity = vertices.next_power_of_two(); + self.vertices = Self::vertex_buffer(device, self.capacity); + } + uploads.buffer( + encoder, + &self.vertices, + 0, + bytemuck::cast_slice(silhouettes), + ); + if self.targets.as_ref().is_some_and(|t| t.size == size) { + return; + } + let texture = |label| { + device + .create_texture(&wgpu::TextureDescriptor { + label: Some(label), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: FORMAT, + usage: wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()) + }; + let outline = texture("Entity outline"); + let swap = texture("Entity outline swap"); + let group = |view: &wgpu::TextureView, sampler: &wgpu::Sampler| { + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Entity outline pass"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(view), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(sampler), + }, + ], + }) + }; + let groups = [ + group(&outline, &self.nearest), + group(&swap, &self.bilinear), + group(&outline, &self.bilinear), + group(&swap, &self.nearest), + ]; + self.targets = Some(Targets { + size, + outline, + swap, + groups, + }); + } + + /// `LevelRenderer.executeOutline`, the post chain and `blitEntityOutline` onto `frame`. + pub(super) fn draw( + &self, + encoder: &mut wgpu::CommandEncoder, + frame: &wgpu::TextureView, + entity_group: &wgpu::BindGroup, + indices: &wgpu::Buffer, + ) { + let Some(t) = self.targets.as_ref().filter(|_| self.quads > 0) else { + return; + }; + let clear = wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT); + { + let mut pass = begin(encoder, "Entity outline", &t.outline, clear); + pass.set_pipeline(&self.silhouette); + pass.set_bind_group(0, entity_group, &[]); + pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(0, self.vertices.slice(..)); + pass.draw_indexed(0..self.quads * 6, 0, 0..1); + } + // post_effect/entity_outline.json; its last pass only copies swap back to the + // outline target, so the blit reads swap. + let steps = [ + ("Entity outline sobel", &t.swap, clear), + ("Entity outline blur across", &t.outline, clear), + ("Entity outline blur up", &t.swap, clear), + ("Entity outline blit", frame, wgpu::LoadOp::Load), + ]; + for (i, (label, view, load)) in steps.into_iter().enumerate() { + let mut pass = begin(encoder, label, view, load); + pass.set_pipeline(&self.passes[i]); + pass.set_bind_group(0, &t.groups[i], &[]); + pass.draw(0..3, 0..1); + } + } +} + +fn begin<'e>( + encoder: &'e mut wgpu::CommandEncoder, + label: &str, + view: &wgpu::TextureView, + load: wgpu::LoadOp, +) -> wgpu::RenderPass<'e> { + let attachments = [Some(wgpu::RenderPassColorAttachment { + view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load, + store: wgpu::StoreOp::Store, + }, + })]; + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some(label), + color_attachments: &attachments, + ..Default::default() + }) +} diff --git a/crates/horizon-client/src/gfx/entity_outline.wgsl b/crates/horizon-client/src/gfx/entity_outline.wgsl new file mode 100644 index 000000000..bd723f11e --- /dev/null +++ b/crates/horizon-client/src/gfx/entity_outline.wgsl @@ -0,0 +1,60 @@ +// The entity_outline post chain (post_effect/entity_outline.json) over the silhouettes of +// the glowing entities, then RenderTarget.blitAndBlendToTexture onto the frame. +@group(0) @binding(0) var source: texture_2d; +@group(0) @binding(1) var source_sampler: sampler; + +struct PostOut { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +}; + +// screenquad.vsh, with v running down the rows as wgpu's textures do. +@vertex fn vs_quad(@builtin(vertex_index) i: u32) -> PostOut { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: PostOut; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} + +fn tap(uv: vec2) -> vec4 { + return textureSampleLevel(source, source_sampler, uv, 0.0); +} + +// entity_sobel.fsh: alpha marks where coverage changes, the colour is the mean of the +// covered texels around. +@fragment fn fs_sobel(in: PostOut) -> @location(0) vec4 { + let texel = 1.0 / vec2(textureDimensions(source)); + let center = tap(in.uv); + let left = tap(in.uv - vec2(texel.x, 0.0)); + let right = tap(in.uv + vec2(texel.x, 0.0)); + let up = tap(in.uv - vec2(0.0, texel.y)); + let down = tap(in.uv + vec2(0.0, texel.y)); + let total = clamp(abs(center.a - left.a) + abs(center.a - right.a) + + abs(center.a - up.a) + abs(center.a - down.a), 0.0, 1.0); + let color = center.rgb * center.a + left.rgb * left.a + right.rgb * right.a + + up.rgb * up.a + down.rgb * down.a; + return vec4(color * 0.2, total); +} + +// entity_outline_box_blur.fsh at Radius 2: bilinear taps at -1.5 and 0.5 texels and half +// a tap at 2; the colour averaged, the alpha summed. +fn blur(uv: vec2, step: vec2) -> vec4 { + let blurred = tap(uv + step * -1.5) + tap(uv + step * 0.5) + tap(uv + step * 2.0) / 2.0; + return vec4(blurred.rgb / 2.5, blurred.a); +} + +// BlurDir (1, 0). +@fragment fn fs_blur_x(in: PostOut) -> @location(0) vec4 { + return blur(in.uv, vec2(1.0 / f32(textureDimensions(source).x), 0.0)); +} + +// BlurDir (0, 1): up the screen in GL's bottom-up textures, towards row 0 here. +@fragment fn fs_blur_y(in: PostOut) -> @location(0) vec4 { + return blur(in.uv, vec2(0.0, -1.0 / f32(textureDimensions(source).y))); +} + +// blit_screen.fsh, blended by RenderPipelines.ENTITY_OUTLINE_BLIT. +@fragment fn fs_blit(in: PostOut) -> @location(0) vec4 { + return tap(in.uv); +} diff --git a/crates/horizon-client/src/gfx/pack_entities.rs b/crates/horizon-client/src/gfx/pack_entities.rs index ab3c66c69..c6bcd8beb 100644 --- a/crates/horizon-client/src/gfx/pack_entities.rs +++ b/crates/horizon-client/src/gfx/pack_entities.rs @@ -405,12 +405,12 @@ pub(super) fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { } /// Whether a run holds only geometry a gbuffers program can draw from the shared atlas: no -/// celestial body, cloud, beam, End portal or crack (overlay codes Horizon's entity shader -/// draws in its own way; entity.wgsl). +/// celestial body, cloud, beam, End portal, crack or energy swirl (overlay codes Horizon's entity +/// shader draws in its own way; entity.wgsl). fn plain(run: &[Vertex]) -> bool { run.iter() .step_by(4) - .all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12)) + .all(|v| !matches!(v.layer, 2 | 4 | 6 | 9 | 10 | 11 | 12 | 34)) } /// The programs of entity runs, in the order they draw. diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 31e4e8104..c0e7be5c8 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -180,6 +180,12 @@ pub struct PlayerHealth { pub hurt: State, /// Client hurt animation; fully blocked hits only refresh the server's hurt state. pub hurt_animation_time: i32, + /// `Player.hurtDir` on a client: the yaw `ClientboundHurtAnimationPacket` + /// gave, which `GameRenderer.bobHurt` tilts the camera around. + pub hurt_dir: f32, + /// `ServerPlayer.hurtDir` of a hit the player's client hasn't been told + /// of yet (`indicateDamage`). + pub indicated_dir: Option, pub dead: bool, pub sync_velocity: bool, pub game_time: i64, @@ -230,6 +236,8 @@ impl PlayerHealth { last_stamp: 0, }, hurt_animation_time: 0, + hurt_dir: 0.0, + indicated_dir: None, dead: false, sync_velocity: false, game_time: 0, @@ -277,6 +285,18 @@ impl PlayerHealth { self.hurt.hurt_time = 10; self.hurt_animation_time = 10; } + /// `LivingEntity.animateHurt(yaw)` on a player: the tilt restarts around + /// `yaw` (`Player.animateHurt` keeps it as `hurtDir`). + pub fn animate_hurt_dir(&mut self, yaw: f32) { + self.animate_hurt(); + self.hurt_dir = yaw; + } + /// `ServerPlayer.indicateDamage`: the hit's direction relative to where + /// the player looks, kept for the packet to its client. + pub fn indicate_damage(&mut self, xd: f64, zd: f64, yaw: f32) { + use horizon_core::geometry::trig::{RAD_TO_DEG, atan2}; + self.indicated_dir = Some((atan2(zd, xd) * f64::from(RAD_TO_DEG) - f64::from(yaw)) as f32); + } /// `LocalPlayer.hurtTo` with `flashOnSetHealth`: a drop below the current /// health starts the hurt animation; `damageCooldownTime` (20 on a drop, /// 10 on a gain) is what lets `Hud.extractPlayerHealth` blink the hearts. @@ -380,6 +400,13 @@ impl PlayerMotion { if outcome.hurt { h.hurt_animation_time = h.hurt.hurt_time; } + // `dealDefaultKnockback` ends in `indicateDamage` unless blocked: a + // hit with no direction of its own (`xd` and `zd` zero) is sent as + // the opposite of the player's yaw. A hit that has a direction + // replaces this (`mob_hits_player`). + if outcome.knockback && outcome.blocked <= 0.0 { + h.indicate_damage(0.0, 0.0, self.yaw); + } let after = h.health() + h.absorption(); if self.hurt_log.len() >= HURT_LOG { self.hurt_log.remove(0); diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 323b1dd70..8dabae0bb 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -796,6 +796,33 @@ pub fn cluster_poses(state: &ItemRenderState, pose: Mat4, amount: u32, seed: i64 mod tests { use super::*; + /// A bad item model surfaces only once items.json has loaded, so a broken + /// items.json still reports itself first. + #[test] + fn item_model_errors_wait_for_the_item_definitions() -> crate::Result<()> { + let root = + std::env::temp_dir().join(format!("horizon-item-model-errors-{}", std::process::id())); + let model = root.join("assets/horizon/models/INVALID.json"); + fs::create_dir_all(model.parent().unwrap())?; + fs::write(model, "{}")?; + let library = crate::model_library::ParsedModels::load(&root).into_item_library(); + assert!(library.is_err()); + fs::write(root.join("items.json"), "{")?; + let load = || { + ItemRenderer::load_with_library(&root, library.clone()) + .err() + .unwrap() + .to_string() + }; + let broken_items = load(); + fs::write(root.join("items.json"), "{}")?; + let bad_model = load(); + let _ = fs::remove_dir_all(&root); + assert!(!broken_items.starts_with("item models:")); + assert!(bad_model.starts_with("item models:")); + Ok(()) + } + #[test] fn rendered_amounts_follow_the_count_bands() { let bands: Vec = [0, 1, 2, 16, 17, 32, 33, 48, 49, 64] diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index dc023f756..445ebcdad 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -499,7 +499,7 @@ pub(super) fn submit( let skin = (!argument.is_null()) .then(|| host.player_skin(argument)) .flatten() - .unwrap_or_else(|| "entity/player/wide/steve".to_owned()); + .unwrap_or_else(|| "entity/player/slim/steve".to_owned()); part("player", &none, &skin, white, Foil::None); } SpecialKind::Trident => { diff --git a/crates/horizon-client/src/item_sync.rs b/crates/horizon-client/src/item_sync.rs index fc35e15e7..01d90246f 100644 --- a/crates/horizon-client/src/item_sync.rs +++ b/crates/horizon-client/src/item_sync.rs @@ -229,6 +229,17 @@ fn profile_tag(p: &Profile) -> Tag { if let Some(name) = &p.name { entries.push(("name", Tag::String(name.as_str().into()))); } + if let Some(id) = p.id { + entries.push(( + "id", + Tag::IntArray(vec![ + (id >> 96) as i32, + (id >> 64) as i32, + (id >> 32) as i32, + id as i32, + ]), + )); + } entries.push(("properties", Tag::List(properties))); Tag::compound(entries) } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 5ccdd0a65..1962b0d35 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -66,6 +66,7 @@ pub mod spawning; pub mod species; pub mod strider; pub mod sulfur_cube; +pub mod sync; pub mod tame; pub mod trader; pub mod transport_items; @@ -802,6 +803,8 @@ pub struct Extra { pub memories: Vec<(&'static str, i64, i64)>, /// A camel's `LAST_POSE_CHANGE_TICK`. pub pose_change_tick: i64, + /// `Entity.DATA_POSE` as a mob of a server has it (`sync::pose_id`). + pub pose: u8, /// The school leader a fish follows, and a tropical fish that swims alone. pub leader: Option, pub lone: bool, @@ -845,6 +848,9 @@ pub struct Mob { pub previous_swell: i32, pub ambient_timer: i32, pub fall_distance: f64, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this mob this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub persistent: bool, /// `CustomName` (plain text) and `CustomNameVisible`. pub custom_name: Option, @@ -917,6 +923,12 @@ pub enum MobEvent { mob: u32, at: [f64; 3], }, + /// `Level.broadcastEntityEvent` for a mob: guests run `sync::entity_event`. + EntityEvent { + mob: u32, + event: i8, + at: [f64; 3], + }, Sound(&'static str, [f64; 3], f32, f32), /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the /// chest's opener count goes up or down (interaction range 3). @@ -1023,7 +1035,9 @@ pub enum MobEvent { mob: u32, charged: bool, }, - Explode([f64; 3], f32), + /// The centre, the radius and the kind of the mob blowing up (it may be + /// gone from the list by the time the blast is handled). + Explode([f64; 3], f32, Species), /// Melee or ranged damage to another mob. AttackMob { target: u32, @@ -1087,8 +1101,11 @@ pub enum MobEvent { at: [f64; 3], count: u32, }, - /// Client particles about a mob's box (`particles::around_self`). + /// Client particles about a mob's box (`particles::around_self`) and the + /// entity event `event` that shows them, sent for mob `mob`. AroundSelf { + mob: u32, + event: i8, kind: &'static str, feet: [f64; 3], width: f64, @@ -1216,6 +1233,12 @@ pub enum MobEvent { table: &'static str, at: [f64; 3], }, + /// `Armadillo.customServerAiStep`: the armadillo sheds a scute. + ShedScute { + mob: u32, + at: [f64; 3], + pitch: f32, + }, /// A lead snaps or loses its holder: the lead item drops when asked. LeashBreak { mob: u32, @@ -1572,6 +1595,8 @@ pub struct PlayerView { pub off_hand: Option>, pub head: Option>, pub armor_cover: f32, + /// The Invisibility effect (`isInvisible`). + pub invisible: bool, pub spectator: bool, /// `PiglinAi.isWearingSafeArmor`: some golden armour. pub gold_armor: bool, @@ -1597,6 +1622,17 @@ pub struct PlayerView { pub passenger: bool, } impl PlayerView { + /// `LivingEntity.getVisibilityPercent` without the worn-skull scaling. + pub fn visibility_percent(&self) -> f64 { + let mut visibility = 1.0; + if self.sneaking { + visibility *= 0.8; + } + if self.invisible { + visibility *= 0.7 * f64::from(self.armor_cover).max(0.1); + } + visibility + } /// `LivingEntity.hasEffect`, by id without namespace. pub fn has_effect(&self, effect: &str) -> bool { self.effects.contains(&effect) @@ -1607,6 +1643,8 @@ pub struct MobWorld<'a> { pub world: &'a World, pub registry: &'a horizon_world::registry::BlockRegistry, pub facts: &'a BlockFacts, + /// Fluid states and flow facts, for the currents that push mobs. + pub fluid_tables: &'a crate::motion::FluidResources, pub movement: &'a horizon_world::movement_properties::BoundMovementProperties, pub collision: &'a BlockCollisionRegistry<'a>, pub data: &'a MobData, @@ -1629,6 +1667,8 @@ pub struct MobWorld<'a> { pub biomes: &'a crate::biome::Biomes, /// The `mob_griefing` game rule. pub mob_griefing: bool, + /// The `mob_drops` game rule (`shouldDropLoot`). + pub mob_drops: bool, /// `getCurrentDifficultyAt` near the player. pub difficulty: spawning::LocalDifficulty, /// The End (its dimension type's monster spawn light rules). @@ -1695,6 +1735,7 @@ impl Mob { // Mob.ambientSoundTime starts at 0. ambient_timer: 0, fall_distance: 0.0, + piston: Default::default(), persistent: false, random, ai: Box::default(), @@ -1925,7 +1966,7 @@ impl Mob { let dead = !self.alive(); let sound = ai::voice_sounds(self)[if dead { 2 } else { 1 }]; if !dead { - self.ambient_timer = -self.kind.ambient_interval; + self.ambient_timer = -self.ambient_interval(); } if !sound.is_empty() { let pitch = self.voice_pitch(); @@ -2006,16 +2047,21 @@ impl Mob { pub fn has_effect(&self, effect: &str) -> bool { self.extra.effects.iter().any(|e| e.0 == effect) } + /// `LivingEntity.isCurrentlyGlowing`: the Glowing effect or the `Glowing` tag (on a + /// server's client, `glowing` holds shared flag 6 instead). + pub fn is_currently_glowing(&self) -> bool { + self.glowing || self.has_effect("minecraft:glowing") + } pub fn add_effect(&mut self, effect: &'static str, ticks: i32, amplifier: i32) { if let Some(e) = self.extra.effects.iter_mut().find(|e| e.0 == effect) { - // MobEffectInstance.update: a stronger effect replaces the old one - // with its own duration, an equal one keeps the longer duration, - // and a weaker one never changes the active effect. + // MobEffectInstance.update: a stronger effect replaces with its + // own duration, an equal one only extends it; a weaker one is + // ignored (vanilla keeps it hidden behind the active one). if amplifier > e.2 { e.1 = ticks; e.2 = amplifier; - } else if amplifier == e.2 { - e.1 = e.1.max(ticks); + } else if amplifier == e.2 && e.1 != -1 && (ticks == -1 || e.1 < ticks) { + e.1 = ticks; } } else { self.extra.effects.push((effect, ticks, amplifier)); @@ -2035,6 +2081,16 @@ impl Mob { let at = [self.position.x, self.eye_y(), self.position.z]; events.push(MobEvent::Sound(event, at, 1.0, 1.0)); } + /// `Mob.getAmbientSoundInterval`; `HappyGhast` waits six times as long + /// while it carries a passenger. + pub fn ambient_interval(&self) -> i32 { + let ridden = self.rider.is_some() || self.extra.rider.is_some(); + if self.species() == Species::HappyGhast && ridden { + self.kind.ambient_interval * 6 + } else { + self.kind.ambient_interval + } + } /// LivingEntity.getVoicePitch. pub fn voice_pitch(&mut self) -> f32 { // HappyGhast.getVoicePitch: always 1.0, babies and all. diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 13dbe8dc4..a0d0b84ca 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -353,6 +353,10 @@ fn generic(m: &mut Mob) { g.add(5, Stroll::avoiding_water(if rabbit { 0.6 } else { 1.0 })); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); + if m.kind.species == Species::Armadillo { + // Armadillo's constructor: pickNextScuteDropTime. + m.extra.egg_time = next_scute_time(m); + } } } /// Subclasses of `net.minecraft.world.entity.monster.Monster`. @@ -635,7 +639,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let t = m.ambient_timer; m.ambient_timer += 1; if roll < t { - m.ambient_timer = -m.kind.ambient_interval; + m.ambient_timer = -m.ambient_interval(); play_ambient(m, w, events); } } @@ -1080,9 +1084,31 @@ fn server_ai_step( } m.jump_control_tick(); } +/// `Armadillo.pickNextScuteDropTime`: 5 to 10 minutes. +fn next_scute_time(m: &mut Mob) -> i32 { + m.random.next_int_bound(20 * 60 * 5).unwrap_or(0) + 20 * 60 * 5 +} +/// `Armadillo.customServerAiStep`: the scute timer keeps counting down and is +/// only reset once `shouldDropLoot` (not a baby, `mob_drops` on) lets it shed. +fn armadillo_server_ai_step(m: &mut Mob, mob_drops: bool, events: &mut Vec) { + if !m.alive() { + return; + } + m.extra.egg_time -= 1; + if m.extra.egg_time <= 0 && !m.is_baby() && mob_drops { + let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0; + events.push(MobEvent::ShedScute { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + pitch, + }); + m.extra.egg_time = next_scute_time(m); + } +} fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) { match m.species() { Species::Rabbit => super::rabbit::server_ai_step(m), + Species::Armadillo => armadillo_server_ai_step(m, cx.w.mob_drops, cx.events), Species::Sheep => {} Species::Zombie | Species::Husk @@ -1682,25 +1708,31 @@ fn tick_effects(m: &mut Mob) { let mut effects = std::mem::take(&mut m.extra.effects); for (effect, ticks, amp) in &mut effects { let interval = |base: i32| (base >> (*amp).max(0)).max(1); + // MobEffectInstance.tickServer: an infinite (-1) effect times its + // ticks by the mob's tickCount and never counts down. + let infinite = *ticks == -1; + let count = if infinite { m.age as i32 } else { *ticks }; match *effect { "minecraft:poison" - if *ticks % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => + if count % interval(25) == 0 && !m.kind.flags.undead && m.health > 1.0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } - "minecraft:wither" if *ticks % interval(40) == 0 => { + "minecraft:wither" if count % interval(40) == 0 => { m.damage(1.0, Damage::of(DamageKind::Magic)); } "minecraft:regeneration" - if *ticks % interval(50) == 0 && !m.kind.flags.undead && m.alive() => + if count % interval(50) == 0 && !m.kind.flags.undead && m.alive() => { m.health = (m.health + 1.0).min(m.attrs.max_health); } _ => {} } - *ticks -= 1; + if !infinite { + *ticks -= 1; + } } - effects.retain(|e| e.1 > 0); + effects.retain(|e| e.1 > 0 || e.1 == -1); m.extra .hidden_effects .retain(|h| effects.iter().any(|e| e.0 == *h)); diff --git a/crates/horizon-client/src/mobs/animal_brain.rs b/crates/horizon-client/src/mobs/animal_brain.rs index bd0eb9c90..d928c34ee 100644 --- a/crates/horizon-client/src/mobs/animal_brain.rs +++ b/crates/horizon-client/src/mobs/animal_brain.rs @@ -625,8 +625,7 @@ fn targetable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { // TargetingConditions.forNonCombat(): in range (scaled by the // player's visibility, at least 2) and in sight. let Some(p) = &w.player else { return false }; - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let r = (range * visibility).max(2.0); + let r = (range * p.visibility_percent()).max(2.0); p.alive && !p.spectator && m.distance_sqr(p.position) <= r * r && m.sees(w, who) } Who::Mob(id) => { diff --git a/crates/horizon-client/src/mobs/breeze.rs b/crates/horizon-client/src/mobs/breeze.rs index 5d78fa8ab..dee48f3d0 100644 --- a/crates/horizon-client/src/mobs/breeze.rs +++ b/crates/horizon-client/src/mobs/breeze.rs @@ -31,6 +31,28 @@ pub fn pose(m: &Mob) -> u8 { pub(super) fn set_pose(m: &mut Mob, pose: u8) { m.extra.variant3 = pose; } +/// `Pose.id` of the pose (`sync::pose_id`), and its inverse. +pub fn pose_id(m: &Mob) -> u8 { + match pose(m) { + SHOOTING => 16, + INHALING => 17, + LONG_JUMPING => 6, + SLIDING => 15, + _ => 0, + } +} +pub(super) fn set_pose_id(m: &mut Mob, id: u8) { + set_pose( + m, + match id { + 16 => SHOOTING, + 17 => INHALING, + 6 => LONG_JUMPING, + 15 => SLIDING, + _ => STANDING, + }, + ); +} /// `Breeze.getFiringYPosition`. pub fn firing_y(m: &Mob) -> f64 { m.position.y + f64::from(m.height()) / 2.0 + f64::from(0.3_f32) diff --git a/crates/horizon-client/src/mobs/camel.rs b/crates/horizon-client/src/mobs/camel.rs index 21ebe9e16..427b4c5ca 100644 --- a/crates/horizon-client/src/mobs/camel.rs +++ b/crates/horizon-client/src/mobs/camel.rs @@ -24,12 +24,13 @@ pub fn register(m: &mut Mob) { m.extra.tame = true; let tempt = m.kind.tempt.clone(); let g = &mut m.ai.goals; + // CamelAi speed modifiers (times the 0.09 movement speed attribute). g.add(0, Float); - g.add(1, CamelPanic(Panic::new(4.0 * 0.25))); + g.add(1, CamelPanic(Panic::new(4.0))); g.add(2, Breed::new(1.0)); - g.add(3, Tempt::new(2.5 * 0.25, tempt, false)); - g.add(4, FollowParent::new(2.5 * 0.25)); - g.add(5, Stroll::new(2.0 * 0.25)); + g.add(3, Tempt::new(2.5, tempt, false)); + g.add(4, FollowParent::new(2.5)); + g.add(5, Stroll::new(2.0)); g.add(5, RandomSitting); g.add(6, LookAtPlayer::new(6.0)); g.add(7, RandomLookAround::default()); @@ -45,6 +46,25 @@ pub fn sitting(m: &Mob) -> bool { fn in_transition(m: &Mob) -> bool { pose_time(m) < if sitting(m) { SIT_DOWN } else { STAND_UP } } +/// `Camel.getPoseTime` of a client mob from the `LAST_POSE_CHANGE_TICK` it +/// was sent and the client's game time, and whether that value says it sits. +fn client_pose(m: &Mob, game_time: i64) -> (i64, bool) { + let tick = m.extra.pose_change_tick; + (game_time - tick.abs(), tick < 0) +} +/// The camel's `LAST_POSE_CHANGE_TICK` as the server sends it: in game time +/// (a mob counts its own age), negative while sitting. +pub fn synced_pose_tick(m: &Mob, game_time: i64) -> i64 { + let tick = (game_time - pose_time(m)).max(0); + if sitting(m) { -tick.max(1) } else { tick } +} +/// `Entity.onSyncedDataUpdated` for the pose tick of a client mob: its sign +/// is whether it sits. `client_tick` keeps `egg_time` (in the mob's age, for +/// `sitting` and `refuse_to_move`) with it. +pub fn set_synced_pose_tick(m: &mut Mob, tick: i64) { + m.extra.pose_change_tick = tick; + m.extra.egg_time = if tick < 0 { -1 } else { 0 }; +} /// `Camel.refuseToMove`: sitting or getting up or down. pub fn refuse_to_move(m: &Mob) -> bool { sitting(m) || in_transition(m) @@ -166,7 +186,29 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.ai.zza = 0.0; m.ai.nav.stop(); } - // setupAnimationStates. + animation_states(m, pose_time(m), sitting(m)); +} +/// `Camel.tick` on a client that is not the server: the dash cooldown, which +/// the dash flag starts, and the keyframe states from the synced pose tick. +pub fn client_tick(m: &mut Mob, game_time: i64) { + if m.extra.anim_ticks > 0 { + m.extra.anim_ticks -= 1; + } + let (pose_time, sitting) = client_pose(m, game_time); + let since = (i64::from(m.age) - pose_time).max(0) as i32; + m.extra.egg_time = if sitting { -since.max(1) } else { since }; + animation_states(m, pose_time, sitting); +} +/// `Camel.onSyncedDataUpdated(DASH)`: a dash starts the cooldown unless it +/// runs. Not on the first tick. +pub fn set_dashing(m: &mut Mob, dashing: bool) { + if m.age > 0 && m.extra.anim_ticks == 0 { + m.extra.anim_ticks = DASH_COOLDOWN; + } + m.extra.flag2 = dashing; +} +/// `Camel.setupAnimationStates` for a pose time and whether it sits. +fn animation_states(m: &mut Mob, pose_time: i64, sitting: bool) { let age = m.age as f32; if m.extra.ints[0] <= 0 { m.extra.ints[0] = m.random.next_int_bound(40).unwrap_or(0) + 80; @@ -175,9 +217,9 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { m.extra.ints[0] -= 1; } // isCamelVisuallySitting: (poseTime < 0) != sitting. - let visually_sitting = (pose_time(m) < 0) != sitting(m); - let sitting_down = sitting(m) && pose_time(m) < SIT_DOWN && pose_time(m) >= 0; - let transition = in_transition(m) && pose_time(m) >= 0; + let visually_sitting = (pose_time < 0) != sitting; + let sitting_down = sitting && (0..SIT_DOWN).contains(&pose_time); + let transition = (0..if sitting { SIT_DOWN } else { STAND_UP }).contains(&pose_time); let dashing = m.extra.flag2; let st = &mut m.anim.states; if visually_sitting { diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 3d9709ac4..6704246de 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -588,24 +588,38 @@ impl Mob { if p.creative || p.allies.contains(&self.id) { return false; } - self.player_in_range(w, range, check_sight) + self.player_in_range(w, range, check_sight, true) + } + /// forCombat().ignoreInvisibilityTesting() for the player: the check for + /// a target the mob already has, which ignores the visibility scaling. + pub fn can_keep_target_player(&mut self, w: &MobWorld, range: f64) -> bool { + let Some(p) = &w.player else { return false }; + if p.creative || p.allies.contains(&self.id) { + return false; + } + self.player_in_range(w, range, true, false) } /// TargetingConditions.forNonCombat().range(range).test for the player /// (seen by anyone, within range scaled by visibility, in sight). pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool { - self.player_in_range(w, range, true) + self.player_in_range(w, range, true, true) } - fn player_in_range(&mut self, w: &MobWorld, range: f64, check_sight: bool) -> bool { + /// `scale` is `TargetingConditions.testInvisible`: scale the range by + /// the player's visibility. + fn player_in_range( + &mut self, + w: &MobWorld, + range: f64, + check_sight: bool, + scale: bool, + ) -> bool { let Some(p) = &w.player else { return false }; if !p.alive || p.spectator { return false; } // LivingEntity.getVisibilityPercent - let mut visibility = 1.0; - if p.sneaking { - visibility *= 0.8; - } - if let Some(head) = &p.head { + let mut visibility = if scale { p.visibility_percent() } else { 1.0 }; + if let Some(head) = p.head.as_ref().filter(|_| scale) { let skull = match self.species() { Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager => { "minecraft:zombie_head" diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index 296644acc..418556750 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -364,8 +364,7 @@ impl Goal for GhastTempt { let Some(p) = &cx.w.player else { return false }; // getNearestPlayer(TargetingConditions.forNonCombat() // .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too. - let visibility = if p.sneaking { 0.8 } else { 1.0 }; - let range = (16.0_f64 * visibility).max(2.0); + let range = (16.0_f64 * p.visibility_percent()).max(2.0); p.alive && !p.spectator && (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand)) diff --git a/crates/horizon-client/src/mobs/hostile.rs b/crates/horizon-client/src/mobs/hostile.rs index f1c990c48..34dc256f9 100644 --- a/crates/horizon-client/src/mobs/hostile.rs +++ b/crates/horizon-client/src/mobs/hostile.rs @@ -184,6 +184,7 @@ pub fn creeper_tick(m: &mut Mob, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y, m.position.z], radius, + m.species(), )); m.removed = true; } diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 6c6923c32..fa9725075 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -9,8 +9,15 @@ use crate::{ }; use horizon_core::{ geometry::{Aabb, Vec3, trig}, + position::BlockPos, random::RandomSource, }; +use horizon_world::{ + entity_fluid::{CurrentAccumulator, CurrentTarget}, + fluid::{FluidKind, FluidState}, + fluid_flow::{FluidFlowWorld, flow_at}, + registry::BlockStateId, +}; /// `Entity.moveDist`, `flyDist` and `nextStep`. #[derive(Clone, Copy, Debug)] @@ -36,6 +43,50 @@ pub struct Fluids { pub in_lava: bool, pub eye_in_water: bool, } +/// `FluidFlowWorld` over the mob's scene: the neighbours a flow vector reads. +struct FlowScene<'a, 'w>(&'a MobWorld<'w>); +impl FluidFlowWorld for FlowScene<'_, '_> { + type Error = std::convert::Infallible; + type Block = BlockStateId; + fn fluid(&mut self, p: BlockPos) -> Result { + Ok(self.0.fluid_tables.fluid(self.0.world.block(p.x, p.y, p.z))) + } + fn block(&mut self, p: BlockPos) -> Result { + Ok(self.0.world.block(p.x, p.y, p.z)) + } + fn blocks_fluid_flow(&self, s: BlockStateId) -> bool { + self.0.fluid_tables.blocks_flow(s) + } + fn is_ice_class(&self, s: BlockStateId) -> bool { + self.0.fluid_tables.ice(s) + } + fn is_face_sturdy( + &mut self, + s: BlockStateId, + _: BlockPos, + d: horizon_core::geometry::Direction, + ) -> Result { + Ok(self.0.fluid_tables.sturdy(s, d)) + } +} +/// The mob's velocity, for `CurrentAccumulator::apply_to`. +struct Pushed<'a>(&'a mut Vec3); +impl CurrentTarget for Pushed<'_> { + type Error = std::convert::Infallible; + fn is_player_class(&self) -> bool { + false + } + fn velocity(&mut self) -> Result { + Ok(*self.0) + } + fn add_delta_movement(&mut self, delta: Vec3) -> Result<(), Self::Error> { + let sum = Vec3::new(self.0.x + delta.x, self.0.y + delta.y, self.0.z + delta.z); + if delta.is_finite() && sum.is_finite() { + *self.0 = sum; + } + Ok(()) + } +} pub fn wrap(a: f32) -> f32 { let mut a = a % 360.0; if a >= 180.0 { @@ -140,6 +191,40 @@ impl MobWorld<'_> { } out } + /// Entity.updateFluidHeightAndDoFluidPushing's currents over the deflated + /// box: the flow of every water and lava block it touches, summed (a thin + /// fluid layer scales its flow down), as (water, lava). + fn fluid_currents(&self, bounds: Aabb) -> (CurrentAccumulator, CurrentAccumulator) { + let base_y = bounds.min_position().y; + let b = bounds.deflate(Vec3::new(0.001, 0.001, 0.001)); + let (lo, hi) = (b.min_position(), b.max_position()); + let mut scene = FlowScene(self); + let (mut water, mut lava) = (CurrentAccumulator::default(), CurrentAccumulator::default()); + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + let p = BlockPos::new(x, y, z); + let state = self.fluid_tables.fluid(self.world.block(x, y, z)); + let current = match state.kind() { + FluidKind::Empty => continue, + FluidKind::Water | FluidKind::FlowingWater => &mut water, + FluidKind::Lava | FluidKind::FlowingLava => &mut lava, + }; + let surface = f64::from(y) + self.fluid_height(x, y, z).1; + if surface < lo.y { + continue; + } + current.height = current.height.max(surface - base_y); + let mut flow = flow_at(&mut scene, state, p).unwrap_or(Vec3::ZERO); + if current.height < 0.4 { + flow = flow.scale(current.height); + } + current.accumulate(flow); + } + } + } + (water, lava) + } /// `BlockState.getCollisionShape(level, pos)` (the empty collision /// context) as boxes in the world. pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec { @@ -363,6 +448,27 @@ impl Mob { pub fn is_in_liquid(&self) -> bool { self.fluids.in_water || self.fluids.in_lava } + /// `Entity.isPushedByFluid`: water animals, turtles, axolotls, frogs and + /// nautiluses keep their own course. + fn pushed_by_fluid(&self) -> bool { + use super::Species as S; + !matches!( + self.species(), + S::Tadpole + | S::Cod + | S::Salmon + | S::TropicalFish + | S::Pufferfish + | S::Squid + | S::GlowSquid + | S::Dolphin + | S::Turtle + | S::Axolotl + | S::Frog + | S::Nautilus + | S::ZombieNautilus + ) + } fn affected_by_fluids(&self) -> bool { true } @@ -457,6 +563,17 @@ impl Mob { // Entity.checkSupportingBlock self.supporting = self.supporting_block(w, moved); self.movement_emission(w, moved, events); + // Entity.applyEffectsFromBlocks: bubble columns push the mob. + if crate::motion::bubble_column_push( + w.world, + w.registry, + w.facts, + w.collision, + self.bounds(), + &mut self.velocity, + ) { + self.fall_distance = 0.0; + } } /// LivingEntity.checkFallDamage: the fluid state refreshed out of water /// (touching water resets the fall), then Entity.checkFallDamage. @@ -479,6 +596,22 @@ impl Mob { pub(super) fn update_fluids(&mut self, w: &MobWorld, events: &mut Vec) { let was_touching_water = self.fluids.in_water; self.fluids = w.fluids(self.bounds(), self.eye_y()); + // EntityFluidInteraction.applyCurrentTo: the flow pushes the mob. + if (self.fluids.in_water || self.fluids.in_lava) && self.pushed_by_fluid() { + let (water, lava) = w.fluid_currents(self.bounds()); + let lava_scale = if w.nether { + 0.007 + } else { + 0.0023333333333333335 + }; + let mut pushed = Pushed(&mut self.velocity); + if water.height > 0.0 { + let _ = water.apply_to(&mut pushed, 0.014); + } + if lava.height > 0.0 { + let _ = lava.apply_to(&mut pushed, lava_scale); + } + } if self.fluids.in_water { self.fall_distance = 0.0; if !was_touching_water && !self.first_tick { diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index 827360406..8be270ec1 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -359,11 +359,14 @@ fn can_attack(m: &Mob, w: &MobWorld, who: Who) -> bool { /// `Sensor.isEntityAttackable`: `TargetingConditions.forCombat()` within the /// follow range, in sight. fn attackable(m: &mut Mob, w: &MobWorld, who: Who) -> bool { + // The current ATTACK_TARGET is tested with ignoreInvisibilityTesting. + let current = mem_ref(m).attack_target.value() == Some(who); let range = m.attrs.follow_range; if !can_attack(m, w, who) { return false; } match who { + Who::Player if current => m.can_keep_target_player(w, range), Who::Player => m.can_target_player(w, range, true), Who::Mob(id) => { let Some(s) = w.seen(id) else { return false }; diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 46eb14cc1..30c40302e 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -664,14 +664,6 @@ pub fn layers(m: &Mob) -> Vec { white, false, ), - // EnergySwirlLayer (the scroll is not reproduced: atlas sprites do not wrap). - S::Creeper if m.extra.charged => push( - &mut v, - "creeper#armor", - "entity/creeper/creeper_armor", - 0x80FF_FFFF, - true, - ), S::TropicalFish => { // TropicalFishPatternLayer: the pattern tinted with the pattern colour. let (model, letter, n) = if m.extra.variant < 6 { @@ -1226,10 +1218,50 @@ fn render_visible( } } } + // EnergySwirlLayer: the armour model, additive, scrolling over the sprite. + if let Some((model, texture, x_offset)) = energy_swirl(m, s.age) + && let Some(part) = m.kind.layer(model) + && let Some([u0, v0, u1, v1]) = atlas(texture) + { + layer_poses.reset(part); + anim::setup(m, &s, &mut layer_poses, &data.animations); + // `RenderTypes.energySwirl`'s texture offset, as the sprite-local UV. + let (du, dv) = (x_offset % 1.0, s.age * 0.01 % 1.0); + let start = out.len(); + draw( + part, + base, + &layer_poses, + [du, dv, 1.0 + du, 1.0 + dv], + crate::breaking::stage_light([u1 - u0, v1 - v0]), + crate::breaking::stage_light([u0, v0]), + crate::gfx::ENERGY_SWIRL_OVERLAY, + out, + ); + // No lighting: the colour bytes carry the sprite's size (fs_energy_swirl). + for vertex in &mut out[start..] { + vertex.normal = [0; 4]; + } + } if shell_last { draw_body(out); } } +/// `EnergySwirlLayer`'s model, texture and `xOffset(t)` for a charged creeper +/// (`CreeperPowerLayer`) or a powered wither (`WitherArmorLayer`); `t` is `ageInTicks`. +fn energy_swirl(m: &Mob, t: f32) -> Option<(&'static str, &'static str, f32)> { + match m.species() { + Species::Creeper if m.extra.charged => { + Some(("creeper#armor", "entity/creeper/creeper_armor", t * 0.01)) + } + Species::Wither if super::wither::powered(m) => Some(( + "wither#armor", + "entity/wither/wither_armor", + (t * 0.02).mcos() * 3.0, + )), + _ => None, + } +} /// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`). fn armor_slot(model: &str) -> Option { Some(match model.rsplit('#').next()? { diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 32f952e15..c510409d9 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -325,6 +325,13 @@ pub fn look_yaw(m: &Mob, at: [f64; 3]) -> Option { f64::from(delta_forward), )) } +/// `Shulker.tick` on a client that is not the server: the lid eases to the +/// peek it was sent, and its body stays square (`ShulkerBodyRotationControl`). +pub fn client_tick(m: &mut Mob) { + m.anim.vo = m.anim.v; + ease_peek(m); + m.body_yaw = 0.0; +} /// `Shulker.hurtServer` before the damage: arrows bounce off a closed shell. pub fn accepts(m: &Mob, source: &Damage) -> bool { !(m.extra.counter == 0 && source.kind == DamageKind::Arrow) diff --git a/crates/horizon-client/src/mobs/sniffer.rs b/crates/horizon-client/src/mobs/sniffer.rs index c0c8d8155..72aa76cc2 100644 --- a/crates/horizon-client/src/mobs/sniffer.rs +++ b/crates/horizon-client/src/mobs/sniffer.rs @@ -74,23 +74,8 @@ pub fn head_block(m: &Mob) -> [i32; 3] { /// the dropped seed and the water malus. pub fn ai_step(m: &mut Mob, events: &mut Vec) { use super::path::PathType; - let age = m.age as f32; let current = state(m); - if current != m.extra.scratch[0] as u8 { - // resetAnimations, then the state's own. - for s in &mut m.anim.states[..5] { - s.stop(); - } - match current { - FEELING_HAPPY => m.anim.states[0].start_if_stopped(age), - SCENTING => m.anim.states[1].start_if_stopped(age), - SNIFFING => m.anim.states[2].start_if_stopped(age), - DIGGING => m.anim.states[3].start_if_stopped(age), - RISING => m.anim.states[4].start_if_stopped(age), - _ => {} - } - m.extra.scratch[0] = i32::from(current); - } + animate(m); if current == DIGGING && now(m) == m.extra.ints[3] { let h = head_block(m); events.push(MobEvent::GiftLoot { @@ -110,6 +95,27 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { let wet = m.fluids.in_water || m.fire_ticks > 0; m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 }); } +/// `Sniffer.onSyncedDataUpdated(DATA_STATE)`: the animation states of the +/// state it changed to (on a client, each tick for the state it has). +pub fn animate(m: &mut Mob) { + let age = m.age as f32; + let current = state(m); + if current != m.extra.scratch[0] as u8 { + // resetAnimations, then the state's own. + for s in &mut m.anim.states[..5] { + s.stop(); + } + match current { + FEELING_HAPPY => m.anim.states[0].start_if_stopped(age), + SCENTING => m.anim.states[1].start_if_stopped(age), + SNIFFING => m.anim.states[2].start_if_stopped(age), + DIGGING => m.anim.states[3].start_if_stopped(age), + RISING => m.anim.states[4].start_if_stopped(age), + _ => {} + } + m.extra.scratch[0] = i32::from(current); + } +} /// The brain memory holding the explored positions /// (`SNIFFER_EXPLORED_POSITIONS`). pub fn to_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) { diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index a5670b8cb..64106574b 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1661,6 +1661,12 @@ impl Def { | S::Camel | S::CamelHusk => 400, S::Ocelot => 900, + // Guardian.getAmbientSoundInterval (the elder too). + S::Guardian | S::ElderGuardian => 160, + // Hoglin extends Animal; Shulker extends AbstractGolem. + S::Hoglin | S::Shulker => 120, + // Allay is a PathfinderMob: the Mob default. + S::Allay => 80, S::Squid | S::GlowSquid | S::Cod diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index e97134505..91c303467 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -371,6 +371,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { events.push(MobEvent::Explode( [m.position.x, m.position.y + 0.0625, m.position.z], power, + m.species(), )); m.removed = true; return; diff --git a/crates/horizon-client/src/mobs/sync.rs b/crates/horizon-client/src/mobs/sync.rs new file mode 100644 index 000000000..d1c5b6609 --- /dev/null +++ b/crates/horizon-client/src/mobs/sync.rs @@ -0,0 +1,85 @@ +//! A server's mobs as a client animates them. The server thread, a LAN host +//! and a dedicated server run each mob's animation state (`ai::tick`); a +//! client of a server only gets synched data and entity events, and runs the +//! animation steps vanilla runs on the client (`Entity.onSyncedDataUpdated`, +//! `handleEntityEvent` and the per tick animation states). The server's half +//! is `game/lan.rs` (`mob_meta`, with `pose_id` here for index 6) and +//! `MobEvent::EntityEvent`; the client's half is `game/remote_mob_data.rs`, +//! `game/remote.rs` (`C::EntityEvent`) and `client_tick` here. +//! +//! To animate another species for a client: +//! - send its synched data in `mob_meta` and read it in +//! `remote_mob_data::apply`; +//! - send its poses in `pose_id` and read them in `set_pose`; +//! - broadcast its entity events with `MobEvent::EntityEvent` and handle +//! them in `entity_event`; +//! - run its client side animation in `client_tick`, sharing the function +//! with the server's `ai_step` where the server computes the same. +use super::{Mob, Species, breeze, camel, shulker, sniffer, warden}; + +// `Pose.id` of the poses mobs take. +pub const STANDING: u8 = 0; +pub const LONG_JUMPING: u8 = 6; +pub const SITTING: u8 = 10; +pub const ROARING: u8 = 11; +pub const SNIFFING: u8 = 12; +pub const EMERGING: u8 = 13; +pub const DIGGING: u8 = 14; +pub const SLIDING: u8 = 15; +pub const SHOOTING: u8 = 16; +pub const INHALING: u8 = 17; + +/// `Entity.DATA_POSE` (index 6) of a mob of a server: the pose its species +/// keeps in its own fields. +pub fn pose_id(m: &Mob) -> u8 { + match m.species() { + Species::Warden => warden::pose_id(m), + Species::Breeze => breeze::pose_id(m), + Species::Camel | Species::CamelHusk if camel::sitting(m) => SITTING, + _ => STANDING, + } +} + +/// `Entity.onSyncedDataUpdated(DATA_POSE)` on a client. +pub fn set_pose(m: &mut Mob, id: u8) { + m.extra.pose = id; + match m.species() { + Species::Warden => warden::set_pose_id(m, id), + Species::Breeze => breeze::set_pose_id(m, id), + _ => {} + } +} + +/// The per tick animation steps of a client's mobs (after `m.age` moved on), +/// for the species whose server runs them in `ai_step`. `game_time` is the +/// client level's. +pub fn client_tick(m: &mut Mob, game_time: i64) { + match m.species() { + Species::Warden => warden::client_tick(m), + Species::Sniffer => sniffer::animate(m), + Species::Breeze => breeze::ai_step(m), + Species::Camel | Species::CamelHusk => camel::client_tick(m, game_time), + Species::Shulker => shulker::client_tick(m), + _ => {} + } +} + +/// `handleEntityEvent` of the mob types that start animations by an event +/// (`ClientboundEntityEventPacket` for a mob of a client). +pub fn entity_event(m: &mut Mob, event: u8) { + let age = m.age as f32; + if m.species() == Species::Warden { + match event { + // Attack: the roar ends, the swing starts. + 4 => { + m.anim.states[warden::ROAR].stop(); + m.anim.states[warden::ATTACK].start(age); + } + // The tendrils twitch. + 61 => m.anim.v[warden::TENDRIL] = 10.0, + // The sonic boom. + 62 => m.anim.states[warden::SONIC_BOOM].start(age), + _ => {} + } + } +} diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index 2052eef4c..f72b0318a 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -2918,11 +2918,18 @@ impl B { let mut bodies = Vec::new(); if let Some(t) = cx.w.target_info(target) { let (min, max) = (t.bounds.min_position(), t.bounds.max_position()); - bodies.push((t.position, max.x - min.x, max.y - min.y)); + bodies.push((partner, t.position, max.x - min.x, max.y - min.y)); } - bodies.push((m.position, f64::from(m.width()), f64::from(m.height()))); - for (feet, width, height) in bodies { + bodies.push(( + m.id, + m.position, + f64::from(m.width()), + f64::from(m.height()), + )); + for (mob, feet, width, height) in bodies { cx.events.push(MobEvent::AroundSelf { + mob, + event: 12, kind: "heart", feet: [feet.x, feet.y, feet.z], width, @@ -3605,6 +3612,8 @@ fn pois_scan_order(_m: &Mob, found: &[(Poi, [i32; 3])]) -> Vec { /// `AbstractVillager.addParticlesAroundSelf(HAPPY_VILLAGER)` on the client. fn happy_particles(m: &Mob, cx: &mut Bx) { cx.events.push(MobEvent::AroundSelf { + mob: m.id, + event: 14, kind: "happy_villager", feet: [m.position.x, m.position.y, m.position.z], width: f64::from(m.width()), diff --git a/crates/horizon-client/src/mobs/warden.rs b/crates/horizon-client/src/mobs/warden.rs index 11161ef7c..747443577 100644 --- a/crates/horizon-client/src/mobs/warden.rs +++ b/crates/horizon-client/src/mobs/warden.rs @@ -67,6 +67,29 @@ impl Pose { } } } +/// `Pose.id` of the poses a warden takes (`sync::pose_id`). +pub fn pose_id(m: &Mob) -> u8 { + match pose(m) { + Pose::Standing => 0, + Pose::Roaring => 11, + Pose::Sniffing => 12, + Pose::Emerging => 13, + Pose::Digging => 14, + } +} +/// `Entity.onSyncedDataUpdated(DATA_POSE)` on a client. +pub(super) fn set_pose_id(m: &mut Mob, id: u8) { + set_pose( + m, + match id { + 11 => Pose::Roaring, + 12 => Pose::Sniffing, + 13 => Pose::Emerging, + 14 => Pose::Digging, + _ => Pose::Standing, + }, + ); +} /// The warden's pose (kept in `Extra.counter` so it can be read while the /// brain is being ticked). pub fn pose(m: &Mob) -> Pose { @@ -434,6 +457,11 @@ pub fn do_push(m: &mut Mob, w: &MobWorld, who: Who, events: &mut Vec) pub(super) fn do_hurt_target(m: &mut Mob, target: Who, w: &MobWorld, events: &mut Vec) { m.anim.states[ROAR].stop(); m.anim.states[ATTACK].start(m.age as f32); + events.push(MobEvent::EntityEvent { + mob: m.id, + event: 4, + at: at(m), + }); let pitch = voice_pitch(m); sound(m, "entity.warden.attack_impact", 10.0, pitch, events); warden_brain::mem(m).sonic_boom_cooldown.set_ttl((), 40); @@ -546,6 +574,11 @@ fn receive_vibration(m: &mut Mob, w: &MobWorld, info: Info, events: &mut Vec) { - let Some(st) = m.extra.warden.as_ref() else { - return; - }; - let client_anger = st.client_anger; - let delay = heart_beat_delay(client_anger); - if i64::from(m.age) % i64::from(delay) == 0 { - m.anim.v[HEART] = 10.0; + if heartbeat(m) { events.push(MobEvent::LevelEventSound { sound: "entity.warden.heartbeat", at: at(m), @@ -745,6 +772,30 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec) { spread: 0.2, }); } + animate(m, events); +} +/// The heart's beat on its clock, from the client's anger level: whether +/// this tick has one (its sound is the caller's). +fn heartbeat(m: &mut Mob) -> bool { + let Some(st) = m.extra.warden.as_ref() else { + return false; + }; + let delay = heart_beat_delay(st.client_anger); + let beat = i64::from(m.age) % i64::from(delay) == 0; + if beat { + m.anim.v[HEART] = 10.0; + } + beat +} +/// `Warden.tick` on a client that is not the server: the heart and tendril +/// animations and the keyframes that ended. Its sounds and particles come +/// from the server. +pub fn client_tick(m: &mut Mob) { + m.anim.vo = m.anim.v; + heartbeat(m); + animate(m, &mut Vec::new()); +} +fn animate(m: &mut Mob, events: &mut Vec) { // The animation values count down after the sync of the last tick. for slot in [TENDRIL, HEART] { if m.anim.v[slot] > 0.0 { diff --git a/crates/horizon-client/src/mobs/warden_brain.rs b/crates/horizon-client/src/mobs/warden_brain.rs index 8caafefc9..667bbedf0 100644 --- a/crates/horizon-client/src/mobs/warden_brain.rs +++ b/crates/horizon-client/src/mobs/warden_brain.rs @@ -937,6 +937,11 @@ impl B { mm.sonic_boom_sound_delay.set_ttl((), SONIC_SOUND_DELAY); // Entity event 62: the sonic boom keyframes start. m.anim.states[warden::SONIC_BOOM].start(m.age as f32); + cx.events.push(MobEvent::EntityEvent { + mob: m.id, + event: 62, + at: [m.position.x, m.position.y, m.position.z], + }); sound(m, "entity.warden.sonic_charge", 3.0, 1.0, cx.events); true } diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6c3316ac7..2fdd16372 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -221,6 +221,7 @@ pub fn custom_server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec, @@ -259,6 +259,9 @@ pub struct PlayerMotion { pub history: MovementHistory, pub fall_distance: f64, pub stuck_multiplier: Vec3, + /// `Entity.pistonDeltas` and `pistonDeltasGameTime`: how far a moving + /// block has pushed this entity this tick (0.51 at most on any axis). + pub piston: horizon_world::piston_movement::PistonMovement, pub yaw: f32, pub head_yaw: f32, pub jumping: bool, @@ -472,6 +475,7 @@ impl PlayerMotion { history: MovementHistory::default(), fall_distance: 0.0, stuck_multiplier: Vec3::ZERO, + piston: Default::default(), yaw: 0.0, head_yaw: 0.0, jumping: false, @@ -1907,8 +1911,14 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> { fn set_collision_flags(&mut self, value: CollisionFlags) { self.player.collision = value; } - fn limit_piston_movement(&mut self, _: Vec3) -> Result { - Err("piston movement requires a ticking entity runtime".into()) + /// `Entity.limitPistonMovement`: the per-tick 0.51-block budget shared by + /// every move on an axis. A failed game-time read leaves the accumulator + /// as it was, as native does. + fn limit_piston_movement(&mut self, movement: Vec3) -> Result { + let time = self.scene.game_time; + self.player + .piston + .limit(movement, || Ok::>(time)) } fn stuck_multiplier(&self) -> Vec3 { self.player.stuck_multiplier diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index 894e6d907..e3751f0c6 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -119,6 +119,67 @@ impl PlayerMotion { !self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&FluidTags, LAVA) } } +/// `BubbleColumnBlock.entityInside` for an entity that is not the player (a mob, +/// a dropped item, an ender pearl): the bubble columns its box touches push it +/// up or drag it down, harder at the surface (`Entity.handleOnAboveBubbleColumn` +/// and `handleOnInsideBubbleColumn`). Returns whether it was inside a column +/// below the surface, which resets its fall distance. +pub fn bubble_column_push( + world: &World, + registry: &horizon_world::registry::BlockRegistry, + facts: &crate::blocks::BlockFacts, + collision: &horizon_world::block_collision::BlockCollisionRegistry<'_>, + bounds: Aabb, + velocity: &mut Vec3, +) -> bool { + let b = bounds.deflate(Vec3::new( + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + f64::from(1.0e-5f32), + )); + let (lo, hi) = (b.min_position(), b.max_position()); + let mut reset_fall = false; + for x in lo.x.floor() as i32..=(hi.x.ceil() as i32 - 1) { + for y in lo.y.floor() as i32..=(hi.y.ceil() as i32 - 1) { + for z in lo.z.floor() as i32..=(hi.z.ceil() as i32 - 1) { + let state = world.block(x, y, z); + if &*facts.get(state).name != "minecraft:bubble_column" { + continue; + } + let drag = registry + .state(state) + .and_then(|s| s.properties.get("drag")) + .is_some_and(|d| d == "true"); + let above = world.block(x, y + 1, z); + // stateAbove.getCollisionShape(level, pos): the shape is asked + // at the column's own position. + let mut scene = SceneCollisions { + world, + binding: collision, + subject: None, + }; + let context = horizon_world::collision_context::CollisionContext::empty(false); + let nothing_above = collision + .collision_shape_with_context( + &mut scene, + above, + BlockPos::new(x, y, z), + &context, + ) + .is_ok_and(|shape| shape.is_empty()) + && facts.get(above).fluid == crate::blocks::Fluid::None; + velocity.y = match (nothing_above, drag) { + (true, true) => (-0.9_f64).max(velocity.y - 0.03), + (true, false) => 1.8_f64.min(velocity.y + 0.1), + (false, true) => (-0.3_f64).max(velocity.y - 0.03), + (false, false) => 0.7_f64.min(velocity.y + 0.06), + }; + reset_fall |= !nothing_above; + } + } + } + reset_fall +} /// Which fluids `FluidTags.WATER` and `FluidTags.LAVA` hold. pub struct FluidTags; impl FluidMembership for FluidTags { diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 1e012fd90..28952ba2c 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -4,9 +4,9 @@ //! and an overlay resource root that layers the enabled packs over the //! vanilla resources (later packs win), so every loader sees one tree. mod cache; -pub mod pattern; use crate::text::Style; use crate::{text::Text, zip::Zip}; +pub use horizon_client_core::pattern; use pattern::Pattern; use std::{ collections::{BTreeMap, BTreeSet}, diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 2e7930b4e..c38e571c5 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -994,6 +994,8 @@ pub struct ParticleEngine { emitters: Vec<(ParticleOptions, [f64; 3], f64, f64, u32)>, /// Camera position for the 32-block spawn limiter. pub camera: [f64; 3], + /// The Particles option (`ParticleStatus`): 0 all, 1 decreased, 2 minimal. + pub particle_level: u8, /// FireworkParticles.Starter instances. starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). @@ -1024,6 +1026,7 @@ impl ParticleEngine { emitters: Vec::new(), starters: Vec::new(), camera: [0.0; 3], + particle_level: 0, sounds: Vec::new(), made: Default::default(), item_sprites: HashMap::new(), @@ -1134,30 +1137,48 @@ impl ParticleEngine { &mut self.level_random } /// `ClientLevel.addParticle`: dropped beyond 32 blocks of the camera unless - /// the type overrides the limiter. + /// the type overrides the limiter, and thinned by the Particles option. pub fn add(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { + self.add_with(options, p, v, false, false); + } + /// `ClientLevel.addParticle(particle, overrideLimiter, alwaysShow, ...)` + /// (`doAddParticle`). `always_show` is `addAlwaysVisibleParticle`'s flag. + pub fn add_with( + &mut self, + options: &ParticleOptions, + p: [f64; 3], + v: [f64; 3], + override_limiter: bool, + always_show: bool, + ) { let c = self.camera; let d2 = (p[0] - c[0]).powi(2) + (p[1] - c[1]).powi(2) + (p[2] - c[2]).powi(2); if let Some(requested) = &mut self.requested { requested.push((options.clone(), p, v)); return; } - if !options.ty.override_limiter() && d2 > 1024.0 { - return; + let minimal = self.calculate_particle_level(always_show) == 2; + if override_limiter || options.ty.override_limiter() || (d2 <= 1024.0 && !minimal) { + self.create(options, p, v); } - self.create(options, p, v); + } + /// `ClientLevel.calculateParticleLevel`: minimal still shows one in ten + /// always-visible particles as decreased, and decreased drops a third. + fn calculate_particle_level(&mut self, always_show: bool) -> u8 { + let mut level = self.particle_level.min(2); + if always_show && level == 2 && self.level_random.next_int_bound(10).unwrap_or(0) == 0 { + level = 1; + } + if level == 1 && self.level_random.next_int_bound(3).unwrap_or(0) == 0 { + level = 2; + } + level } /// `LevelEventHandler.singleBlockTeleportationParticles` towards /// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon /// egg's event 2015 packs offsets within (16, 8, 16), a consumable's /// teleport (2017) within (127, 127, 127). - pub fn block_teleportation( - &mut self, - from: [i32; 3], - data: i32, - radius: [i32; 3], - particle_level: u8, - ) { + pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, radius: [i32; 3]) { let to = [ from[0].wrapping_add(((data >> 16) & 255) - radius[0]), from[1].wrapping_add(((data >> 8) & 255) - radius[1]), @@ -1175,15 +1196,7 @@ impl ParticleEngine { to[1] + t * (from[1] - to[1]) + r.next_double() - 0.5, to[2] + t * (from[2] - to[2]) + (r.next_double() - 0.5) + 0.5, ]; - // The option roll shares the level random and precedes the distance check. - let limited = match particle_level { - 1 => r.next_int_bound(3).unwrap_or(0) == 0, - 2 => true, - _ => false, - }; - if !limited { - self.add(&options, position, velocity); - } + self.add(&options, position, velocity); } } /// `ClientPacketListener.handleExplosion` + `ClientExplosionTracker`: the @@ -1225,6 +1238,10 @@ impl ParticleEngine { block_count: usize, is_air: &dyn Fn([i32; 3]) -> bool, ) { + // ClientExplosionTracker.tick: only the All option throws the debris. + if self.particle_level != 0 { + return; + } for _ in 0..block_count.min(512) { let r = &mut self.random; let d = Vec3::new( @@ -3789,7 +3806,7 @@ mod tests { let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new(), &HashSet::new()); engine.seed_randoms(0, 0, 0); // Destination offset (-15, 7, 15); the unused top byte is ignored. - engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0); + engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16]); assert_eq!(engine.pending.len(), 128); assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); let first = &engine.pending[0]; @@ -3816,7 +3833,7 @@ mod tests { // TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition // of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4). let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127); - engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0); + engine.block_teleportation([4, 12, -5], data, [127, 127, 127]); assert_eq!(engine.pending.len(), 128); for p in &engine.pending { let [x, y, z] = p.position; @@ -3842,7 +3859,8 @@ mod tests { if distant { engine.camera = [1000.0; 3]; } - engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option); + engine.particle_level = option; + engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16]); assert_eq!(engine.pending.len(), if distant { 0 } else { count }); assert_eq!(engine.level_random.state(), state); } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index b6f4c1322..97045f6f7 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -339,59 +339,7 @@ impl SaveTables { } } -/// A container's loot table and what Horizon rolled from it. Vanilla keeps -/// `LootTable` and `LootTableSeed` until the container is first opened; -/// Horizon rolls when it generates or loads the chunk, and saves the table -/// again while the container still holds exactly the rolled items. -#[derive(Clone, Debug, PartialEq)] -pub struct RolledLoot { - pub pos: (i32, i32, i32), - pub table: String, - /// The saved `LootTableSeed`, written back unless 0 (trySaveLootTable). - pub seed: Option, - /// The rolled `Items`. - pub items: Tag, -} -impl RolledLoot { - /// Puts the loot table back in place of `Items` while they are still the - /// roll; false once the container holds anything else. - pub fn restore(&self, map: &mut Compound) -> bool { - if map.get(&"Items".into()) != Some(&self.items) { - return false; - } - map.remove(&"Items".into()); - map.insert("LootTable".into(), string(&self.table)); - if let Some(seed) = self.seed.filter(|s| *s != 0) { - map.insert("LootTableSeed".into(), Tag::Long(seed)); - } - true - } -} - -/// Save data loaded with a chunk that Horizon keeps but does not simulate. -#[derive(Clone, Debug, Default)] -pub struct ChunkExtras { - /// Chunk root keys written back as loaded (structures, PostProcessing, - /// InhabitedTime, blending data, ...). - pub root: Compound, - /// Block entities Horizon does not model. - pub block_entities: Vec, - /// The NBT of the modelled block entities as loaded, to restore the fields and - /// detail Horizon does not model when it saves them (`block_entity_nbt::overlay`). - pub block_entity_sources: Vec<((i32, i32, i32), Tag)>, - /// Every saved block entity's position in the order of the save's list, - /// the order `SerializableChunkData` puts them in the chunk's maps. - pub block_entity_order: Vec<(i32, i32, i32)>, - /// Scheduled ticks (`block_ticks`/`fluid_ticks`): delays relative to the - /// save time. Registered with the level's tick scheduler on arrival and - /// replaced with the scheduler's pending ticks when saving. - pub block_ticks: Vec, - pub fluid_ticks: Vec, - /// Game time written as `LastUpdate`. - pub last_update: i64, - /// Containers still holding their loot table's roll. - pub rolled_loot: Vec, -} +pub use crate::chunk::{ChunkExtras, RolledLoot}; fn tick_list(ticks: &[SavedTick], name: impl Fn(u32) -> Option) -> Tag { Tag::List( @@ -643,6 +591,16 @@ pub fn encode_block_entity( entries.push(("custom_name", name.clone())); } } + // TheEndGatewayBlockEntity.saveAdditional. + BlockEntity::EndGateway(g) => { + entries.push(("Age", Tag::Long(g.age))); + if let Some(exit) = g.exit_portal { + entries.push(("exit_portal", Tag::IntArray(exit.to_vec()))); + } + if g.exact_teleport { + entries.push(("ExactTeleport", Tag::Byte(1))); + } + } BlockEntity::Spawner(s) => entries.extend(s.save()), BlockEntity::TrialSpawner(s) => entries.extend(s.save()), BlockEntity::Vault(v) => entries.extend(v.save()), @@ -702,11 +660,24 @@ fn roll_loaded_loot( biome, )) } +/// `TheEndGatewayBlockEntity.loadAdditional`. +pub fn decode_end_gateway(tag: &Tag) -> crate::containers::EndGateway { + crate::containers::EndGateway { + age: number(tag.get("Age")).unwrap_or(0), + exit_portal: tag + .get("exit_portal") + .and_then(crate::block_entity_nbt::gateway_exit), + exact_teleport: number(tag.get("ExactTeleport")).unwrap_or(0) != 0, + } +} pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers::BlockEntity)> { use crate::containers::BlockEntity; let int = |k: &str| number(tag.get(k)).map(|v| v as i32); let id = text(tag.get("id"))?; let pos = (int("x")?, int("y")?, int("z")?); + if id == "minecraft:end_gateway" { + return Some((pos, BlockEntity::EndGateway(decode_end_gateway(tag)))); + } if id == "minecraft:jukebox" { let record = tag.get("RecordItem").and_then(item_from_nbt); let ticks = number(tag.get("ticks_since_song_started")).unwrap_or(0); @@ -846,6 +817,7 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain | BlockEntity::Lectern(_) | BlockEntity::Banner(_) | BlockEntity::CreakingHeart(_) + | BlockEntity::EndGateway(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector => {} BlockEntity::Spawner(s) => **s = crate::mobs::spawner::Spawner::load(tag), @@ -4642,6 +4614,79 @@ mod tests { } use super::*; + #[test] + fn end_gateway_block_entity_round_trips() { + use crate::containers::{BlockEntity, EndGateway}; + let plain = BlockEntity::for_block("minecraft:end_gateway").expect("gateway"); + assert!(matches!(&plain, BlockEntity::EndGateway(g) if *g == EndGateway::default())); + for exit in [None, Some([8, 100, 0])] { + for exact in [false, true] { + let gateway = EndGateway { + age: 201, + exit_portal: exit, + exact_teleport: exact, + }; + let tag = encode_block_entity( + (702, 100, 0), + &BlockEntity::EndGateway(gateway.clone()), + "minecraft:end_gateway", + ); + assert_eq!( + text(tag.get("id")).as_deref(), + Some("minecraft:end_gateway") + ); + assert_eq!(tag.get("Age"), Some(&Tag::Long(201))); + assert_eq!( + tag.get("exit_portal"), + exit.map(|p| Tag::IntArray(p.to_vec())).as_ref() + ); + assert_eq!( + tag.get("ExactTeleport"), + exact.then_some(Tag::Byte(1)).as_ref() + ); + let (pos, back) = decode_block_entity(&tag).expect("gateway"); + assert_eq!(pos, (702, 100, 0)); + assert!(matches!(back, BlockEntity::EndGateway(g) if g == gateway)); + } + } + } + + #[test] + fn end_gateway_exit_requires_spawnable_bounds() { + for (exit, valid) in [ + (vec![-30_000_000, -20_000_000, -30_000_000], true), + (vec![29_999_999, 19_999_999, 29_999_999], true), + (vec![30_000_000, 0, 0], false), + (vec![0, 0, 30_000_000], false), + (vec![-30_000_001, 0, 0], false), + (vec![0, 0, -30_000_001], false), + (vec![0, 20_000_000, 0], false), + (vec![0, -20_000_001, 0], false), + (vec![i32::MIN, 0, 0], false), + (vec![0, 100], false), + ] { + let tag = Tag::compound([ + ("id", string("minecraft:end_gateway")), + ("x", Tag::Int(702)), + ("y", Tag::Int(100)), + ("z", Tag::Int(0)), + ("exit_portal", Tag::IntArray(exit)), + ]); + let (_, crate::containers::BlockEntity::EndGateway(g)) = + decode_block_entity(&tag).unwrap() + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal.is_some(), valid); + let canonical = crate::block_entity_nbt::canonical(&tag).expect("gateway NBT"); + assert_eq!(canonical.get("exit_portal").is_some(), valid); + } + assert_eq!( + decode_end_gateway(&Tag::Compound(Compound::new())), + crate::containers::EndGateway::default() + ); + } + #[test] fn skull_block_entity_keeps_its_profile() { // A placed `player_head` as vanilla saves it: the owning player's diff --git a/crates/horizon-client/src/signs.rs b/crates/horizon-client/src/signs.rs index 07217ed79..799210797 100644 --- a/crates/horizon-client/src/signs.rs +++ b/crates/horizon-client/src/signs.rs @@ -147,10 +147,10 @@ fn component_text(tag: &Tag) -> String { _ => s, } } - Tag::Compound(_) => match tag.get("text") { - Some(Tag::String(t)) => t.to_string_lossy(), - _ => String::new(), - }, + // Component.getString: translations and key binds resolved. + Tag::Compound(_) => { + crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(tag)).plain() + } _ => String::new(), } } diff --git a/crates/horizon-client/src/skins.rs b/crates/horizon-client/src/skins.rs index ee6851e00..740208973 100644 --- a/crates/horizon-client/src/skins.rs +++ b/crates/horizon-client/src/skins.rs @@ -116,20 +116,9 @@ pub fn unpack(value: &str, signature: Signature, valid_uris: &[&str]) -> Texture /// heads and mannequins read their profile this way, and `SkinManager` lets /// those textures be unsigned (`getInsecureSkinInformation`). pub fn profile_skin_url(profile: &serde_json::Value) -> Option { - let value = profile - .get("properties")? - .as_array()? - .iter() - .find_map(|p| { - if p.get("name")?.as_str()? == "textures" { - p.get("value")?.as_str() - } else { - None - } - })?; - unpack(value, Signature::Unsigned, &TEXTURE_URIS).skin + let (value, signature) = parse_profile(profile).textures?; + unpack(&value, signature, &TEXTURE_URIS).skin } - /// `profile_skin_url` on a block entity's `profile` NBT (`SkullBlockEntity`): /// the same `properties` list, held as a compound. A name-only profile (a /// string tag) has no properties and no skin URL. @@ -164,13 +153,329 @@ pub fn profile_uuid_nbt(profile: &horizon_world::nbt::Tag) -> Option { } } -fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { +pub(crate) fn nbt_text(tag: Option<&horizon_world::nbt::Tag>) -> Option { match tag { Some(horizon_world::nbt::Tag::String(s)) => Some(s.to_string_lossy()), _ => None, } } +/// `Either`: the key a `Dynamic` `ResolvableProfile` resolves +/// by (`ResolvableProfile.nameOrId`). +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub enum NameOrId { + Name(String), + Id(u128), +} + +/// `GameProfile` as `fetchProfile` returns it: the account's id, name and +/// property map (its `textures` property is the skin). +#[derive(Clone, Debug)] +pub struct ResolvedProfile { + pub id: u128, + pub name: String, + /// `(name, value, signature)` properties. + pub properties: Vec<(String, String, Option)>, +} +impl ResolvedProfile { + /// `SessionService.getPackedTextures`: the `textures` property. + pub fn textures(&self) -> Option<(String, Signature)> { + self.properties + .iter() + .find(|(n, _, _)| n == "textures") + .map(|(_, v, s)| { + ( + v.clone(), + if s.is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + ) + }) + } +} + +/// Where a `Dynamic` profile's resolution stands (`resolveProfile`'s future). +#[derive(Clone, Debug)] +pub enum Resolve { + Pending, + /// The services' answer: `None` for no profile or no answer, which the + /// cache holds like any result (`Optional.empty`). + Done(Option), +} + +/// `ProfileResolver.Cached`: resolves a `Dynamic` profile through the +/// services — `profileCacheByName` asks `profiles`/`getByName` for the id, +/// `profileCacheById` asks `session`/`getProfileById` for the profile — +/// at most 256 entries kept 10 minutes after their last use, fetched on +/// background threads. +pub struct Resolver { + entries: std::collections::HashMap, + done: std::sync::mpsc::Receiver<(NameOrId, Option)>, + send: std::sync::mpsc::Sender<(NameOrId, Option)>, + last_sweep: std::time::Instant, +} +struct Entry { + touched: std::time::Instant, + /// `None` while the fetch is in flight. + resolved: Option>, +} +/// `ProfileResolver.Cached`'s cache bounds. +const MAX_PROFILES: usize = 256; +const PROFILE_TTL: std::time::Duration = std::time::Duration::from_secs(10 * 60); + +/// `StringUtil.isValidPlayerName` (the check `fetchByName` makes first). +fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// `fetchByNameOrId`: `getByName` answers `{id, name}`; `getProfileById` +/// (`fetchProfile(id, requireSecure)`) answers `{id, name, properties}` — +/// asked `unsigned=false` so the `textures` property is signed. +fn resolve_profile(key: &NameOrId, doc: &serde_json::Value) -> Option { + let id = match key { + NameOrId::Id(id) => *id, + NameOrId::Name(name) => { + let url = crate::auth::endpoint(doc, "profiles", "getByName")? + .replace("{name}", &name.to_lowercase()); + let body = http_get(&url)?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + crate::auth::parse_uuid(v.get("id")?.as_str()?)? + } + }; + let url = crate::auth::endpoint(doc, "session", "getProfileById")? + .replace("{profileId}", &format!("{id:032x}")); + let separator = if url.contains('?') { '&' } else { '?' }; + let body = http_get(&format!("{url}{separator}unsigned=false"))?; + let v: serde_json::Value = serde_json::from_slice(&body).ok()?; + Some(ResolvedProfile { + id: crate::auth::parse_uuid(v.get("id")?.as_str()?)?, + name: v.get("name")?.as_str()?.to_owned(), + properties: v + .get("properties")? + .as_array()? + .iter() + .map(|p| { + Some(( + p.get("name")?.as_str()?.to_owned(), + p.get("value")?.as_str()?.to_owned(), + p.get("signature") + .and_then(|s| s.as_str()) + .map(str::to_owned), + )) + }) + .collect::>>()?, + }) +} + +impl Default for Resolver { + fn default() -> Self { + Self::new() + } +} +impl Resolver { + pub fn new() -> Self { + let (send, done) = std::sync::mpsc::channel(); + Self { + entries: Default::default(), + done, + send, + last_sweep: std::time::Instant::now(), + } + } + /// `CacheBuilder.expireAfterAccess` with `maximumSize`. + fn sweep(&mut self) { + if self.last_sweep.elapsed() < std::time::Duration::from_secs(30) { + return; + } + self.last_sweep = std::time::Instant::now(); + self.entries + .retain(|_, e| e.touched.elapsed() < PROFILE_TTL); + while self.entries.len() > MAX_PROFILES + && let Some(oldest) = self + .entries + .iter() + .min_by_key(|(_, e)| e.touched) + .map(|(k, _)| k.clone()) + { + self.entries.remove(&oldest); + } + } + /// How the resolution of `key` stands, starting it the first time. + pub fn state(&mut self, key: &NameOrId) -> Resolve { + while let Ok((key, resolved)) = self.done.try_recv() { + self.entries.insert( + key, + Entry { + touched: std::time::Instant::now(), + resolved: Some(resolved), + }, + ); + } + self.sweep(); + if let Some(entry) = self.entries.get_mut(key) { + entry.touched = std::time::Instant::now(); + return match &entry.resolved { + Some(resolved) => Resolve::Done(resolved.clone()), + None => Resolve::Pending, + }; + } + // `fetchByName` refuses an invalid name without a fetch; like every + // other empty answer that is the cached result. + let resolved = matches!(key, NameOrId::Name(name) if !valid_player_name(name)); + self.entries.insert( + key.clone(), + Entry { + touched: std::time::Instant::now(), + resolved: resolved.then_some(None), + }, + ); + if resolved { + return Resolve::Done(None); + } + let (key, send) = (key.clone(), self.send.clone()); + std::thread::spawn(move || { + let resolved = crate::auth::discovery() + .ok() + .and_then(|doc| resolve_profile(&key, &doc)); + let _ = send.send((key, resolved)); + }); + Resolve::Pending + } +} + +/// `ResolvableProfile` (an item's `minecraft:profile` component, a skull's +/// `profile` tag): the `textures` property it carries, the key a `Dynamic` +/// profile resolves by, and `partialProfile.id` — the fallback skin's key. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ProfileInfo { + /// `GameProfile.id` (`DefaultPlayerSkin.get`). + pub id: u128, + /// The `textures` property's value and signature state, when present. + pub textures: Option<(String, Signature)>, + /// `Dynamic` profiles resolve by name or id. + pub dynamic: Option, +} + +/// A profile's `id`: `UUIDUtil.CODEC` (an int array of four, or a UUID +/// string). +fn profile_id(v: &serde_json::Value) -> Option { + match v { + serde_json::Value::Array(a) => { + let ints: Option> = a.iter().map(|x| x.as_i64()).collect(); + let i = ints?; + (i.len() == 4).then(|| { + ((i[0] as u32 as u128) << 96) + | ((i[1] as u32 as u128) << 64) + | ((i[2] as u32 as u128) << 32) + | i[3] as u32 as u128 + }) + } + serde_json::Value::String(s) => crate::auth::parse_uuid(s), + _ => None, + } +} + +/// `ResolvableProfile`'s read of a `profile` value: a bare name is +/// `createUnresolved` (the `PLAYER_NAME` codec's alternative), a compound +/// `name` + `id` + `properties` (`Partial.MAP_CODEC` or a `GameProfile`). +pub fn parse_profile(v: &serde_json::Value) -> ProfileInfo { + if let serde_json::Value::String(name) = v { + return ProfileInfo { + id: horizon_protocol::crypto::offline_uuid(name), + textures: None, + dynamic: valid_player_name(name).then(|| NameOrId::Name(name.clone())), + }; + } + let name = v.get("name").and_then(|n| n.as_str()).map(str::to_owned); + let id = v.get("id").and_then(profile_id); + let properties = v.get("properties").and_then(|p| p.as_array()); + let textures = properties + .into_iter() + .flatten() + .find(|p| p.get("name").and_then(|n| n.as_str()) == Some("textures")) + .and_then(|p| { + Some(( + p.get("value")?.as_str()?.to_owned(), + if p.get("signature").is_some() { + Signature::Signed + } else { + Signature::Unsigned + }, + )) + }); + // `ResolvableProfile.create`: a Partial is Dynamic with no properties + // and exactly one of a name or an id. + let dynamic = + (properties.is_none_or(|p| p.is_empty()) && name.is_some() != id.is_some()).then(|| { + name.as_deref().map_or_else( + || NameOrId::Id(id.unwrap()), + |n| NameOrId::Name(n.to_owned()), + ) + }); + ProfileInfo { + // `createPartialProfile`: the id, else the name's offline UUID, else nil. + id: id + .or_else(|| name.as_deref().map(horizon_protocol::crypto::offline_uuid)) + .unwrap_or(0), + textures, + dynamic, + } +} + +/// `ResolvableProfile.create`'s `Dynamic` key from a skull's `profile` tag: +/// a bare name string is `createUnresolved`, and a compound without +/// properties and with exactly one of a name or an id is `Dynamic`. +pub fn dynamic_nbt(profile: &horizon_world::nbt::Tag) -> Option { + if let horizon_world::nbt::Tag::String(s) = profile { + let name = s.to_string_lossy(); + return valid_player_name(&name).then_some(NameOrId::Name(name)); + } + if matches!(profile.get("properties"), Some(horizon_world::nbt::Tag::List(l)) if !l.is_empty()) + { + return None; + } + match (nbt_text(profile.get("name")), profile_uuid_nbt(profile)) { + (Some(name), None) => Some(NameOrId::Name(name)), + (None, Some(id)) => Some(NameOrId::Id(id)), + _ => None, + } +} + +/// `PlayerSkinRenderCache.getOrDefault` for a head: the resolved skin once +/// its texture is in the atlas (`atlas`), else `partialProfile`'s default. +pub fn head_skin( + profile: &serde_json::Value, + resolver: &mut Resolver, + downloads: &mut Downloader, + atlas: impl Fn(&str) -> bool, +) -> String { + let p = parse_profile(profile); + let property = p.textures.or_else(|| { + let key = p.dynamic.as_ref()?; + match resolver.state(key) { + Resolve::Done(Some(profile)) => profile.textures(), + _ => None, + } + }); + if let Some((value, signature)) = property + && let Some(url) = unpack(&value, signature, &TEXTURE_URIS).skin + && let Some(hash) = texture_hash(&url) + { + let location = skin_location(&hash); + match downloads.state(Kind::Skin, &url) { + Download::Ready if atlas(&location) => return location, + // Its slot was evicted: offer the image again. + Download::Ready => { + downloads.again(&location); + } + _ => {} + } + } + crate::tab_list::default_skin(p.id).to_owned() +} + /// `MinecraftProfileTexture.getHash`: the base name of the URL's path. pub fn texture_hash(url: &str) -> Option { let rest = url.split_once("://")?.1; @@ -313,7 +618,16 @@ pub struct Downloader { done: std::sync::mpsc::Receiver<((Kind, String), Option>)>, send: std::sync::mpsc::Sender<((Kind, String), Option>)>, ready: Vec<(String, Vec)>, + /// Locations already in `ready`, so `again` does not double-queue. + queued: std::collections::HashSet, + /// Decoded skin images by location, kept so a skin evicted from the + /// atlas uploads again (`again`); the disk cache backs anything dropped. + images: std::collections::HashMap>, + image_order: std::collections::VecDeque, } +/// `images` is bounded only so a long session on a busy server does not grow +/// without end; the disk cache holds everything it drops. +const MAX_SKIN_IMAGES: usize = 1024; impl Downloader { pub fn new(root: std::path::PathBuf) -> Self { let (send, done) = std::sync::mpsc::channel(); @@ -323,6 +637,9 @@ impl Downloader { done, send, ready: Vec::new(), + queued: Default::default(), + images: Default::default(), + image_order: Default::default(), } } /// How the download of `url` stands, starting it the first time. @@ -331,7 +648,8 @@ impl Downloader { let state = match image { Some(rgba) => { if key.0 == Kind::Skin { - self.ready.push((skin_location(&key.1), rgba)); + let location = skin_location(&key.1); + self.queue(location, rgba); } Download::Ready } @@ -370,8 +688,53 @@ impl Downloader { }); Download::Pending } + /// Keeps a decoded skin for `again`, dropping the oldest past the bound. + fn remember(&mut self, location: String, rgba: Vec) { + if !self.images.contains_key(&location) { + self.image_order.push_back(location.clone()); + while self.image_order.len() > MAX_SKIN_IMAGES + && let Some(old) = self.image_order.pop_front() + { + self.images.remove(&old); + } + } + self.images.insert(location, rgba); + } + /// An image off to the atlas: remembered for `again` and marked queued + /// so nothing uploads the same location twice. + fn queue(&mut self, location: String, rgba: Vec) { + self.remember(location.clone(), rgba.clone()); + self.queued.insert(location.clone()); + self.ready.push((location, rgba)); + } + /// A ready skin whose atlas slot was evicted (`show_skin` answered no): + /// its image for upload again, from memory or the disk cache. + pub fn again(&mut self, location: &str) -> bool { + if self.queued.contains(location) { + return true; + } + let Some(digest) = location.strip_prefix("skins/") else { + return false; + }; + let image = self.images.get(location).cloned().or_else(|| { + let file = self + .root + .join(if digest.len() > 2 { &digest[..2] } else { "xx" }) + .join(digest); + let (w, h, rgba) = crate::hud::decode_bytes(&std::fs::read(&file).ok()?).ok()?; + process_legacy_skin(w, h, &rgba) + }); + let Some(image) = image else { + return false; + }; + self.queue(location.to_owned(), image); + true + } /// Skins that finished since the last call: texture id and 64x64 RGBA. pub fn take_ready(&mut self) -> Vec<(String, Vec)> { + for (location, _) in &self.ready { + self.queued.remove(location); + } std::mem::take(&mut self.ready) } } @@ -452,6 +815,134 @@ pub fn sha1(data: &[u8]) -> [u8; 20] { #[cfg(test)] mod tests { + #[test] + fn profiles_parse_like_resolvable_profiles() { + use super::{NameOrId, Signature, parse_profile}; + // A bare name is `createUnresolved`: dynamic by name, and its partial + // id is the name's offline UUID. + let p = parse_profile(&serde_json::json!("Notch")); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + assert_eq!(p.id, horizon_protocol::crypto::offline_uuid("Notch")); + assert!(p.textures.is_none()); + // A name-only compound resolves the same way. + let p = parse_profile(&serde_json::json!({"name": "Notch"})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + // An id-only compound resolves by id (int array or UUID string). + let id = 0x0123_4567_89ab_cdef_0123_4567_89ab_cdef_u128; + let ints: Vec = [ + (id >> 96) as i32 as i64, + (id >> 64) as i32 as i64, + (id >> 32) as i32 as i64, + id as i32 as i64, + ] + .into(); + let p = parse_profile(&serde_json::json!({"id": ints})); + assert_eq!(p.dynamic, Some(NameOrId::Id(id))); + let p = parse_profile(&serde_json::json!({"id": "01234567-89ab-cdef-0123-4567abcdef00"})); + assert_eq!( + p.dynamic, + Some(NameOrId::Id(0x0123_4567_89ab_cdef_0123_4567_abcd_ef00)) + ); + // Name and id but no properties is Static: it never resolves, and its + // default skin keys off the id. + let p = parse_profile(&serde_json::json!({"name": "Notch", "id": ints})); + assert!(p.dynamic.is_none()); + assert_eq!(p.id, id); + // A `textures` property makes it Static (unsigned and signed). + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v"}] + })); + assert!(p.dynamic.is_none()); + assert_eq!(p.textures, Some(("v".into(), Signature::Unsigned))); + let p = parse_profile(&serde_json::json!({ + "properties": [{"name": "textures", "value": "v", "signature": "s"}] + })); + assert_eq!(p.textures, Some(("v".into(), Signature::Signed))); + // Empty properties leave it dynamic. + let p = parse_profile(&serde_json::json!({"name": "Notch", "properties": []})); + assert_eq!(p.dynamic, Some(NameOrId::Name("Notch".into()))); + } + + /// `getByName` and `getProfileById` answer from the services the + /// discovery document names; a profile resolves through both. + #[test] + fn profiles_resolve_through_the_services() { + use std::io::{BufRead, BufReader, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + std::thread::spawn(move || { + let reply = |status: &str, body: &str| { + format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + }; + for stream in listener.incoming().take(3) { + let mut stream = stream.unwrap(); + let mut line = String::new(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + reader.read_line(&mut line).unwrap(); + while reader.read_line(&mut String::new()).unwrap() > 2 {} + let body = if line.contains("/users/profiles/minecraft/") { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"# + } else if line.contains("/session/minecraft/profile/") + && line.contains("unsigned=false") + { + r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch","properties":[{"name":"textures","value":"dmFsdWU=","signature":"c2ln"}]}"# + } else { + "{}" + }; + stream.write_all(reply("200 OK", body).as_bytes()).unwrap(); + } + }); + let doc = serde_json::json!({"discovery": { + "profiles": {"endpoints": {"getByName": {"uri": format!("{base}/users/profiles/minecraft/{{name}}")}}}, + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + let resolved = + super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).unwrap(); + assert_eq!(resolved.id, 0x069a_79f4_44e9_4726_a5be_fca9_0e38_aaf5); + assert_eq!(resolved.name, "Notch"); + assert_eq!( + resolved.properties, + vec![( + "textures".to_owned(), + "dmFsdWU=".to_owned(), + Some("c2ln".to_owned()) + )] + ); + let by_id = super::resolve_profile(&super::NameOrId::Id(resolved.id), &doc).unwrap(); + assert_eq!(by_id.name, "Notch"); + // A discovery without `profiles`/`getByName` resolves no name. + let doc = serde_json::json!({"discovery": { + "session": {"endpoints": {"getProfileById": {"uri": format!("{base}/session/minecraft/profile/{{profileId}}")}}}, + }}); + assert!(super::resolve_profile(&super::NameOrId::Name("Notch".into()), &doc).is_none()); + } + + /// A skin evicted from the atlas re-uploads (`again`), once per ask. + #[test] + fn evicted_skins_upload_again() { + let mut d = super::Downloader::new(std::env::temp_dir().join("horizon-test-skins")); + d.remember("skins/abc".into(), vec![1, 2, 3]); + assert!(d.again("skins/abc")); + assert!(!d.again("skins/missing")); + // Once queued, more asks do not pile up uploads. + assert!(d.again("skins/abc")); + assert_eq!( + d.take_ready(), + vec![("skins/abc".to_owned(), vec![1, 2, 3])] + ); + assert!(d.take_ready().is_empty()); + assert!(d.again("skins/abc")); + assert_eq!(d.take_ready().len(), 1); + // The first upload marks the location queued too: an `again` before + // `take_ready` does not put the same skin in the atlas twice. + d.queue("skins/def".into(), vec![4]); + assert!(d.again("skins/def")); + assert_eq!(d.take_ready(), vec![("skins/def".to_owned(), vec![4])]); + } + #[test] fn profile_components_supply_unsigned_head_skins() { let value = "eyJ0ZXh0dXJlcyI6IHsiU0tJTiI6IHsidXJsIjogImh0dHBzOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlL2FiYzEyMyJ9fX0="; diff --git a/crates/horizon-client/src/structure_blocks.rs b/crates/horizon-client/src/structure_blocks.rs index 0a4c9a88e..8183b415a 100644 --- a/crates/horizon-client/src/structure_blocks.rs +++ b/crates/horizon-client/src/structure_blocks.rs @@ -257,6 +257,23 @@ mod tests { use super::*; use horizon_world::loot::{ExplorationMap, LootStack}; + #[test] + fn generated_end_gateway_keeps_its_exit() { + let Tag::Compound(nbt) = Tag::compound([ + ("exit_portal", Tag::IntArray(vec![100, 50, 0])), + ("ExactTeleport", Tag::Byte(1)), + ]) else { + unreachable!() + }; + let Some(BlockEntity::EndGateway(g)) = + generated_block_entity("minecraft:end_gateway", &nbt) + else { + panic!("gateway"); + }; + assert_eq!(g.exit_portal, Some([100, 50, 0])); + assert!(g.exact_teleport); + } + #[test] fn placed_chest_loot_keeps_its_enchantments_and_potions() { let stack = diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 83083eba2..00ff04ac5 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -93,11 +93,13 @@ pub struct World { pub light_log: Option>, /// The villager POIs of each section (`PoiManager`'s sections). pub pois: crate::poi_sections::PoiSections, + /// Moving-piston states removed during the last tick; retained until the + /// final block mesh is visible. + pub moving_piston_fallback: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, /// The moving-piston block entities of the level, by position, copied /// from the block ticks after each tick: collision and rendering read them. pub moving_pistons: Vec<([i32; 3], horizon_world::piston_shape::MovingPistonState)>, } -/// ServerLevel weather state (advanceWeatherCycle). #[derive(Clone, Copy, Debug, Default)] pub struct Weather { pub clear_time: i32, @@ -187,6 +189,7 @@ impl World { weather: Weather::default(), block_log: None, light_log: None, + moving_piston_fallback: Vec::new(), moving_pistons: Vec::new(), pois: Default::default(), } diff --git a/crates/horizon-world/examples/probe/main.rs b/crates/horizon-world/examples/probe/main.rs index b87e5620a..56dbc8843 100644 --- a/crates/horizon-world/examples/probe/main.rs +++ b/crates/horizon-world/examples/probe/main.rs @@ -137,6 +137,7 @@ mod movement_support_fixture; mod object_open_map_fixture; mod object_open_set_fixture; mod piston_movement_fixture; +mod piston_push_fixture; mod piston_shape_fixture; mod placement_fixture; mod player_equipment_fixture; @@ -309,6 +310,7 @@ probes! { object_open_map_fixture, object_open_set_fixture, piston_movement_fixture, + piston_push_fixture, piston_shape_fixture, placement_fixture, player_equipment_fixture, diff --git a/crates/horizon-world/examples/probe/piston_push_fixture.rs b/crates/horizon-world/examples/probe/piston_push_fixture.rs new file mode 100644 index 000000000..1d40cd610 --- /dev/null +++ b/crates/horizon-world/examples/probe/piston_push_fixture.rs @@ -0,0 +1,163 @@ +//! The moving-piston push maths against the real game: `PistonMath.getMovementArea`, +//! `moveByPositionAndProgress`, `getMovement`, the `moveCollidedEntities` loop +//! over the block's own boxes, and `moveStuckEntities`' box with +//! `matchesStickyCritera`. +use crate::support::common::f64_hex; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::{level::data::PushReaction, piston_push, piston_shape::MovingPistonState}; +use serde_json::Value; +use std::{ + fs, + io::{self, BufWriter, Write}, + path::Path, +}; + +fn number(v: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} + +fn float(v: &Value) -> f32 { + f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap()) +} + +fn aabb(v: &Value) -> Aabb { + let a = v.as_array().unwrap(); + Aabb::new( + Vec3::new(number(&a[0]), number(&a[1]), number(&a[2])), + Vec3::new(number(&a[3]), number(&a[4]), number(&a[5])), + ) +} + +fn direction(index: i64) -> Direction { + Direction::ALL[index.rem_euclid(6) as usize] +} + +fn reaction(index: i64) -> PushReaction { + match index.rem_euclid(5) { + 0 => PushReaction::PushPull, + 1 => PushReaction::Push, + 2 => PushReaction::Popped, + 3 => PushReaction::Immoveable, + _ => PushReaction::IgnoreEntity, + } +} + +fn line(out: &mut impl Write, name: &str, b: Aabb) -> io::Result<()> { + let (min, max) = (b.min_position(), b.max_position()); + writeln!( + out, + "{name} {} {} {} {} {} {}", + f64_hex(min.x), + f64_hex(min.y), + f64_hex(min.z), + f64_hex(max.x), + f64_hex(max.y), + f64_hex(max.z) + ) +} + +pub fn main() -> Result<(), Box> { + let arg = crate::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let mut out = BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for text in fs::read_to_string(dir.join("inputs.txt"))?.lines() { + let f: Value = serde_json::from_str(text)?; + let p = &f["pos"]; + let pos = BlockPos::new( + p[0].as_i64().unwrap() as i32, + p[1].as_i64().unwrap() as i32, + p[2].as_i64().unwrap() as i32, + ); + let progress = float(&f["progress"]); + let piston = MovingPistonState { + moved_state: horizon_world::registry::BlockStateId(0), + direction: direction(f["direction"].as_i64().unwrap()), + extending: f["extending"].as_bool().unwrap(), + source: f["source"].as_bool().unwrap(), + progress, + previous_progress: progress, + }; + let new_progress = float(&f["new_progress"]); + let delta_progress = f64::from(new_progress - progress); + let movement = piston.movement_direction(); + let block_box = aabb(&f["block_box"]); + let entity = aabb(&f["entity"]); + let movement_box = aabb(&f["movement_box"]); + + writeln!( + out, + "extended {:08x}", + piston_push::extended_progress(piston, progress).to_bits() + )?; + let origin = piston_push::move_by_position_and_progress(pos, block_box, piston); + line(&mut out, "origin", origin)?; + line( + &mut out, + "area", + piston_push::movement_area(block_box, movement, delta_progress), + )?; + for (name, face) in [ + ("east", Direction::East), + ("west", Direction::West), + ("up", Direction::Up), + ("down", Direction::Down), + ("south", Direction::South), + ("north", Direction::North), + ] { + writeln!( + out, + "movement {name} {}", + f64_hex(piston_push::get_movement(movement_box, face, entity)) + )?; + } + + // `moveCollidedEntities`' loop: the furthest box reaches into the + // entity, capped at the progress delta, plus the push offset. + let boxes: Vec = f["boxes"].as_array().unwrap().iter().map(aabb).collect(); + let mut delta: f64 = 0.0; + let mut capped = false; + for block in &boxes { + let moving = piston_push::movement_area( + piston_push::move_by_position_and_progress(pos, *block, piston), + movement, + delta_progress, + ); + if moving.intersects(entity) { + delta = delta.max(piston_push::get_movement(moving, movement, entity)); + if delta >= delta_progress { + capped = true; + break; + } + } + } + let collided = if delta <= 0.0 { + 0.0 + } else { + delta.min(delta_progress) + piston_push::PUSH_OFFSET + }; + writeln!(out, "collided {} {capped}", f64_hex(collided))?; + line( + &mut out, + "search", + piston_push::movement_search_area(origin, movement, delta_progress), + )?; + let sticky = piston_push::sticky_area(pos, piston, number(&f["sticky_top"])); + line(&mut out, "sticky", sticky)?; + writeln!( + out, + "matches {}", + piston_push::matches_sticky_criteria( + sticky, + reaction(f["reaction"].as_i64().unwrap()), + f["on_ground"].as_bool().unwrap(), + f["supported"].as_bool().unwrap(), + Vec3::new(number(&f["entity_x"]), 0.0, number(&f["entity_z"])), + ) + )?; + } + out.flush()?; + Ok(()) +} diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 831dea544..8f17ba1cc 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -559,20 +559,26 @@ impl Behaviours { sim.game_event_state(pos, "minecraft:block_change", next); } - /// The state change of `RedStoneOreBlock.attack` when mining begins. + /// `BlockBehaviour.attack` when mining begins: `RedStoneOreBlock.attack` + /// lights the ore, `NoteBlock.attack` plays the note. True for a note + /// block, whose player also earns the `play_noteblock` statistic. pub fn attack_block( &self, level: &mut L, ticks: &mut Ticks, pos: BlockPos, - ) { + ) -> bool { let mut sim = self.sim(level, ticks); let state = sim.state(pos); - if self.data(state).chain.contains(&Class::RedStoneOre) - && !self.table.bool(state, self.props.lit) - { + let chain = &self.data(state).chain; + if chain.contains(&Class::Note) { + sim.note_play(pos, state); + return true; + } + if chain.contains(&Class::RedStoneOre) && !self.table.bool(state, self.props.lit) { sim.set_block_and_update(pos, self.table.set_bool(state, self.props.lit, true)); } + false } /// `BlockState.useWithoutItem` for a right-click on `pos` (hit face and @@ -641,6 +647,25 @@ impl Behaviours { if self.data(state).chain.contains(&Class::CopperGolemStatue) { return self.turn_statue(level, ticks, pos, state, item); } + // NoteBlock.useItemOn: a mob head on the top face is placed, not tuned + // (`#minecraft:noteblock_top_instruments`). + if face == Direction::Up + && self.data(state).chain.contains(&Class::Note) + && item.is_some_and(|i| { + matches!( + i, + "minecraft:zombie_head" + | "minecraft:skeleton_skull" + | "minecraft:creeper_head" + | "minecraft:dragon_head" + | "minecraft:wither_skeleton_skull" + | "minecraft:piglin_head" + | "minecraft:player_head" + ) + }) + { + return InteractionResult::Pass; + } self.use_without_item(level, ticks, pos, face, hit, player) } diff --git a/crates/horizon-world/src/level/pistons.rs b/crates/horizon-world/src/level/pistons.rs index 45e469efd..70e8aa32a 100644 --- a/crates/horizon-world/src/level/pistons.rs +++ b/crates/horizon-world/src/level/pistons.rs @@ -182,7 +182,9 @@ impl Sim<'_, L> { self.neighbor_changed_at(pos, block); } } - /// `PistonMovingBlockEntity.tick` (entity pushing excluded). + /// `PistonMovingBlockEntity.tick`. A piston that is still moving reports + /// the push `moveCollidedEntities` would do at its new progress; the caller + /// moves the entities, because `Ticks` has none (`piston_pushes`). fn moving_piston_tick(&mut self, pos: BlockPos) { let Some(mut piston) = self.moving_piston(pos) else { return; @@ -227,14 +229,20 @@ impl Sim<'_, L> { } } } else { - piston.progress = (piston.progress + 0.5).min(1.0); - if let Some(entry) = self + // moveCollidedEntities and moveStuckEntities run with the new + // progress but read the old one off the entity (their delta), + // so the push carries the piston as it was before the advance. + let old = piston; + let new_progress = (old.progress + 0.5).min(1.0); + let current = self .ticks .moving_pistons .iter_mut() - .find(|(p, _)| *p == pos) - { + .find(|(p, _)| *p == pos); + if let Some(entry) = current { + piston.progress = new_progress; entry.1 = piston; + self.ticks.piston_pushes.push((pos, old, new_progress)); } } } diff --git a/crates/horizon-world/src/level/tick.rs b/crates/horizon-world/src/level/tick.rs index 25e2a19d3..51b6b8083 100644 --- a/crates/horizon-world/src/level/tick.rs +++ b/crates/horizon-world/src/level/tick.rs @@ -1478,6 +1478,80 @@ impl Sim<'_, L> { let block = b.table.block_by_name(&format!("minecraft:{next}"))?; Some(b.table.with_properties_of(block, state)) } + /// `WeatheringCopper.getPrevious` (and `getFirst` by repeating it) by + /// registry naming: the block one oxidation step back. + fn copper_previous_name(path: &str) -> Option { + if let Some(rest) = path.strip_prefix("oxidized_") { + Some(format!("weathered_{rest}")) + } else if let Some(rest) = path.strip_prefix("weathered_") { + Some(format!("exposed_{rest}")) + } else { + path.strip_prefix("exposed_").map(|rest| { + if rest == "copper" { + "copper_block".to_owned() + } else { + rest.to_owned() + } + }) + } + } + fn copper_stepped(&self, state: BlockStateId, all_the_way: bool) -> Option { + let b = self.b; + let name = &*b.table.info(b.block(state)).name; + let mut path = Self::copper_previous_name(name.strip_prefix("minecraft:")?)?; + while all_the_way && let Some(earlier) = Self::copper_previous_name(&path) { + path = earlier; + } + let block = b.table.block_by_name(&format!("minecraft:{path}"))?; + Some(b.table.with_properties_of(block, state)) + } + /// `LightningBolt.clearCopperOnLightningStrike`: the struck copper goes + /// back to unoxidized, then 3 to 5 random walks of up to 8 steps each + /// scrape one step of oxidation off the weathering copper they land on. + /// A waxed block is left as it is but still starts the walks. + pub(crate) fn lightning_clear_copper(&mut self, struck: BlockPos) { + let b = self.b; + let state = self.state(struck); + let weathering = b + .data(state) + .implements(super::classes::Interface::WeatheringCopper); + let waxed = b.table.name(state).starts_with("minecraft:waxed_"); + if !(weathering || waxed) { + return; + } + if weathering && let Some(first) = self.copper_stepped(state, true) { + self.set_block_and_update(struck, first); + } + for _ in 0..self.rand_int(3) + 3 { + let mut at = struck; + for _ in 0..self.rand_int(8) + 1 { + // randomStepCleaningCopper: up to 10 random blocks in the + // 3x3x3 cube around the walk's position. + let mut next = None; + for _ in 0..10 { + let x = at.x - 1 + self.rand_int(3); + let y = at.y - 1 + self.rand_int(3); + let z = at.z - 1 + self.rand_int(3); + let candidate = BlockPos::new(x, y, z); + let state = self.state(candidate); + if b.data(state) + .implements(super::classes::Interface::WeatheringCopper) + { + if let Some(previous) = self.copper_stepped(state, false) { + self.set_block_and_update(candidate, previous); + } + self.level_event(3002, candidate, -1); + next = Some(candidate); + break; + } + } + match next { + Some(p) => at = p, + None => break, + } + } + } + } } /// `Biome.Precipitation` at a position. @@ -1661,6 +1735,15 @@ impl Behaviours { ) { self.sim(level, ticks).random_tick_at(pos); } + /// `LightningBolt.clearCopperOnLightningStrike` for the block at `struck`. + pub fn lightning_clear_copper( + &self, + level: &mut L, + ticks: &mut Ticks, + struck: BlockPos, + ) { + self.sim(level, ticks).lightning_clear_copper(struck); + } /// Run one scheduled block tick at `pos` immediately (no queue check). pub fn scheduled_block_tick( &self, diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs index c8d715623..195078e31 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -29,6 +29,11 @@ pub struct Ticks { /// Moving-piston block entities in ticker order (render and collide /// moving blocks from these; see `piston_shape`). pub moving_pistons: Vec<(BlockPos, super::pistons::MovingPiston)>, + /// The pushes this tick's moving-piston block entities asked for: each + /// piston with the progress it is about to reach, in the order they ticked + /// (`PistonMovingBlockEntity.tick`'s `moveCollidedEntities` call). The + /// caller moves entities by these; `Ticks` has no entities of its own. + pub piston_pushes: Vec<(BlockPos, super::pistons::MovingPiston, f32)>, pub(crate) next_block_entity_id: u64, /// `ServerLevel.blockEvents`, run by `Behaviours::run_block_events`. pub block_events: Vec, @@ -65,6 +70,7 @@ impl Ticks { comparator_outputs: Default::default(), torch_toggles: Vec::new(), moving_pistons: Vec::new(), + piston_pushes: Vec::new(), next_block_entity_id: 0, block_events: Vec::new(), handling_tick: false, diff --git a/crates/horizon-world/src/lib.rs b/crates/horizon-world/src/lib.rs index b6d05ecf6..6df870d42 100644 --- a/crates/horizon-world/src/lib.rs +++ b/crates/horizon-world/src/lib.rs @@ -94,6 +94,7 @@ pub mod nbt; pub mod object_open_map; pub mod object_open_set; pub mod piston_movement; +pub mod piston_push; pub mod piston_shape; pub mod player_food; pub mod player_health; diff --git a/crates/horizon-world/src/piston_push.rs b/crates/horizon-world/src/piston_push.rs new file mode 100644 index 000000000..5f64f22ba --- /dev/null +++ b/crates/horizon-world/src/piston_push.rs @@ -0,0 +1,461 @@ +//! `PistonMovingBlockEntity.moveCollidedEntities`, `moveStuckEntities` and +//! `fixEntityWithinPistonBase` over immutable geometry. +//! +//! Entity storage, the moving entities themselves and the blocks they collide +//! with belong to the caller: these functions decide *how far* an entity is +//! pushed, which is the part that must match vanilla to the bit. The movement +//! they describe is an `Entity.move(MoverType.PISTON, …)`, so the caller still +//! applies it through its own collision resolution and per-tick piston limit. +use crate::{level::data::PushReaction, piston_shape::MovingPistonState}; +use horizon_core::{ + geometry::{Aabb, Direction, Vec3}, + position::BlockPos, +}; + +/// `PistonMovingBlockEntity.PUSH_OFFSET`. +pub const PUSH_OFFSET: f64 = 0.01; + +/// `PistonMovingBlockEntity.getExtendedProgress`: where along its travel the +/// moved block is, in blocks (negative before it starts, 0 when it arrives). +pub fn extended_progress(piston: MovingPistonState, progress: f32) -> f32 { + if piston.extending { + progress - 1.0 + } else { + 1.0 - progress + } +} + +/// `Direction.getAxisDirection().getStep()`. +fn step_along(direction: Direction) -> i32 { + match direction { + Direction::East | Direction::Up | Direction::South => 1, + Direction::West | Direction::Down | Direction::North => -1, + } +} + +/// `Direction.getStepX/Y/Z` as a vector. +pub fn step_vector(direction: Direction) -> Vec3 { + let [x, y, z] = direction.normal(); + Vec3::new(f64::from(x), f64::from(y), f64::from(z)) +} + +/// `PistonMath.getMovementArea`: the slab an entity's box must reach into to be +/// run over by `amount` of further travel along `direction`. +pub fn movement_area(aabb: Aabb, direction: Direction, amount: f64) -> Aabb { + let delta = amount * f64::from(step_along(direction)); + let low = delta.min(0.0); + let high = delta.max(0.0); + let (min, max) = (aabb.min_position(), aabb.max_position()); + match direction { + Direction::West => Aabb::new( + Vec3::new(min.x + low, min.y, min.z), + Vec3::new(min.x + high, max.y, max.z), + ), + Direction::East => Aabb::new( + Vec3::new(max.x + low, min.y, min.z), + Vec3::new(max.x + high, max.y, max.z), + ), + Direction::Down => Aabb::new( + Vec3::new(min.x, min.y + low, min.z), + Vec3::new(max.x, min.y + high, max.z), + ), + Direction::Up => Aabb::new( + Vec3::new(min.x, max.y + low, min.z), + Vec3::new(max.x, max.y + high, max.z), + ), + Direction::North => Aabb::new( + Vec3::new(min.x, min.y, min.z + low), + Vec3::new(max.x, max.y, min.z + high), + ), + Direction::South => Aabb::new( + Vec3::new(min.x, min.y, max.z + low), + Vec3::new(max.x, max.y, max.z + high), + ), + } +} + +/// `PistonMovingBlockEntity.moveByPositionAndProgress`: a box moved to the +/// block position and on to where the moved block currently is. +pub fn move_by_position_and_progress(pos: BlockPos, aabb: Aabb, piston: MovingPistonState) -> Aabb { + let current = f64::from(extended_progress(piston, piston.progress)); + let step = step_vector(piston.direction); + aabb.move_by(Vec3::new( + f64::from(pos.x) + current * step.x, + f64::from(pos.y) + current * step.y, + f64::from(pos.z) + current * step.z, + )) +} + +/// `PistonMovingBlockEntity.getMovement`: how far `entity` stands inside the +/// block it must be pushed out of, measured along `movement`'s axis. +pub fn get_movement(block: Aabb, movement: Direction, entity: Aabb) -> f64 { + let (bmin, bmax) = (block.min_position(), block.max_position()); + let (emin, emax) = (entity.min_position(), entity.max_position()); + match movement { + Direction::East => bmax.x - emin.x, + Direction::West => emax.x - bmin.x, + Direction::Up => bmax.y - emin.y, + Direction::Down => emax.y - bmin.y, + Direction::South => bmax.z - emin.z, + Direction::North => emax.z - bmin.z, + } +} + +/// `moveCollidedEntities`' inner loop: the furthest any of the moved block's +/// boxes reaches into `entity`, capped at the progress delta, plus +/// [`PUSH_OFFSET`]. `0.0` when the block does not touch the entity. +pub fn collided_amount( + boxes: &[Aabb], + pos: BlockPos, + piston: MovingPistonState, + new_progress: f32, + movement: Direction, + entity: Aabb, +) -> f64 { + let delta_progress = f64::from(new_progress - piston.progress); + let mut delta: f64 = 0.0; + for block in boxes { + let moving = movement_area( + move_by_position_and_progress(pos, *block, piston), + movement, + delta_progress, + ); + if moving.intersects(entity) { + delta = delta.max(get_movement(moving, movement, entity)); + if delta >= delta_progress { + break; + } + } + } + if delta <= 0.0 { + return 0.0; + } + delta.min(delta_progress) + PUSH_OFFSET +} + +/// The box `level.getEntities` searches for a push: the moved block's own box +/// widened by the slab it is about to sweep. +pub fn movement_search_area(block_box: Aabb, movement: Direction, delta_progress: f64) -> Aabb { + movement_area(block_box, movement, delta_progress).union_bounds(block_box) +} + +/// `moveStuckEntities`: the box of standing entities a moving honey block drags +/// with it. `sticky_top` is the moved state's top collision height. +pub fn sticky_area(pos: BlockPos, piston: MovingPistonState, sticky_top: f64) -> Aabb { + let area = Aabb::new( + Vec3::new(0.0, sticky_top, 0.0), + Vec3::new(1.0, 1.500_001_000_000_000_1, 1.0), + ); + move_by_position_and_progress(pos, area, piston) +} + +/// `PistonMovingBlockEntity.matchesStickyCritera`. +pub fn matches_sticky_criteria( + area: Aabb, + reaction: PushReaction, + on_ground: bool, + supported_by_piston: bool, + entity_position: Vec3, +) -> bool { + if reaction != PushReaction::PushPull || !on_ground { + return false; + } + if supported_by_piston { + return true; + } + let (min, max) = (area.min_position(), area.max_position()); + entity_position.x >= min.x + && entity_position.x <= max.x + && entity_position.z >= min.z + && entity_position.z <= max.z +} + +/// The level query intersects the sticky box before applying the predicate. +pub fn sticky_entity_selected( + area: Aabb, + bounds: Aabb, + reaction: PushReaction, + on_ground: bool, + supported_by_piston: bool, + position: Vec3, +) -> bool { + area.intersects(bounds) + && matches_sticky_criteria(area, reaction, on_ground, supported_by_piston, position) +} + +/// `fixEntityWithinPistonBase`: a retracting source piston drags an entity that +/// is still inside the piston's own block out along the opposite of `movement`. +/// The returned distance is measured along that opposite direction. +pub fn fix_within_piston_base( + pos: BlockPos, + entity: Aabb, + movement: Direction, + delta_progress: f64, +) -> Option { + let block = Aabb::unit_cube(Vec3::from_block(pos)); + if !entity.intersects(block) { + return None; + } + let opposite = movement.opposite(); + let delta = get_movement(block, opposite, entity) + PUSH_OFFSET; + let intersected = entity.intersect(block); + let delta_intersected = get_movement(block, opposite, intersected) + PUSH_OFFSET; + // As deep inside as the block allows: it is stuck in the base itself, so it + // leaves along with the retraction. + if (delta - delta_intersected).abs() < PUSH_OFFSET { + Some(delta.min(delta_progress) + PUSH_OFFSET) + } else { + None + } +} + +/// `PistonMovingBlockEntity.getCollisionRelatedBlockState` uses the moved state +/// unless a source piston is retracting, where it shows a piston head instead. +/// The state itself comes from [`PistonBlockBindings::collision_related_state`]. +/// +/// [`PistonBlockBindings::collision_related_state`]: +/// crate::piston_shape::PistonBlockBindings::collision_related_state +pub fn uses_moved_state(piston: MovingPistonState) -> bool { + piston.extending || !piston.source +} + +/// `moveCollidedEntities`' slime bounce: a slime block sets the velocity along +/// the movement axis to that direction's step, leaving the other axes. +pub fn bounce_velocity(movement: Direction, velocity: Vec3) -> Vec3 { + let mut velocity = velocity; + match movement { + Direction::East => velocity.x = 1.0, + Direction::West => velocity.x = -1.0, + Direction::Up => velocity.y = 1.0, + Direction::Down => velocity.y = -1.0, + Direction::South => velocity.z = 1.0, + Direction::North => velocity.z = -1.0, + } + velocity +} + +/// `Entity.getPistonPushReaction() == PushReaction.IGNORE_ENTITY`. +/// +/// `Marker`, `Interaction`, `Display`, `AreaEffectCloud` and +/// `OminousItemSpawner` return `IGNORE_ENTITY`, and an armor stand does when it +/// is a marker. Horizon gives those kinds no pushed body, so a caller that has +/// no box to push never reaches the maths above; this names the predicate for +/// the kinds that do have one. +pub fn ignores_push(marker: bool) -> bool { + marker +} + +#[cfg(test)] +mod tests { + use super::*; + + fn unit() -> Aabb { + Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 1.0)) + } + + fn moving(direction: Direction, extending: bool, progress: f32) -> MovingPistonState { + MovingPistonState { + moved_state: crate::registry::BlockStateId(0), + direction, + extending, + source: false, + progress, + previous_progress: progress, + } + } + + /// `getMovementArea` puts the slab on the leading face and widens it by the + /// travel in that direction only. + #[test] + fn movement_area_sits_on_the_leading_face() { + let east = movement_area(unit(), Direction::East, 0.5); + assert_eq!(east.min_position(), Vec3::new(1.0, 0.0, 0.0)); + assert_eq!(east.max_position(), Vec3::new(1.5, 1.0, 1.0)); + + let west = movement_area(unit(), Direction::West, 0.5); + assert_eq!(west.min_position(), Vec3::new(-0.5, 0.0, 0.0)); + assert_eq!(west.max_position(), Vec3::new(0.0, 1.0, 1.0)); + + let up = movement_area(unit(), Direction::Up, 0.5); + assert_eq!(up.min_position(), Vec3::new(0.0, 1.0, 0.0)); + assert_eq!(up.max_position(), Vec3::new(1.0, 1.5, 1.0)); + + let north = movement_area(unit(), Direction::North, 0.5); + assert_eq!(north.min_position(), Vec3::new(0.0, 0.0, -0.5)); + assert_eq!(north.max_position(), Vec3::new(1.0, 1.0, 0.0)); + } + + /// A negative amount sweeps behind the leading face. + #[test] + fn movement_area_follows_a_negative_amount() { + let area = movement_area(unit(), Direction::East, -0.5); + assert_eq!(area.min_position(), Vec3::new(0.5, 0.0, 0.0)); + assert_eq!(area.max_position(), Vec3::new(1.0, 1.0, 1.0)); + } + + /// The arm of a piston at the origin: the block entity sits in the block it + /// pushes into, and at progress 0 its shape is still a block back. + const ARM: BlockPos = BlockPos::new(1, 0, 0); + + /// An entity in the way is pushed the progress delta, plus the push offset; + /// here it hangs 0.6 into the slab and the delta caps it at 0.5. + #[test] + fn a_collided_entity_moves_the_progress_delta() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(0.9, 0.0, 0.2), Vec3::new(1.5, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert!((amount - (0.5 + PUSH_OFFSET)).abs() < 1.0e-12, "{amount}"); + } + + /// The delta is not a floor: an entity barely nicking the slab moves by only + /// what it is owed, plus the offset. + #[test] + fn a_grazed_entity_moves_only_what_it_overlaps() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(1.4, 0.0, 0.2), Vec3::new(2.0, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert!((amount - (0.1 + PUSH_OFFSET)).abs() < 1.0e-12, "{amount}"); + } + + /// Clear of the block, nothing moves. + #[test] + fn an_entity_out_of_the_way_is_left_alone() { + let piston = moving(Direction::East, true, 0.0); + let entity = Aabb::new(Vec3::new(3.0, 0.0, 0.2), Vec3::new(3.6, 1.8, 0.8)); + let amount = collided_amount(&[unit()], ARM, piston, 0.5, Direction::East, entity); + assert_eq!(amount, 0.0); + } + + /// A retracting base drags an entity stuck inside its own block, limited by + /// the progress delta. + #[test] + fn a_retracting_base_drags_a_stuck_entity() { + let entity = Aabb::new(Vec3::new(0.75, 0.0, 0.2), Vec3::new(1.35, 1.8, 0.8)); + let amount = fix_within_piston_base(BlockPos::new(0, 0, 0), entity, Direction::West, 0.5) + .expect("stuck in the base"); + assert!(amount > 0.0 && amount <= 0.5 + PUSH_OFFSET, "{amount}"); + } + + /// An entity outside the base's block is not dragged by it. + #[test] + fn a_free_entity_is_not_dragged_by_the_base() { + let entity = Aabb::new(Vec3::new(2.0, 0.0, 0.2), Vec3::new(2.6, 1.8, 0.8)); + assert_eq!( + fix_within_piston_base(BlockPos::new(0, 0, 0), entity, Direction::West, 0.5), + None + ); + } + + /// Honey drags only entities that stand on it and that blocks may push. + #[test] + fn honey_drags_standing_entities() { + let area = Aabb::new(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.5, 1.0)); + let on_top = Vec3::new(0.5, 0.0, 0.5); + assert!(matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + false, + on_top + )); + assert!(!matches_sticky_criteria( + area, + PushReaction::PushPull, + false, + false, + on_top + )); + assert!(!matches_sticky_criteria( + area, + PushReaction::Immoveable, + true, + false, + on_top + )); + // Beside it: only standing on the piston's own block holds it. + let beside = Vec3::new(2.0, 0.0, 0.5); + assert!(!matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + false, + beside + )); + assert!(matches_sticky_criteria( + area, + PushReaction::PushPull, + true, + true, + beside + )); + } + + #[test] + fn honey_selection_uses_entity_position_and_intersection() { + let area = Aabb::new(Vec3::new(0.0, 1.0, 0.0), Vec3::new(1.0, 1.5, 1.0)); + let position = Vec3::new(0.1, 1.0, 0.5); + let bounds = Aabb::new(Vec3::new(-0.2, 1.0, 0.2), Vec3::new(0.4, 2.8, 0.8)); + assert!(sticky_entity_selected( + area, + bounds, + PushReaction::PushPull, + true, + false, + position + )); + let above = bounds.move_by(Vec3::new(0.0, 3.0, 0.0)); + assert!(!sticky_entity_selected( + area, + above, + PushReaction::PushPull, + true, + true, + position + )); + } + + /// The slime bounce rewrites only the movement axis. + #[test] + fn a_slime_block_bounces_along_its_axis() { + let v = Vec3::new(0.2, -0.5, 0.3); + assert_eq!( + bounce_velocity(Direction::East, v), + Vec3::new(1.0, -0.5, 0.3) + ); + assert_eq!(bounce_velocity(Direction::Up, v), Vec3::new(0.2, 1.0, 0.3)); + assert_eq!( + bounce_velocity(Direction::North, v), + Vec3::new(0.2, -0.5, -1.0) + ); + } + + /// The moved block sits along the piston's own direction, half a block short + /// at mid-travel and in place once landed. + #[test] + fn the_moved_block_sits_along_the_piston_direction() { + let half = moving(Direction::East, true, 0.5); + let moved = move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), half); + assert_eq!(moved.min_position(), Vec3::new(1.5, 3.0, 4.0)); + + let landed = moving(Direction::East, true, 1.0); + assert_eq!( + move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), landed).min_position(), + Vec3::new(2.0, 3.0, 4.0) + ); + + // Retracting runs the other way: two thirds out at progress 1/3. + let pulling = moving(Direction::East, false, 0.5); + assert_eq!( + move_by_position_and_progress(BlockPos::new(2, 3, 4), unit(), pulling).min_position(), + Vec3::new(2.5, 3.0, 4.0) + ); + } + + /// The search area covers the block and the slab in front of it. + #[test] + fn the_search_area_covers_block_and_sweep() { + let area = movement_search_area(unit(), Direction::East, 0.5); + assert_eq!(area.min_position(), Vec3::new(0.0, 0.0, 0.0)); + assert_eq!(area.max_position(), Vec3::new(1.5, 1.0, 1.0)); + } +} diff --git a/docs/resource-packs.md b/docs/resource-packs.md index 69eee3393..f29569068 100644 --- a/docs/resource-packs.md +++ b/docs/resource-packs.md @@ -31,7 +31,7 @@ harness named checks that loader against vanilla). | --- | --- | --- | --- | | Pack metadata: description, icon, `min_format`/`max_format`, old `supported_formats`, compatibility warning | `pack.mcmeta`, `pack.png` | works | `test_pack_screen_parity`, `test_pack_selection_parity` | | Overlays per format | `pack.mcmeta` `overlays` | works | `test_resource_pack_parity` (an overlay for 26.3 applied, an older one not) | -| Filters | `pack.mcmeta` `filter` | works | `test_resource_pack_parity` (`packs/pattern.rs` regex subset) | +| Filters | `pack.mcmeta` `filter` | works | `test_resource_pack_parity` (`horizon-client-core/src/pattern.rs` regex subset) | | Folder and zip packs, order, built-in packs | `resourcepacks/` | works | `test_resource_pack_parity`, `test_pack_selection_parity` | | Server resource packs: the prompt, the server list's Server Resource Packs setting, download (250 MiB, SHA-1, `downloads/` keeps 20), download toasts, a progress screen while the packs reload, applied on top of the player's packs, removed on leaving | the server's `resource_pack_push`/`_pop` | works | `tools/server_pack_e2e.py` (against vanilla's server and Horizon's), unit tests in `server_packs.rs`; `test_server_resource_pack_parity` for Horizon's server | | Other namespaces | `assets//` | works | `test_resource_pack_parity` | diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java new file mode 100644 index 000000000..f1cee2fc2 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java @@ -0,0 +1,78 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.monster.zombie.Zombie; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.piston.*; +import net.minecraft.world.phys.*; +import net.minecraft.world.phys.shapes.*; +/** + * The real moving-piston push maths: PistonMath.getMovementArea, + * moveByPositionAndProgress, getMovement, the moveCollidedEntities loop over + * the block's own boxes, and moveStuckEntities' box and matchesStickyCritera. + * fixEntityWithinPistonBase is left out: it moves the entity + * (`Entity.move(MoverType.PISTON, ...)`), which needs a live level, so the + * Rust side is covered by its own unit tests. + */ +public final class VanillaPistonPushOracle { + private static float number(JsonElement v){return Float.intBitsToFloat(Integer.parseUnsignedInt(v.getAsString(),16));} + private static double dbl(JsonElement v){return Double.longBitsToDouble(Long.parseUnsignedLong(v.getAsString(),16));} + private static AABB box(JsonElement v){var a=v.getAsJsonArray();return new AABB(dbl(a.get(0)),dbl(a.get(1)),dbl(a.get(2)),dbl(a.get(3)),dbl(a.get(4)),dbl(a.get(5)));} + private static void line(PrintWriter out,String name,AABB b){out.printf(name+" %016x %016x %016x %016x %016x %016x%n",Double.doubleToLongBits(b.minX),Double.doubleToLongBits(b.minY),Double.doubleToLongBits(b.minZ),Double.doubleToLongBits(b.maxX),Double.doubleToLongBits(b.maxY),Double.doubleToLongBits(b.maxZ));} + private static Field field(Class c,String name)throws Exception{var f=c.getDeclaredField(name);f.setAccessible(true);return f;} + private static Method method(Class c,String name,Class...types)throws Exception{var m=c.getDeclaredMethod(name,types);m.setAccessible(true);return m;} + @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + var allocator=Class.forName("sun.misc.Unsafe");var uf=allocator.getDeclaredField("theUnsafe");uf.setAccessible(true);var unsafe=uf.get(null);var allocate=allocator.getMethod("allocateInstance",Class.class); + var progress=field(PistonMovingBlockEntity.class,"progress"); + var movedBy=method(PistonMovingBlockEntity.class,"moveByPositionAndProgress",BlockPos.class,AABB.class,PistonMovingBlockEntity.class); + var extended=method(PistonMovingBlockEntity.class,"getExtendedProgress",float.class); + var getMovement=method(PistonMovingBlockEntity.class,"getMovement",AABB.class,Direction.class,AABB.class); + var matches=method(PistonMovingBlockEntity.class,"matchesStickyCritera",AABB.class,Entity.class,BlockPos.class); + var movementDir=method(PistonMovingBlockEntity.class,"getMovementDirection"); + var position=field(Entity.class,"position");var onGroundField=field(Entity.class,"onGround");var supporting=field(Entity.class,"mainSupportingBlockPos");var bbField=field(Entity.class,"bb"); + var faces=new Direction[]{Direction.EAST,Direction.WEST,Direction.UP,Direction.DOWN,Direction.SOUTH,Direction.NORTH}; + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator) { + var f=JsonParser.parseString(line).getAsJsonObject();var v=f.getAsJsonArray("pos");var p=new BlockPos(v.get(0).getAsInt(),v.get(1).getAsInt(),v.get(2).getAsInt()); + var direction=Direction.values()[f.get("direction").getAsInt()]; + var piston=new PistonMovingBlockEntity(p,Blocks.MOVING_PISTON.defaultBlockState(),Blocks.STONE.defaultBlockState(),direction,f.get("extending").getAsBoolean(),f.get("source").getAsBoolean()); + float current=number(f.get("progress")); + progress.setFloat(piston,current); + float newProgress=number(f.get("new_progress")); + double deltaProgress=newProgress-current; + Direction movement=(Direction)movementDir.invoke(piston); + AABB blockBox=box(f.get("block_box")); + AABB entityBox=box(f.get("entity")); + AABB movementBox=box(f.get("movement_box")); + out.printf("extended %08x%n",Float.floatToIntBits((float)extended.invoke(piston,current))); + AABB origin=(AABB)movedBy.invoke(null,p,blockBox,piston); + line(out,"origin",origin); + line(out,"area",PistonMath.getMovementArea(blockBox,movement,deltaProgress)); + for(var face:faces)out.printf("movement %s %016x%n",face.getSerializedName(),Double.doubleToLongBits((double)getMovement.invoke(null,movementBox,face,entityBox))); + double delta=0.0;boolean capped=false; + for(var value:f.getAsJsonArray("boxes")){ + AABB movingAABB=PistonMath.getMovementArea((AABB)movedBy.invoke(null,p,box(value),piston),movement,deltaProgress); + if(movingAABB.intersects(entityBox)){delta=Math.max(delta,(double)getMovement.invoke(null,movingAABB,movement,entityBox));if(delta>=deltaProgress){capped=true;break;}} + } + double collided=delta<=0.0?0.0:Math.min(delta,deltaProgress)+0.01; + out.printf("collided %016x %b%n",Double.doubleToLongBits(collided),capped); + line(out,"search",PistonMath.getMovementArea(origin,movement,deltaProgress).minmax(origin)); + AABB sticky=(AABB)movedBy.invoke(null,p,new AABB(0.0,dbl(f.get("sticky_top")),0.0,1.0,1.5000010000000001,1.0),piston); + line(out,"sticky",sticky); + boolean pushable=f.get("reaction").getAsInt()==0; + var entity=(Entity)allocate.invoke(unsafe,pushable?Zombie.class:Marker.class); + position.set(entity,new Vec3(dbl(f.get("entity_x")),0.0,dbl(f.get("entity_z")))); + bbField.set(entity,entityBox); + onGroundField.setBoolean(entity,f.get("on_ground").getAsBoolean()); + supporting.set(entity,f.get("supported").getAsBoolean()?Optional.of(p):Optional.empty()); + out.printf("matches %b%n",(boolean)matches.invoke(null,sticky,entity,p)); + } + } + } +} \ No newline at end of file diff --git a/tests/test_remote_motion.py b/tests/test_remote_motion.py index b00e5f0a9..59526b476 100644 --- a/tests/test_remote_motion.py +++ b/tests/test_remote_motion.py @@ -35,7 +35,8 @@ impl End { fn remote_eye_motion(&mut self, _id: u32, _v: [f64; 3]) {} } #[derive(Default)] struct Game { mobs: Vec, dropped: Vec, falling: Vec, tnts: Vec, - creatures: Creatures, dragon_fireballs: Vec, remote: Option, + creatures: Creatures, dragon_fireballs: Vec, rockets: Vec, + remote: Option, potions: Potions, end: End, } impl Game { diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 442d4f809..1a0b25a9d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -24,7 +24,7 @@ address. The script then checks, from both sides, what a guest's game used to ge - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, or on one team without friendly fire, nothing; - kills: a pig the guest kills counts in the guest's killed statistic, not the host's (#484); - +- leave: a guest who leaves has leave_game in their saved statistics, and again after the next leave; - arrows: the guest and the host shoot each other with a bow; with the pvp game rule off, nothing (#484); - looks: mobs look on both sides as the server has them (their synched data): a calf is a @@ -301,10 +301,10 @@ GUEST_NAME = 'Guest' # Match normal single player; --in-frame is the comparison path. SERVER_THREAD = True CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'spawned', 'sign', 'damage', 'mobs', 'hazards', 'pvp', - 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', + 'arrows', 'kills', 'leave', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'styles', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', - 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', + 'piston-push', 'piston-slime', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'doors', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'hands', 'lightning', 'riding', 'occupied_horse', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', @@ -1196,6 +1196,35 @@ def check_pvp(host, guest, out): return hits +def leave_game_total(host): + """The leave_game statistic summed over the stats files the host's world holds.""" + total = 0 + for path in (host.work / 'saves' / 'Lan' / 'players' / 'stats').glob('*.json'): + custom = json.loads(path.read_text()).get('stats', {}).get('minecraft:custom', {}) + total += custom.get('minecraft:leave_game', 0) + return total + + +def check_leave(host, guest, out): + # PlayerList.remove awards Stats.LEAVE_GAME before it saves the player: a guest who leaves has it in + # their saved statistics, and it counts again the next time they leave. + port = host.raw('lan', 'status')['port'] + before = leave_game_total(host) + counts = [] + for _ in range(2): + guest.raw('disconnect') + for _ in range(20): + time.sleep(0.5) + if leave_game_total(host) > (counts[-1] if counts else before): + break + counts.append(leave_game_total(host)) + guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) + guest.raw('wait-for', 'loaded', '--timeout', 300) + guest.wait(20) + assert counts == [before + 1, before + 2], f'leave_game was {before}, then {counts} after two leaves' + return {'leave_game': counts} + + def check_kills(host, guest, out): # A mob the guest kills is the guest's kill (#484): LivingEntity.die credits lastHurtByPlayer, so the # killed statistic (and its scoreboard criterion) counts for the guest, not the host. @@ -2410,6 +2439,168 @@ def wait_state(game, pos, key, want, ticks): return state_of(game, pos, key) +def check_piston_push(host, guest, out): + """A moving piston pushes both players and a stationary mob on each host path.""" + hx, _, hz = pos_of(host) + x, y, z = (int(hx // 16) * 16 + 8, 100, int(hz // 16) * 16 + 8) + host('command', command=f'fill {x-4} {y-1} {z-4} {x+7} {y-1} {z+4} minecraft:stone') + host('command', command=f'fill {x-4} {y} {z-4} {x+7} {y+5} {z+4} minecraft:air') + host('command', command=f'setblock {x} {y} {z} minecraft:piston[facing=east]') + results = {} + for player, name in ((host, host.player), (guest, GUEST_NAME)): + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp {"@s" if player is host else GUEST_NAME} {x+1.65} {y} {z+0.5}') + player.wait(15) + before = pos_of(player) + assert abs(before[0] - (x + 1.65)) < 0.1, f'{name} did not reach piston: {before}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + player.wait(30) + after = pos_of(player) + results[name] = after[0] - before[0] + assert results[name] > 0.3, f'piston did not push {name}: {before} -> {after}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp @s {x+1.65} {y} {z+0.5}') + host.wait(10) + host.raw('key', 'e', 'tap') + host.raw('wait-for', 'screen', 'inventory') + before = pos_of(host) + guest('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + host.wait(30) + after = pos_of(host) + results['inventory'] = after[0] - before[0] + assert results['inventory'] > 0.3, f'piston did not push player with inventory open: {before} -> {after}' + host.raw('key', 'esc', 'tap') + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'summon minecraft:pig {x+1.65} {y} {z+0.5} {{NoAI:1b}}') + host.wait(10) + pigs = host('entities', radius=16, type='pig')['entities'] + pig = min(pigs, key=lambda p: abs(p['pos'][0] - (x + 1.65)) + abs(p['pos'][2] - (z + 0.5))) + before = pig['pos'][0] + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + host.wait(30) + pigs = host('entities', radius=16, type='pig')['entities'] + after = next(p['pos'][0] for p in pigs if p['id'] == pig['id']) + results['pig'] = after - before + assert results['pig'] > 0.3, f'piston did not push pig: {before} -> {after}' + results.update(piston_push_at_border(host, guest)) + return results + + +def piston_push_at_border(host, guest): + """A piston next to the world border: the border's wall stops the pushed + body, as it stops ordinary movement (`Entity.collectCollidersIgnoringWorldBorder`).""" + hx, _, hz = pos_of(host) + x, y, z = (int(hx // 16) * 16 + 8, 100, int(hz // 16) * 16 + 8) + host('command', command=f'fill {x-4} {y-1} {z-4} {x+7} {y-1} {z+4} minecraft:stone') + host('command', command=f'fill {x-4} {y} {z-4} {x+7} {y+5} {z+4} minecraft:air') + host('command', command=f'setblock {x} {y} {z} minecraft:piston[facing=east]') + # The border's east wall stands at `x + 2`, the east face of the block the + # head extends into: a body pushed east stops there instead of being + # pushed out through the border. `worldborder center` centres integers on + # the block, so the centre is `x - 8.5` and the wall lands on `x + 2`. + wall = x + 2 + center = [x - 8.5, z + 0.5] + results = {} + try: + host('command', command=f'worldborder center {x - 9} {z}') + host('command', command='worldborder set 20.5') + seen = None + for _ in range(10): + host.wait(2) + seen = [g('status').get('border') for g in (host, guest)] + if all(b and b['size'] == 20.5 and b['center'] == center for b in seen): + break + results['border'] = seen + for player, name in ((host, host.player), (guest, GUEST_NAME)): + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp {"@s" if player is host else GUEST_NAME} {x+1.65} {y} {z+0.5}') + player.wait(15) + before = pos_of(player) + assert abs(before[0] - (x + 1.65)) < 0.1, f'{name} did not reach the piston: {before}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + player.wait(30) + after = pos_of(player) + # The wall's inner face is at `wall`: the body's box stops there. + results[name] = round(after[0] - before[0], 3) + assert after[0] > before[0], f'the piston did not push {name}: {before} -> {after}' + assert after[0] <= wall - 0.3 + 0.01, f'the border did not stop {name}: {before} -> {after}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + finally: + host('command', command='worldborder center 0 0') + host('command', command='worldborder set 59999968') + return results + + +def check_piston_slime(host, guest, out): + """A piston pushing a slime block: the block pushes the body in front of + it and bounces it (`PistonMovingBlockEntity.moveCollidedEntities`).""" + hx, _, hz = pos_of(host) + x, y, z = (int(hx // 16) * 16 + 8, 100, int(hz // 16) * 16 + 8) + results = {} + + def setup(): + # The previous case may have left a mob where the body stands. + host('command', command='kill @e[type=minecraft:pig]') + host('command', command=f'setblock {x} {y} {z} minecraft:air') + host.wait(10) + host('command', command=f'fill {x-4} {y-1} {z-4} {x+7} {y-1} {z+4} minecraft:stone') + host('command', command=f'fill {x-4} {y} {z-4} {x+7} {y+5} {z+4} minecraft:air') + host('command', command=f'setblock {x} {y} {z} minecraft:piston[facing=east]') + host.wait(5) + + for player, name in ((host, host.player), (guest, GUEST_NAME)): + setup() + host('command', command=f'setblock {x+1} {y} {z} minecraft:slime_block') + host('command', command=f'tp @s {x+5.5} {y} {z+2.5}') + host('command', command=f'tp {GUEST_NAME} {x+5.5} {y} {z-1.5}') + host('command', command=f'tp {"@s" if player is host else GUEST_NAME} {x+2.5} {y} {z+0.5}') + player.wait(15) + before = pos_of(player) + assert abs(before[0] - (x + 2.5)) < 0.1, f'{name} did not reach the slime: {before}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + # The bounce sets the velocity along the push axis; it decays fast, so + # sample it while the block is still moving. + speed = 0.0 + for _ in range(6): + player.wait(2) + speed = max(speed, player('state')['player']['velocity'][0]) + after = pos_of(player) + results[name] = round(after[0] - before[0], 3) + # The block pushes the body out of its way, and the bounce launches it. + assert results[name] > 1.5, f'the slime block did not push and bounce {name}: {before} -> {after}' + assert speed > 0.05, f'the slime block did not bounce {name}: {speed}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + player.wait(10) + # A plain block only pushes: the body is not launched. + setup() + host('command', command=f'setblock {x+1} {y} {z} minecraft:stone') + host('command', command=f'tp @s {x+2.5} {y} {z+0.5}') + host.wait(15) + before = pos_of(host) + host('command', command=f'setblock {x-1} {y} {z} minecraft:redstone_block') + speed = 0.0 + for _ in range(6): + host.wait(2) + speed = max(speed, host('state')['player']['velocity'][0]) + after = pos_of(host) + results['stone'] = round(after[0] - before[0], 3) + assert results['stone'] < 1.5, f'a plain block bounced the player: {before} -> {after}' + host('command', command=f'setblock {x-1} {y} {z} minecraft:air') + host.wait(10) + return results + + def check_plates(host, guest, out): guest('command', command='gamemode survival') x, y, z = (int(v // 1) for v in pos_of(guest)) @@ -4769,13 +4960,14 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'cartography': check_cartography, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, - 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, + 'clicks': check_clicks, 'sleep': check_sleep, 'push': check_push, 'piston-push': check_piston_push, + 'piston-slime': check_piston_slime, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, 'blast': check_blast, 'light': check_light, 'plates': check_plates, 'swings': check_swings, 'cracks': check_cracks, 'time': check_time, 'growth': check_growth, 'doors': check_doors, 'flight': check_flight, 'fireball': check_fireball, 'deflect': check_deflect, - 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, + 'barter': check_barter, 'worn': check_worn, 'kills': check_kills, 'leave': check_leave, 'arrows': check_arrows, 'predict': check_predict, 'ladder': check_ladder, 'boats': check_boats, 'minecarts': check_minecarts, 'frames': check_frames, 'hands': check_hands, 'lightning': check_lightning, 'riding': check_riding, 'occupied_horse': check_occupied_horse, 'mounts': check_mounts, diff --git a/tools/test_piston_push_parity.py b/tools/test_piston_push_parity.py new file mode 100644 index 000000000..17f1a257d --- /dev/null +++ b/tools/test_piston_push_parity.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Compare moving-piston push geometry and predicates with pinned vanilla. + +`PistonMovingBlockEntity.moveCollidedEntities` decides how far an entity is +pushed; the movement it describes is `Entity.move(MoverType.PISTON, ...)`, whose +collision and per-tick limit the game owns. This harness covers the deciding +half: the movement area, the offset block box, `getMovement` on every face, the +per-box loop, `moveStuckEntities`' box and `matchesStickyCritera`, and +`fixEntityWithinPistonBase`. +""" +import argparse +import json +import os +from pathlib import Path +import platform +import random +import struct +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def corpus(): + def f32(v): return struct.pack('>f', float(v)).hex() + def f64(v): return struct.pack('>d', float(v)).hex() + def box(values): return [f64(v) for v in values] + step = [1.0 / 3.0, 0.25, 0.5, 0.75, 1.0] + unit = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] + offsets = [[0, 0, 0], [-17, -64, 30000000], [2147483647, -2147483648, -2147483648]] + faces = [0, 1, 2, 3, 4, 5] + # Progress pairs around the 0.25/0.5/1.0 thresholds the head and the + # extended-progress offset change at. + progress = [0.0, 0.25, 0.49999997, 0.5, 0.75, 0.99999994, 1.0] + entities = [ + [0.9, 0.0, 0.2, 1.5, 1.8, 0.8], + [1.4, 0.0, 0.2, 2.0, 1.8, 0.8], + [0.75, 0.0, 0.2, 1.35, 1.8, 0.8], + [3.0, 0.0, 0.2, 3.6, 1.8, 0.8], + [0.49, 0.0, 0.49, 0.51, 1.8, 0.51], + [0.0, 1.0, 0.0, 1.0, 2.8, 1.0], + ] + for index, position in enumerate(offsets): + for direction in faces: + for extending in (False, True): + for source in (False, True): + for current in progress: + advanced = min(current + 0.5, 1.0) + for entity in entities: + yield { + 'pos': position, + 'direction': direction, + 'extending': extending, + 'source': source, + 'progress': f32(current), + 'new_progress': f32(advanced), + 'block_box': box(unit), + 'movement_box': box(unit), + 'entity': box(entity), + 'boxes': [box(unit)], + 'sticky_top': f64(0.0), + 'reaction': 0, + 'on_ground': True, + 'supported': False, + 'entity_x': f64(entity[0]), + 'entity_z': f64(entity[2]), + } + # Split boxes, a retracting honey drag with every push reaction, and the + # predicate's supported/on-ground corners. + for index in range(4000): + rng = random.Random(0x50555348 + index) + current = rng.choice(progress) + advanced = min(current + 0.5, 1.0) + count = rng.randint(1, 4) + boxes = [] + for _ in range(count): + low = [rng.choice([0.0, 0.25, 0.5]), rng.choice([0.0, 0.5]), rng.choice([0.0, 0.5])] + high = [min(v + rng.choice([0.25, 0.5, 1.0]), 1.0) for v in low] + boxes.append(box(low + high)) + yield { + 'pos': rng.choice(offsets), + 'direction': rng.randrange(6), + 'extending': rng.random() < 0.5, + 'source': rng.random() < 0.5, + 'progress': f32(current), + 'new_progress': f32(advanced), + 'block_box': boxes[0], + 'movement_box': boxes[rng.randrange(len(boxes))], + 'entity': box([ + rng.choice([0.0, 0.49, 0.75, 0.9, 1.4]), + rng.choice([0.0, 0.5]), + rng.choice([0.0, 0.2, 0.49]), + rng.choice([0.51, 1.35, 1.5, 2.0]), + rng.choice([1.8, 2.8]), + rng.choice([0.51, 0.8, 1.0]), + ]), + 'boxes': boxes, + 'sticky_top': f64(rng.choice([0.0, 0.5, 0.9375])), + 'reaction': rng.randrange(5), + 'on_ground': rng.random() < 0.5, + 'supported': rng.random() < 0.5, + 'entity_x': f64(rng.choice([0.0, 0.5, 1.0, 2.0])), + 'entity_z': f64(rng.choice([0.0, 0.5, 1.0, 2.0])), + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--prepare', action='store_true') + args = parser.parse_args() + build = lab.LOCAL / 'rust-piston-push-parity' + build.mkdir(parents=True, exist_ok=True) + report_path = build / 'report.json' + report_path.unlink(missing_ok=True) + if args.prepare: + lab.prepare() + lock, jars, libraries = base.verify_artifacts() + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPistonPushOracle.java' + helpers = [oracle.with_name(name + '.java') + for name in ['VanillaCollisionOracle', 'VanillaBlockStateCodecOracle', 'VanillaFaceSupportOracle']] + sources = [oracle, *helpers, Path(__file__), lab.ROOT / 'tools/test_rust_parity.py', lab.ROOT / 'tools/lab.py', + lab.ROOT / 'Cargo.toml', lab.ROOT / 'Cargo.lock', + lab.ROOT / 'crates/horizon-core/Cargo.toml', lab.ROOT / 'crates/horizon-world/Cargo.toml', + *sorted((lab.ROOT / 'crates/horizon-core/src').rglob('*.rs')), + *sorted((lab.ROOT / 'crates/horizon-world/src').rglob('*.rs')), + lab.ROOT / 'crates/horizon-world/examples/probe/piston_push_fixture.rs'] + tested_sources = base.source_hashes(sources) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + + def run(command, name): + with (build / (name + '.log')).open('w', encoding='utf-8') as log: + base.run(list(map(str, command)), stdout=log, stderr=subprocess.STDOUT) + + dependency_path = os.pathsep.join(map(str, libraries)) + run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', + '-sourcepath', str(lab.ROOT / 'mods/horizon/src/test/java'), + '-cp', str(jars['server']) + os.pathsep + dependency_path, + '-d', classes, oracle, *helpers], 'compile-java') + + def java(side, mode, path): + run(['java', '-Xmx512M', '-cp', os.pathsep.join([str(classes), str(jars[side]), dependency_path]), + 'dev.horizonlab.parity.VanillaPistonPushOracle', mode, path], side + '-' + mode) + + fixtures = list(corpus()) + inputs = build / 'inputs.txt' + inputs.write_text(''.join(json.dumps(value, separators=(',', ':')) + '\n' for value in fixtures), encoding='utf-8') + fixture_paths = [inputs] + tested_fixtures = base.source_hashes(fixture_paths) + run(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'world_probe'], 'compile-rust') + metadata = json.loads(subprocess.check_output( + ['cargo', 'metadata', '--no-deps', '--format-version', '1'], cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release/examples' / ('world_probe.exe' if os.name == 'nt' else 'world_probe') + run([binary, 'piston_push_fixture', build], 'rust') + references = [] + for side, jar in jars.items(): + java(side, side, build) + reference = build / f'{side}.txt' + matched = base.compare(reference, build / 'rust.txt') + references.append({'side': side, 'jar_sha256': lab.digest(jar, 'sha256'), + 'output_sha256': lab.digest(reference, 'sha256'), 'matched_output_lines': matched}) + print(f'{side}: {matched:,} piston-push output lines match Rust', flush=True) + base.ensure_sources_unchanged(sources, tested_sources) + base.ensure_sources_unchanged(fixture_paths, tested_fixtures) + report = { + 'schema': 1, + 'minecraft': lock['minecraft']['version'], + 'manifest_sha1': lock['minecraft']['manifest_sha1'], + 'platform': platform.platform(), + 'java': subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + 'rustc': subprocess.check_output(['rustc', '--version'], text=True).strip(), + 'fixtures': len(fixtures), + 'sources_sha256': tested_sources, + 'fixtures_sha256': tested_fixtures, + 'rust_output_sha256': lab.digest(build / 'rust.txt', 'sha256'), + 'references': references, + 'scope': 'Actual PistonMovingBlockEntity push geometry and predicates: getExtendedProgress, ' + 'moveByPositionAndProgress, PistonMath.getMovementArea, getMovement on every face, the ' + 'moveCollidedEntities loop over split shapes with its delta cap and PUSH_OFFSET, the ' + 'getEntities search box, and moveStuckEntities\' box with matchesStickyCritera for every push ' + 'reaction. fixEntityWithinPistonBase is covered by unit tests only: it calls ' + 'Entity.move(MoverType.PISTON, ...) and so needs a live level. Entity selection order, that ' + 'collision pass, the per-tick 0.51 limit, block behaviour of the moved state and full gameplay ' + 'remain elsewhere.', + } + lab.write_json(report_path, report) + print(f'Scoped piston-push parity passed: {report_path}') + + +if __name__ == '__main__': + main() \ No newline at end of file