Maces smash: fall damage bonus, Density, Breach, Wind Burst, knockback

A mace hit after falling more than 1.5 blocks is now a smash attack
(MaceItem): the fall-based damage bonus plus Density, mace_smash damage,
the stopped fall with its damage waived, the ground/air smash sounds, the
dust pillars (level event 2013) and the knockback of the creatures around
the target, then the fall reset and landing particles. Breach thins the
target's armor (CombatRules.getDamageAfterAbsorb), Wind Burst bursts at
the player's feet (ExplodeEffect, trigger), and weapons wear by their
weapon component and award the used statistic.

Vanilla details matched on the way: the hurt knockback is 0.4F and reads
the live knockback-resistance attribute, explosion exposure uses the
exact COLLIDER clip, a burst posts the explode game event and ends the
impulse grace unless it is a wind charge's, visible armor stands feel
bursts that affect block-like entities, attack sounds play at the player.

tools/test_mace_parity.py compares the hit with VanillaDispenserOracle's
real MaceItem / hurtServer / post-attack effects: 3000/3000.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-14 21:00:13 +02:00
parent e15c879fe7
commit 56aae0e902
19 changed files with 1174 additions and 96 deletions
+34 -1
View File
@@ -628,7 +628,8 @@ impl Enchantments {
} else {
spec
};
spec.is_null() && entity.is_some() || self.entity_matches(spec, entity)
(spec.is_null() && entity.is_some() || self.entity_matches(spec, entity))
&& movement_matches(&c["predicate"], role_state(c, ctx))
}
"minecraft:random_chance" => {
let chance = match &c["chance"] {
@@ -661,6 +662,38 @@ pub struct EffectContext<'a> {
pub this: Option<&'a str>,
pub attacker: Option<&'a str>,
pub direct_attacker: Option<&'a str>,
/// The direct attacker's fall distance and whether it flies (elytra or
/// abilities), for `movement` and `flags` predicates.
pub direct_motion: Option<(f64, bool)>,
}
/// The fall distance and flying flag known for an `entity_properties` role.
fn role_state(c: &Value, ctx: &EffectContext<'_>) -> Option<(f64, bool)> {
match c["entity"].as_str().unwrap_or("this") {
"direct_attacker" => ctx.direct_motion,
_ => None,
}
}
/// `EntityPredicate`'s `minecraft:movement` fall distance and
/// `minecraft:flags` is_flying (the parts enchantment requirements use); an
/// entity whose state is unknown matches neither.
fn movement_matches(predicate: &Value, state: Option<(f64, bool)>) -> bool {
let fall = &predicate["minecraft:movement"]["fall_distance"];
let flying = predicate["minecraft:flags"]["is_flying"].as_bool();
if fall.is_null() && flying.is_none() {
return true;
}
let Some((distance, is_flying)) = state else {
return false;
};
// MinMaxBounds.Doubles: a number is an exact bound.
let bound = |key: &str| {
fall.as_f64()
.or_else(|| fall.get(key).and_then(Value::as_f64))
};
// MinMaxBounds.Doubles.matches
bound("min").is_none_or(|min| min <= distance)
&& bound("max").is_none_or(|max| distance <= max)
&& flying.is_none_or(|f| f == is_flying)
}
fn next_int<R: RandomSource>(random: &mut R, bound: i32) -> i32 {
random.next_int_bound(bound.max(1)).unwrap_or(0)
+40 -38
View File
@@ -58,6 +58,7 @@ mod level_particles;
mod lightning;
mod llamas;
mod loom;
mod mace;
mod machines;
mod maps;
mod minecarts;
@@ -1640,6 +1641,11 @@ impl Game<'_> {
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
self.spawner_burst([pos.x, pos.y, pos.z])
}
LevelEvent::LevelEvent {
id: 2013,
pos,
data,
} => self.smash_dust(pos, data),
LevelEvent::LevelEvent {
id: id @ 3002..=3005,
pos,
@@ -2916,6 +2922,11 @@ impl Game<'_> {
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
MotionEvent::SmashLanding {
state,
position,
fall_distance,
} => self.smash_landing_particles(state, position, fall_distance),
_ => {}
}
}
@@ -5182,19 +5193,20 @@ impl Game<'_> {
let delay = 20.0 / speed;
let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
let mut amount = damage * (0.2 + scale * scale * 0.8);
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(&target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting);
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
let target_kind = self.mobs[index].kind.id.clone();
amount += self.enchant_damage_bonus(&format!(
"minecraft:{}",
target_kind.trim_start_matches("minecraft:")
)) * scale;
amount += self.enchant_damage_bonus(&target_kind) * scale;
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
@@ -5206,21 +5218,23 @@ impl Game<'_> {
self.swing_arm();
// LivingEntity.setLastHurtMob (tamed wolves join in).
self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
let mob = &mut self.mobs[index];
let center = [
mob.position.x,
mob.position.y + mob.kind.height / 2.0,
mob.position.z,
];
let dealt = (amount.min(mob.health.max(0.0)) * 10.0).round() as i32;
if mob.hurt(amount, from, &mut self.world.random) {
self.stats.custom("damage_dealt", dealt);
let old_health = self.mobs[index].health;
let source = match from {
Some(f) => self.attack_source(f),
None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic),
};
if self.hurt_by_player(index, amount, source) {
let mob = &self.mobs[index];
// Player.damageStatsAndHearts: the damage the hit actually did.
let actual = old_health - mob.health;
// Player.attack: crit emitter and damage indicator hearts.
let (feet, width, height) = (
[mob.position.x, mob.position.y, mob.position.z],
mob.kind.width,
mob.kind.height,
);
self.stats
.custom("damage_dealt", (actual * 10.0).round() as i32);
if crit {
self.particles.tracking_emitter(
horizon_client::particles::ParticleOptions::simple(
@@ -5231,7 +5245,7 @@ impl Game<'_> {
height,
);
}
if amount > 2.0 {
if actual > 2.0 {
let indicator = horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::DamageIndicator,
);
@@ -5240,10 +5254,10 @@ impl Game<'_> {
[feet[0], feet[1] + height * 0.5, feet[2]],
[0.1, 0.0, 0.1],
0.2,
(amount * 0.5) as u32,
(actual * 0.5) as u32,
);
}
self.last_hurt_by_player.insert(mob.id);
self.last_hurt_by_player.insert(self.mobs[index].id);
let sound = if crit {
"minecraft:entity.player.attack.crit"
} else if scale > 0.9 {
@@ -5251,33 +5265,21 @@ impl Game<'_> {
} else {
"minecraft:entity.player.attack.weak"
};
self.audio.play(sound, Some(center), 1.0, 1.0);
// Player.playServerSideSound: at the player.
self.audio.play(sound, from, 1.0, 1.0);
// The hurt or death sound the mob raised (getHurtSound / getDeathSound,
// its voice pitch from its own random).
let queued = std::mem::take(&mut self.mobs[index].outbox);
for event in queued {
if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(center), volume, pitch);
}
}
self.post_attack(index);
if let Some(stack) = self.inventory[self.selected].clone()
&& let Some(max) = self
.res
.items
.get(&stack.item)
.filter(|i| i.max_damage > 0)
.map(|i| i.max_damage)
{
let loss = self.durability_loss(&stack, 1);
if let Some(stack) = self.inventory[self.selected].as_mut() {
stack.damage += loss;
if stack.damage >= max {
self.inventory[self.selected] = None;
}
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
}
}
self.weapon_hit(index);
} else {
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
true
}
@@ -89,6 +89,7 @@ impl Game<'_> {
fn damage_kind(ty: &str) -> DamageKind {
match ty.trim_start_matches("minecraft:") {
"player_attack" => DamageKind::PlayerAttack,
"mace_smash" => DamageKind::MaceSmash,
"mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
"arrow" => DamageKind::Arrow,
"thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
@@ -2572,6 +2572,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
use horizon_client::mobs::DamageKind as K;
match kind {
K::PlayerAttack => "minecraft:player_attack",
K::MaceSmash => "minecraft:mace_smash",
K::MobAttack => "minecraft:mob_attack",
K::Arrow => "minecraft:arrow",
K::Thrown => "minecraft:thrown",
@@ -59,8 +59,18 @@ pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
}
}
/// Java's `String.format("%.6f")`: the exact value rounded half up (away
/// from zero) where Rust rounds a tie to even.
fn num(v: f64) -> String {
format!("{v:.6}")
let exact = format!("{:.40}", v.abs());
let tie = exact
.split_once('.')
.is_some_and(|(_, f)| f[6..].starts_with('5') && f[7..].bytes().all(|b| b == b'0'));
if tie {
format!("{:.6}", v + 0.5e-6_f64.copysign(v))
} else {
format!("{v:.6}")
}
}
fn floor_pos(p: [f64; 3]) -> String {
format!(
@@ -299,6 +309,8 @@ impl Game<'_> {
),
None => "respawn none".to_owned(),
});
} else if let Some(op) = case.get("attack") {
used = self.fixture_attack(op, &targets)?;
} else if case.get("hopper").is_some() {
// HopperBlockEntity.pushItemsTick, once.
self.hopper_try_move_items((origin.x, origin.y, origin.z));
@@ -559,6 +571,119 @@ impl Game<'_> {
Ok(out)
}
/// The player's hit on the first target with the case's item, from the
/// attack strength's scaled `base` damage on: the item's damage bonus and
/// source, the hurt with the weapon's armor effects, then `weapon_hit`
/// (the mace's smash, post-attack enchantments, the wear), as
/// `VanillaDispenserOracle.attack` prints them.
fn fixture_attack(&mut self, op: &Value, targets: &[Target]) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.mode = if op["creative"].as_bool().unwrap_or(false) {
GameMode::Creative
} else {
GameMode::Survival
};
self.creative = self.mode == GameMode::Creative;
let v3 = |v: &Value| {
horizon_core::geometry::Vec3::new(
v[0].as_f64().unwrap_or(0.0),
v[1].as_f64().unwrap_or(0.0),
v[2].as_f64().unwrap_or(0.0),
)
};
let mut player = PlayerMotion::new(self.motion, v3(&op["player"]))?;
player.velocity = v3(&op["motion"]);
player.fall_distance = op["fall"].as_f64().unwrap_or(0.0);
player.fall_flying = op["fall_flying"].as_bool().unwrap_or(false);
player.flying = op["flying"].as_bool().unwrap_or(false);
player.may_fly = self.creative;
if !op["impact"].is_null() {
player.impulse.impact_position = Some(v3(&op["impact"]));
}
let feet = [player.position.x, player.position.y, player.position.z];
self.player = Some(player);
self.inventory[self.selected] = stack.clone();
let used_before = stack
.as_ref()
.map_or(0, |s| self.stats.get("used", &s.item));
let Some(&Target::Mob(id)) = targets.first() else {
return Err("an attack case hits a mob".into());
};
let index = self
.mobs
.iter()
.position(|m| m.id == id)
.ok_or("the target is gone")?;
let kind = self.mobs[index].kind.id.clone();
let base = op["base"].as_f64().unwrap_or(0.0) as f32;
let bonus = self.smash_damage_bonus(&kind);
let source = self.attack_source(feet);
let hurt = self.hurt_by_player(index, base + bonus, source);
// The hurt sound the mob raised, where it stands.
for event in std::mem::take(&mut self.mobs[index].outbox) {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
}
}
if hurt {
self.weapon_hit(index);
}
self.process_level_events()?;
let mut out = Vec::new();
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
if used != 0 {
out.push(format!("stat {} minecraft:used {used}", s.item));
}
}
let source = match source.kind {
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
_ => "minecraft:player_attack",
};
out.push(format!(
"attack bonus={} source={source} hurt={hurt}",
num(f64::from(bonus))
));
for (i, t) in targets.iter().enumerate() {
let (health, v) = match *t {
Target::Mob(id) => match self.mobs.iter().find(|m| m.id == id) {
Some(m) => (num(f64::from(m.health)), m.velocity),
None => continue,
},
Target::Stand(id) => match self.armor_stands.iter().find(|s| s.id == id) {
Some(s) => ("-".to_owned(), s.velocity),
None => continue,
},
};
out.push(format!(
"V {i} {health} {} {} {}",
num(v.x),
num(v.y),
num(v.z)
));
}
if let Some(p) = self.player.take() {
let impact = p.impulse.impact_position.map_or("-".to_owned(), |i| {
format!("{},{},{}", num(i.x), num(i.y), num(i.z))
});
out.push(format!(
"P {} {} {} fall={} impact={impact} grace={} extra={}",
num(p.velocity.x),
num(p.velocity.y),
num(p.velocity.z),
num(p.fall_distance),
p.impulse.reset_grace_time,
p.spawn_extra_particles_on_fall
));
}
out.push(format!(
"held {}",
canon_stack(self.inventory[self.selected].as_ref())
));
Ok(out)
}
/// A stack in a block entity's slot: a container's, a jukebox's record, a
/// lectern's book, or the items of a block entity Horizon keeps as saved.
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
@@ -678,8 +803,10 @@ impl Game<'_> {
self.next_entity += 1;
let id = self.next_entity;
if kind == "minecraft:armor_stand" {
self.armor_stands
.push(horizon_client::entities::ArmorStand::new(id, at, yaw));
let mut stand = horizon_client::entities::ArmorStand::new(id, at, yaw);
stand.marker = e["marker"].as_bool().unwrap_or(false);
stand.on_ground = e["ground"].as_bool().unwrap_or(false);
self.armor_stands.push(stand);
return Ok(Target::Stand(id));
}
let t = self
@@ -728,6 +855,14 @@ impl Game<'_> {
if flag("loot") {
mob.extra.pick_up_loot = true;
}
mob.on_ground = flag("ground");
if let Some(health) = e["health"].as_f64() {
mob.attrs.max_health = health as f32;
mob.health = health as f32;
}
if let Some(resistance) = e["knockback_resistance"].as_f64() {
mob.attrs.knockback_resistance = resistance;
}
if flag("brown") && s == Species::Mooshroom {
mob.extra.variant = 1;
}
@@ -165,6 +165,69 @@ impl Game<'_> {
self.potions.burning.retain(|(m, _)| *m != id);
self.potions.burning.push((id, (ignite * 20.0) as i32));
}
self.post_attack_bursts(&held, &kind);
}
/// `minecraft:post_attack` explode effects on the attacker (wind burst):
/// a burst at the player's feet that only knocks back and triggers
/// blocks (`ExplodeEffect` with `block_interaction: trigger`).
fn post_attack_bursts(&mut self, held: &ItemStack, victim: &str) {
let Some(p) = self.player.as_ref() else {
return;
};
// EntityFlagsPredicate.isFlying: gliding or flying.
let motion = (p.fall_distance, p.fall_flying || p.flying);
let feet = [p.position.x, p.position.y, p.position.z];
let ctx = EffectContext {
this: Some(victim),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
items: Some(&self.res.items),
direct_motion: Some(motion),
..Default::default()
};
let mut bursts = Vec::new();
for (id, level) in held.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:post_attack"]
.as_array()
.into_iter()
.flatten()
{
let e = &effect["effect"];
if effect["enchanted"] != "attacker"
|| effect["affected"] != "attacker"
|| e["type"] != "minecraft:explode"
|| e["block_interaction"] != "trigger"
{
continue;
}
let ok = effect.get("requirements").is_none_or(|r| {
self.res.stations.enchantments.condition(
r,
*level,
&ctx,
&mut self.world.random,
)
});
if !ok {
continue;
}
let radius = horizon_client::enchant::level_value(&e["radius"], *level).max(0.0);
// ExplosionDamageCalculator.getKnockbackMultiplier: 1 unless given.
let knockback = if e["knockback_multiplier"].is_null() {
1.0
} else {
horizon_client::enchant::level_value(&e["knockback_multiplier"], *level)
};
bursts.push((radius, knockback));
}
}
for (radius, knockback) in bursts {
let _ = self.wind_burst(feet, radius, knockback, false, false);
}
}
/// Burning mobs (fire aspect): one damage every 20 ticks, flame particles.
pub(super) fn tick_burning(&mut self) {
+83 -34
View File
@@ -3,14 +3,64 @@
//! draws), entity damage with exposure and knockback, block interaction with
//! merged drops and TNT chain priming, and optional fire.
use super::Game;
use horizon_client::{Result, blocks::Fluid, items::ItemStack};
use horizon_client::{Result, blocks::Fluid, collisions::SceneCollisions, items::ItemStack};
use horizon_core::{
geometry::Vec3,
geometry::{Vec3, VoxelShape},
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
use std::cmp::Ordering;
use horizon_world::{
collision_context::{CollisionContext, CollisionEntity, CollisionItem},
entity_obstruction::EntityIdentity,
java_hash_map::{JavaHashMap, JavaKey},
registry::BlockStateId,
world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world},
};
use std::{cmp::Ordering, io};
/// `Level.clip` with `ClipContext.Block.COLLIDER`, no fluids and the
/// collision context of the entity whose exposure is measured.
struct ColliderRays<'a, 'r> {
scene: SceneCollisions<'a, 'r>,
context: CollisionContext<'static>,
}
impl RayWorld for ColliderRays<'_, '_> {
type Error = io::Error;
type Block = BlockStateId;
type Fluid = ();
fn block_state(&mut self, p: BlockPos) -> io::Result<BlockStateId> {
Ok(self.scene.world.block(p.x, p.y, p.z))
}
fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> {
Ok(())
}
fn block_shape(
&mut self,
state: BlockStateId,
p: BlockPos,
_: RayBlockMode,
) -> io::Result<VoxelShape> {
let binding = self.scene.binding;
binding
.collision_shape_with_context(&mut self.scene, state, p, &self.context)
.map_err(|e| io::Error::other(format!("{e:?}")))
}
fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result<VoxelShape> {
Ok(VoxelShape::empty())
}
fn fluid_is_source(&mut self, _: ()) -> io::Result<bool> {
Ok(false)
}
fn fluid_is_empty(&mut self, _: ()) -> io::Result<bool> {
Ok(true)
}
fn fluid_is_water(&mut self, _: ()) -> io::Result<bool> {
Ok(false)
}
fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result<VoxelShape> {
Ok(VoxelShape::empty())
}
}
/// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -48,35 +98,6 @@ pub(super) fn client_float() -> f32 {
}
impl Game<'_> {
/// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
/// collision cubes as obstacles.
fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let steps = (length / 0.1).ceil().max(1.0) as i32;
let mut last = [i32::MIN; 3];
for i in 0..=steps {
let t = f64::from(i) / f64::from(steps);
let b = [
(from[0] + d[0] * t).floor() as i32,
(from[1] + d[1] * t).floor() as i32,
(from[2] + d[2] * t).floor() as i32,
];
if b == last {
continue;
}
last = b;
if self
.res
.facts
.get(self.world.block(b[0], b[1], b[2]))
.full_collision
{
return false;
}
}
true
}
/// `ServerExplosion.getSeenPercent` for an entity box.
pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
@@ -87,6 +108,23 @@ impl Game<'_> {
if xs < 0.0 || ys < 0.0 || zs < 0.0 {
return 0.0;
}
// ClipContext(..., entity): the entity standing at the box's bottom.
let mut rays = ColliderRays {
scene: SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
},
context: CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
y: min[1],
descending: false,
main_hand: Some(CollisionItem::EMPTY),
},
false,
),
};
let (mut hits, mut count) = (0, 0);
let mut xx = 0.0;
while xx <= 1.0 {
@@ -97,7 +135,18 @@ impl Game<'_> {
let x = min[0] + (max[0] - min[0]) * xx;
let y = min[1] + (max[1] - min[1]) * yy;
let z = min[2] + (max[2] - min[2]) * zz;
if self.clear_line([x + x_offset, y, z + z_offset], center) {
let from = Vec3::new(x + x_offset, y, z + z_offset);
let to = Vec3::new(center[0], center[1], center[2]);
let missed = clip_world(
&mut rays,
from,
to,
RayBlockMode::Collider,
RayFluidMode::None,
4096,
)
.is_ok_and(|r| r.miss);
if missed {
hits += 1;
}
count += 1;
+330
View File
@@ -0,0 +1,330 @@
//! Maces (`MaceItem`): a hit after falling more than one and a half blocks is
//! a smash attack. It adds damage for the height fallen (more with Density),
//! stops the fall, cancels its damage and knocks the creatures around the
//! target away. The rest of a weapon hit (`Player.itemAttackInteraction`)
//! is here too: `hurtEnemy`, the post-attack enchantments and `postHurtEnemy`.
use super::Game;
use horizon_client::{
enchant::EffectContext,
mobs::{Damage, Mob, Species},
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
use horizon_world::registry::BlockStateId;
/// `MaceItem.SMASH_ATTACK_FALL_THRESHOLD`.
const FALL_THRESHOLD: f64 = 1.5;
/// `MaceItem.SMASH_ATTACK_HEAVY_THRESHOLD`.
const HEAVY_THRESHOLD: f64 = 5.0;
/// `MaceItem.SMASH_ATTACK_KNOCKBACK_RADIUS`.
const KNOCKBACK_RADIUS: f64 = 3.5;
/// `MaceItem.SMASH_ATTACK_KNOCKBACK_POWER`.
const KNOCKBACK_POWER: f32 = 0.7;
/// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob
/// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and
/// `Allay.considersEntityAsAlly` (an allay that likes it).
fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
let tamable = matches!(
m.species(),
Species::Wolf
| Species::Cat
| Species::Parrot
| Species::Nautilus
| Species::ZombieNautilus
);
tamable && m.extra.tame && m.extra.owner.is_some() && m.extra.owner == player
|| m.species() == Species::Allay && m.extra.tame
}
impl Game<'_> {
fn holds_mace(&self) -> bool {
self.inventory[self.selected]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:mace")
}
/// `MaceItem.canSmashAttack` for the player: falling and not gliding.
fn can_smash_attack(&self) -> bool {
self.player
.as_ref()
.is_some_and(|p| p.fall_distance > FALL_THRESHOLD && !p.fall_flying)
}
/// A held mace about to smash (`MaceItem.getItemDamageSource`: the attack
/// is `mace_smash` damage).
pub(super) fn smash_attack(&self) -> bool {
self.holds_mace() && self.can_smash_attack()
}
/// The damage source of the player's hit from `from` with the held item.
pub(super) fn attack_source(&self, from: [f64; 3]) -> Damage {
if self.smash_attack() {
Damage::mace(from)
} else {
Damage::player(from)
}
}
/// `MaceItem.getAttackDamageBonus` against `victim`: 4 per block for the
/// first three blocks fallen, 2 for the next five, 1 after that, plus
/// `smash_damage_per_fallen_block` (Density) for every block.
pub(super) fn smash_damage_bonus(&mut self, victim: &str) -> f32 {
if !self.smash_attack() {
return 0.0;
}
let fall = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
let damage = if fall <= 3.0 {
4.0 * fall
} else if fall <= 8.0 {
12.0 + 2.0 * (fall - 3.0)
} else {
22.0 + fall - 8.0
};
let held = self.inventory[self.selected].clone();
let ctx = EffectContext {
this: Some(victim),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some("minecraft:mace_smash"),
items: Some(&self.res.items),
..Default::default()
};
// EnchantmentHelper.modifyFallBasedDamage(..., 0)
let per_block = self.res.stations.enchantments.modify_value(
held.as_ref(),
"minecraft:smash_damage_per_fallen_block",
&ctx,
&mut self.world.random,
0.0,
);
(damage + f64::from(per_block) * fall) as f32
}
/// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
/// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
let held = self.inventory[self.selected].clone();
let kind = self.mobs[index].kind.id.clone();
let ctx = EffectContext {
this: Some(&kind),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some(match source.kind {
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
_ => "minecraft:player_attack",
}),
items: Some(&self.res.items),
..Default::default()
};
let enchantments = &self.res.stations.enchantments;
let random = &mut self.world.random;
// CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness.
let mut breach = |fraction: f32| {
enchantments.modify_value(
held.as_ref(),
"minecraft:armor_effectiveness",
&ctx,
random,
fraction,
)
};
let old_health = self.mobs[index].health;
let hurt = self.mobs[index].damage_with(amount, source, Some(&mut breach));
if hurt && self.mobs[index].health != old_health {
self.mob_damage_event(self.mobs[index].id);
}
hurt
}
/// `Player.itemAttackInteraction` after the player's hit landed on the mob
/// at `index`: the item's `hurtEnemy` (the "used" statistic of a weapon),
/// the post-attack enchantments, then `postHurtEnemy` with the weapon's
/// wear.
pub(super) fn weapon_hit(&mut self, index: usize) {
let Some(stack) = self.inventory[self.selected].clone() else {
return;
};
let weapon = self
.res
.items
.get(&stack.item)
.and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
let smash = self.smash_attack();
if smash {
self.mace_hurt_enemy(index);
}
if weapon.is_some() {
self.stats.add("used", &stack.item, 1);
}
self.post_attack(index);
// MaceItem.postHurtEnemy
if smash && let Some(p) = self.player.as_mut() {
p.fall_distance = 0.0;
}
// ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
if let Some((per_attack, max)) = weapon
&& max > 0
&& !self.creative
{
let loss = self.durability_loss(&stack, per_attack);
if let Some(held) = self.inventory[self.selected].as_mut() {
held.damage += loss;
if held.damage >= max {
self.inventory[self.selected] = None;
}
}
}
}
/// `MaceItem.hurtEnemy` for a smash: the fall stops and its damage is
/// waived from where the hit landed, the ground or air smash sounds, and
/// the knockback around the target.
fn mace_hurt_enemy(&mut self, index: usize) {
let target_on_ground = self.mobs[index].on_ground;
let Some(p) = self.player.as_mut() else {
return;
};
p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z);
// calculateImpactPosition: an earlier impact below the player stays.
let impact = match p.impulse.impact_position {
Some(at) if at.y <= p.position.y => at,
_ => p.position,
};
p.impulse.set_ignore_fall_damage(true, Some(impact));
let fall = p.fall_distance;
let feet = [p.position.x, p.position.y, p.position.z];
let sound = if target_on_ground {
p.spawn_extra_particles_on_fall = true;
if fall > HEAVY_THRESHOLD {
"minecraft:item.mace.smash_ground_heavy"
} else {
"minecraft:item.mace.smash_ground"
}
} else {
"minecraft:item.mace.smash_air"
};
self.audio.play(sound, Some(feet), 1.0, 1.0);
self.smash_knockback(index, fall);
}
/// `MaceItem.knockback`: the dust pillar (level event 2013) under the
/// target, then every living entity within 3.5 blocks of it but the
/// player and the target pushed away and up, harder after a fall of more
/// than five blocks. Spectators, the player's allies (`isAlliedTo`: its
/// pets and the allays that like it), marker armor stands and creative
/// flyers are spared; the predicate's own tamed-animal test asks whether
/// the target owns the animal, which a mob never does.
fn smash_knockback(&mut self, index: usize, fall: f64) {
let target = &self.mobs[index];
let (id, center) = (target.id, target.position);
// Entity.getOnPos without a supporting block.
let on_pos = [
center.x.floor() as i32,
(center.y - f64::from(1.0e-5f32)).floor() as i32,
center.z.floor() as i32,
];
self.level_event_at(2013, on_pos, 750);
let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 };
// getKnockbackPower and the push of one entity at `at`.
let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| {
let d = [at.x - center.x, at.y - center.y, at.z - center.z];
let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
return;
}
let length = distance_sqr.sqrt();
let power = (KNOCKBACK_RADIUS - length)
* f64::from(KNOCKBACK_POWER)
* heavy
* (1.0 - resistance);
if power <= 0.0 {
return;
}
// Vec3.normalize: a vector shorter than 1e-5 has no direction.
let (x, z) = if length < f64::from(1.0e-5f32) {
(0.0, 0.0)
} else {
(d[0] / length * power, d[2] / length * power)
};
*velocity = Vec3::new(
velocity.x + x,
velocity.y + f64::from(KNOCKBACK_POWER),
velocity.z + z,
);
};
let player = self.level.player_uuid.or(Some([0, 0, 0, 1]));
for m in self
.mobs
.iter_mut()
.filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player))
{
push(m.position, &mut m.velocity, m.attrs.knockback_resistance);
}
for s in self.armor_stands.iter_mut().filter(|s| !s.marker) {
push(s.position, &mut s.velocity, 0.0);
}
}
/// `ServerPlayer.checkFallDamage` after a smash on a grounded target:
/// the landing block's particles, 50 for every block fallen (200 at most).
pub(super) fn smash_landing_particles(
&mut self,
state: BlockStateId,
pos: BlockPos,
fall_distance: f64,
) {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let count = (50.0 * fall_distance).clamp(0.0, 200.0) as u32;
let spread = f64::from(0.3f32);
self.particles.send_particles(
&ParticleOptions::block(ParticleType::Block, sprite, tint),
[
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
],
[spread; 3],
f64::from(0.15f32),
count,
);
}
/// Level event 2013 (`ParticleUtils.spawnSmashAttackParticles`): dust
/// pillars of the block at `pos`, a cluster over it and a ring 3.5 out.
pub(super) fn smash_dust(&mut self, pos: BlockPos, count: i32) {
let state = self.world.block(pos.x, pos.y, pos.z);
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let options = ParticleOptions::block(ParticleType::DustPillar, sprite, tint);
let center = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
];
let near = f64::from(0.2f32);
let mut i = 0;
while (i as f32) < count as f32 / 3.0 {
let r = self.particles.random();
let x = center[0] + r.next_gaussian() / 2.0;
let z = center[2] + r.next_gaussian() / 2.0;
let v = [
r.next_gaussian() * near,
r.next_gaussian() * near,
r.next_gaussian() * near,
];
self.particles.add(&options, [x, center[1], z], v);
i += 1;
}
let far = f64::from(0.05f32);
let mut i = 0;
while (i as f32) < count as f32 / 1.5 {
let r = self.particles.random();
let angle = f64::from(i);
let x = center[0] + KNOCKBACK_RADIUS * angle.cos() + r.next_gaussian() / 2.0;
let z = center[2] + KNOCKBACK_RADIUS * angle.sin() + r.next_gaussian() / 2.0;
let v = [
r.next_gaussian() * far,
r.next_gaussian() * far,
r.next_gaussian() * far,
];
self.particles.add(&options, [x, center[1], z], v);
i += 1;
}
}
}
+13
View File
@@ -507,6 +507,19 @@ impl Game<'_> {
let ctx = self.who_context(who, state);
self.post_game_event(event, center((pos[0], pos[1], pos[2])), ctx);
}
/// `LivingEntity.actuallyHurt`'s damage vibration, heard as the hit lands;
/// the end-of-tick scan then knows this damage.
pub(super) fn mob_damage_event(&mut self, id: u32) {
if let Some(t) = self
.mobs
.iter()
.find(|m| m.id == id)
.and_then(|m| m.last_damage.map(|(_, t)| t))
{
self.sculk.damaged.insert(id, t);
}
self.post_entity_event("minecraft:entity_damage", Who::Mob(id));
}
/// A game event of an entity at its position.
pub(super) fn post_entity_event(&mut self, event: &'static str, who: Who) {
let at = match who {
+48 -16
View File
@@ -101,13 +101,7 @@ impl Game<'_> {
],
Hit::None => return Ok(()),
};
self.wind_burst(
center,
radius,
knockback,
breeze,
p.owner == Some(Who::Player),
)
self.wind_burst(center, radius, knockback, breeze, !breeze)
}
/// `AbstractWindCharge.onHitEntity`: one point of damage.
fn wind_charge_damage(&mut self, p: &Projectile, who: Who) {
@@ -208,7 +202,8 @@ impl Game<'_> {
center: [f64; 3],
radius: f32,
multiplier: f32,
player_charge: bool,
wind_charge: bool,
blocklike: bool,
) {
let diameter = f64::from(radius * 2.0);
let distance = |p: [f64; 3]| {
@@ -257,11 +252,10 @@ impl Game<'_> {
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
// ServerPlayer.onExplosionHit: a player's own charge cancels the fall.
if player_charge {
let at = p.position;
p.impulse.set_ignore_fall_damage(true, Some(at));
}
// ServerPlayer.onExplosionHit: a wind charge's burst cancels the
// fall; any other burst ends the grace of the last impulse.
let at = p.position;
p.impulse.set_ignore_fall_damage(wind_charge, Some(at));
}
}
}
@@ -288,6 +282,39 @@ impl Game<'_> {
);
}
self.mobs = mobs;
// ArmorStand.ignoreExplosion: a visible stand feels only a burst that
// affects block-like entities (never a wind charge's).
if blocklike {
let mut stands = std::mem::take(&mut self.armor_stands);
for s in stands.iter_mut().filter(|s| !s.invisible) {
let feet = [s.position.x, s.position.y, s.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
continue;
}
// EntityType.ARMOR_STAND's size, halved when small; a marker has none.
let (w, h, eye) = if s.marker {
(0.0, 0.0, 0.0)
} else if s.small {
(0.125, f64::from(0.9875f32), f64::from(0.9875f32))
} else {
(0.25, f64::from(1.975f32), f64::from(1.7775f32))
};
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let power = (1.0 - dist) * f64::from(exposure) * multiplier;
let dir = direction([feet[0], feet[1] + eye, feet[2]]);
s.velocity = Vec3::new(
s.velocity.x + dir[0] * power,
s.velocity.y + dir[1] * power,
s.velocity.z + dir[2] * power,
);
}
self.armor_stands = stands;
}
// Arrows and other projectiles (the charges themselves ignore it).
let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| {
let feet = [position.x, position.y, position.z];
@@ -331,16 +358,21 @@ impl Game<'_> {
self.tnts = tnts;
}
/// The burst: knockback, the blocks that react, the gust and the sound.
fn wind_burst(
pub(super) fn wind_burst(
&mut self,
center: [f64; 3],
radius: f32,
multiplier: f32,
breeze: bool,
player_charge: bool,
wind_charge: bool,
) -> Result<()> {
// ServerExplosion.explode: the blast is heard first.
let ctx = horizon_client::sculk::Context::default();
self.post_game_event("minecraft:explode", center, ctx);
let mut targets = self.wind_positions(center, radius);
self.wind_knockback(center, radius, multiplier, player_charge);
// ServerExplosion.shouldAffectBlocklikeEntities
let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing");
self.wind_knockback(center, radius, multiplier, wind_charge, blocklike);
// Explosion.canTriggerBlocks: a breeze's charge needs mob griefing.
if !breeze || self.ui.rules.bool("mob_griefing") {
// Util.shuffle(list, level.random)
+7
View File
@@ -70,6 +70,8 @@ pub struct ItemInfo {
pub blocks_attacks: Option<BlocksAttacks>,
/// `weapon.disable_blocking_for_seconds` (axes).
pub disable_blocking_seconds: f32,
/// `weapon.item_damage_per_attack`, when the item is a weapon.
pub weapon_damage: Option<u32>,
/// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2).
pub use_speed: f32,
/// `glider` (elytra).
@@ -439,6 +441,11 @@ impl Items {
disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"]
.as_f64()
.unwrap_or(0.0) as f32,
weapon_damage: c["minecraft:weapon"].is_object().then(|| {
c["minecraft:weapon"]["item_damage_per_attack"]
.as_u64()
.unwrap_or(1) as u32
}),
equip_asset: c["minecraft:equippable"]["asset_id"]
.as_str()
.map(str::to_owned),
+27 -3
View File
@@ -492,6 +492,8 @@ pub enum Who {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DamageKind {
PlayerAttack,
/// `mace_smash`: a mace hit after a fall (the player attack tags too).
MaceSmash,
MobAttack,
Arrow,
Thrown,
@@ -541,6 +543,14 @@ impl Damage {
from: Some(from),
}
}
/// `DamageSources.mace`: a player's smash attack.
pub fn mace(from: [f64; 3]) -> Self {
Self {
kind: DamageKind::MaceSmash,
attacker: Some(Who::Player),
from: Some(from),
}
}
pub fn mob(id: u32, from: [f64; 3]) -> Self {
Self {
kind: DamageKind::MobAttack,
@@ -1518,6 +1528,16 @@ impl Mob {
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
}
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
self.damage_with(amount, source, None)
}
/// `damage` by a source with a weapon: `armor_effectiveness` runs the
/// weapon's armor-effectiveness enchantments (breach) over the armor fraction.
pub fn damage_with(
&mut self,
amount: f32,
source: Damage,
armor_effectiveness: Option<&mut dyn FnMut(f32) -> f32>,
) -> bool {
raider::note_hurt(self);
if !self.alive() || self.removed || self.invulnerable_flag {
return false;
@@ -1535,7 +1555,11 @@ impl Mob {
let armor = self.kind.armor + worn;
let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0;
let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
amount *= 1.0 - effective / 25.0;
let mut fraction = effective / 25.0;
if let Some(modify) = armor_effectiveness {
fraction = modify(fraction).clamp(0.0, 1.0);
}
amount *= 1.0 - fraction;
}
// CombatRules.getDamageAfterMagicAbsorb: enchantment protection.
let epf = gear::protection(self, source.kind);
@@ -1570,7 +1594,7 @@ impl Mob {
let (dx, dz) = source.from.map_or((0.0, 0.0), |f| {
(f[0] - self.position.x, f[2] - self.position.z)
});
self.knockback(0.4, dx, dz);
self.knockback(f64::from(0.4f32), dx, dz);
}
ai::after_hurt(self, &source);
if self.health <= 0.0 {
@@ -1597,7 +1621,7 @@ impl Mob {
}
/// LivingEntity.knockback(power, xd, zd) towards the negative direction.
pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) {
let power = power * (1.0 - self.kind.knockback_resistance);
let power = power * (1.0 - self.attrs.knockback_resistance);
if power <= 0.0 {
return;
}
@@ -117,6 +117,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
let direct = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MaceSmash
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
+4 -1
View File
@@ -291,7 +291,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.hurt_time == 10
&& !moving
&& let Some((d, _)) = m.last_damage
&& matches!(d.kind, DamageKind::PlayerAttack | DamageKind::MobAttack)
&& matches!(
d.kind,
DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
)
{
let from = [m.position.x, m.position.y, m.position.z];
match d.attacker {
@@ -289,6 +289,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool {
let immune = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MaceSmash
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
+20
View File
@@ -143,6 +143,13 @@ pub enum MotionEvent {
InsidePortal {
pos: BlockPos,
},
/// `ServerPlayer.checkFallDamage` after a mace smash: block particles
/// from the landing block, more the further the fall.
SmashLanding {
state: BlockStateId,
position: BlockPos,
fall_distance: f64,
},
}
pub struct PlayerMotion {
pub position: Vec3,
@@ -200,6 +207,9 @@ pub struct PlayerMotion {
pub events: Vec<MotionEvent>,
pub attributes: LiveAttributes<Box<dyn FnMut() -> i32>>,
pub impulse: ImpulseContext,
/// `ServerPlayer.spawnExtraParticlesOnFall`: a mace smash on a grounded
/// target makes the next landing throw up the block below.
pub spawn_extra_particles_on_fall: bool,
pub health: crate::health::PlayerHealth,
/// Status effects and armor protection seen by movement and damage.
pub status: crate::effects::StatusFlags,
@@ -259,6 +269,7 @@ impl PlayerMotion {
health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?,
status: crate::effects::StatusFlags::default(),
impulse: ImpulseContext::default(),
spawn_extra_particles_on_fall: false,
position,
velocity: Vec3::ZERO,
ground: GroundState::default(),
@@ -1385,6 +1396,15 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
state: BlockStateId,
position: BlockPos,
) -> Result<()> {
if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
{
self.player.events.push(MotionEvent::SmashLanding {
state,
position,
fall_distance: self.player.fall_distance,
});
self.player.spawn_extra_particles_on_fall = false;
}
self.player.events.push(MotionEvent::Landing {
dy,
grounded,
@@ -281,6 +281,8 @@ public final class VanillaBlockUpdateOracle {
if (entities != null) entities.add(entity);
return true;
}
/** No players watch: the hurt animation and its sound are not sent. */
@Override public void broadcastDamageEvent(Entity entity, net.minecraft.world.damagesource.DamageSource source) { }
@Override public void levelEvent(Entity source, int type, BlockPos p, int data) { emit("L " + type + " " + pos(p) + " " + data); }
@Override public void playSeededSound(Entity except, double x, double y, double z, net.minecraft.core.Holder<SoundEvent> sound, SoundSource source, float volume, float pitch, long seed) {
emit("S " + pos(BlockPos.containing(x, y, z)) + " " + sound.value().location());
@@ -218,6 +218,19 @@ public final class VanillaDispenserOracle {
}
if (e.has("chest") && ent instanceof net.minecraft.world.entity.animal.equine.AbstractChestedHorse chested) chested.setChest(true);
if (e.has("loot") && ent instanceof Mob mob) mob.setCanPickUpLoot(true);
if (e.has("ground")) ent.setOnGround(true);
if (e.has("health") && ent instanceof LivingEntity living) {
living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.MAX_HEALTH).setBaseValue(e.get("health").getAsDouble());
living.setHealth(e.get("health").getAsFloat());
}
if (e.has("knockback_resistance") && ent instanceof LivingEntity living) {
living.getAttribute(net.minecraft.world.entity.ai.attributes.Attributes.KNOCKBACK_RESISTANCE).setBaseValue(e.get("knockback_resistance").getAsDouble());
}
if (e.has("marker") && ent instanceof net.minecraft.world.entity.decoration.ArmorStand stand) {
Method marker = net.minecraft.world.entity.decoration.ArmorStand.class.getDeclaredMethod("setMarker", boolean.class);
marker.setAccessible(true);
marker.invoke(stand, true);
}
if (e.has("brown") && ent instanceof net.minecraft.world.entity.animal.cow.MushroomCow cow) {
Method variant = net.minecraft.world.entity.animal.cow.MushroomCow.class.getDeclaredMethod("setVariant", net.minecraft.world.entity.animal.cow.MushroomCow.Variant.class);
variant.setAccessible(true);
@@ -318,6 +331,8 @@ public final class VanillaDispenserOracle {
used = useItem(w, origin, f.getAsJsonObject("use_item"));
} else if (f.has("respawn_at")) {
used = respawnAt(w, origin, f.getAsJsonObject("respawn_at"));
} else if (f.has("attack")) {
used = attack(w, f.getAsJsonObject("attack"), targets);
} else if (f.has("hopper")) {
// HopperBlockEntity.pushItemsTick, once.
var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin);
@@ -578,6 +593,148 @@ public final class VanillaDispenserOracle {
return List.of("respawn " + num(p.x) + " " + num(p.y) + " " + num(p.z) + " " + Float.floatToRawIntBits((float) yaw.invoke(angle)));
}
/**
* The player of an "attack" case: a `ServerPlayer` with a place, a fall
* and a velocity, a stand-in connection and abilities.
*/
static final class Attacker extends net.minecraft.server.level.ServerPlayer {
VanillaBlockUpdateOracle.World world;
boolean creative, fallFlying;
ItemStack hand;
List<String> stats;
Attacker() {
super(null, null, null, null);
}
@Override public ServerLevel level() { return world; }
@Override public boolean hasInfiniteMaterials() { return creative; }
@Override public boolean isCreative() { return creative; }
@Override public boolean isSpectator() { return false; }
@Override public boolean isFallFlying() { return fallFlying; }
@Override public net.minecraft.world.phys.Vec3 getKnownMovement() { return getDeltaMovement(); }
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; }
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY;
}
@Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) {
if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack;
}
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
}
}
/** The synched data `Entity`'s constructor defines (a player's air supply is 300). */
@SuppressWarnings({"unchecked", "rawtypes"})
static void defineData(Entity e) throws Exception {
var builder = new net.minecraft.network.syncher.SynchedEntityData.Builder(e);
Object[][] base = {{"DATA_SHARED_FLAGS_ID", (byte) 0}, {"DATA_AIR_SUPPLY_ID", 300}, {"DATA_CUSTOM_NAME_VISIBLE", false},
{"DATA_CUSTOM_NAME", Optional.empty()}, {"DATA_SILENT", false}, {"DATA_NO_GRAVITY", false}, {"DATA_POSE", Pose.STANDING},
{"DATA_TICKS_FROZEN", 0}};
for (Object[] d : base) {
Field f = Entity.class.getDeclaredField((String) d[0]);
f.setAccessible(true);
builder.define((net.minecraft.network.syncher.EntityDataAccessor) f.get(null), d[1]);
}
Method define = Entity.class.getDeclaredMethod("defineSynchedData", net.minecraft.network.syncher.SynchedEntityData.Builder.class);
define.setAccessible(true);
define.invoke(e, builder);
VanillaBlockUpdateOracle.set(Entity.class, e, "entityData", builder.build());
}
/** A connection to no client: the motion packets a smash sends go nowhere. */
static final class Silent extends net.minecraft.server.network.ServerGamePacketListenerImpl {
Silent() { super(null, null, null, null); }
@Override public void send(net.minecraft.network.protocol.Packet<?> packet) { }
}
/**
* A player hit on the first target with the case's item, as
* `Player.attack` and `itemAttackInteraction` run it after the attack
* strength scaled the base damage to `base`: the item's damage bonus
* (`MaceItem.getAttackDamageBonus`) and damage source, the target's real
* `hurtServer` (armor with the weapon's Breach), then `hurtEnemy` (the
* mace's smash), the post-attack enchantments (Wind Burst) and
* `postHurtEnemy` (the fall reset and the weapon's wear). Every target's
* health and velocity, the player's velocity, fall, impulse and the
* statistics follow.
*/
static List<String> attack(VanillaBlockUpdateOracle.World w, JsonObject op, List<Entity> targets) throws Exception {
if (VanillaBlockUpdateOracle.Server.players == null) {
VanillaBlockUpdateOracle.Server.players = (Ops) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Ops.class);
}
Attacker player = (Attacker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Attacker.class);
player.world = w;
player.creative = op.get("creative").getAsBoolean();
player.fallFlying = op.get("fall_flying").getAsBoolean();
player.hand = stack(op.get("item").getAsString());
player.stats = new ArrayList<>();
var abilities = new net.minecraft.world.entity.player.Abilities();
abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative;
abilities.flying = op.get("flying").getAsBoolean();
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities);
var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class);
VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>());
VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements);
player.connection = (Silent) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Silent.class);
defineData(player);
player.setId(w.getNextEntityId());
VanillaBlockUpdateOracle.set(LivingEntity.class, player, "attributes",
new net.minecraft.world.entity.ai.attributes.AttributeMap(net.minecraft.world.entity.player.Player.createAttributes().build()));
player.setUUID(new UUID(0L, 1L));
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "gameProfile",
new com.mojang.authlib.GameProfile(new UUID(0L, 1L), "Player"));
var p = op.getAsJsonArray("player");
var at = new net.minecraft.world.phys.Vec3(p.get(0).getAsDouble(), p.get(1).getAsDouble(), p.get(2).getAsDouble());
VanillaBlockUpdateOracle.set(Entity.class, player, "position", at);
VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at));
var standing = EntityTypes.PLAYER.getDimensions();
VanillaBlockUpdateOracle.set(Entity.class, player, "dimensions", standing);
VanillaBlockUpdateOracle.set(Entity.class, player, "eyeHeight", standing.eyeHeight());
player.setBoundingBox(standing.makeBoundingBox(at));
var m = op.getAsJsonArray("motion");
player.setDeltaMovement(m.get(0).getAsDouble(), m.get(1).getAsDouble(), m.get(2).getAsDouble());
player.fallDistance = op.get("fall").getAsDouble();
if (op.has("impact")) {
var i = op.getAsJsonArray("impact");
player.currentImpulseImpactPos = new net.minecraft.world.phys.Vec3(i.get(0).getAsDouble(), i.get(1).getAsDouble(), i.get(2).getAsDouble());
}
// The player stands in the level, for the bursts that push it.
w.entities.add(player);
LivingEntity target = (LivingEntity) targets.get(0);
ItemStack weapon = player.hand;
var source = weapon.getDamageSource(player);
float base = op.get("base").getAsFloat();
float bonus = weapon.getItem().getAttackDamageBonus(target, base, source);
boolean hurt = target.hurtServer(w, source, base + bonus);
if (hurt) {
boolean weaponHit = weapon.hurtEnemy(target, player);
net.minecraft.world.item.enchantment.EnchantmentHelper.doPostAttackEffectsWithItemSource(w, target, source, weapon);
if (weaponHit) weapon.postHurtEnemy(target, player);
}
w.entities.remove(player);
List<String> out = new ArrayList<>(player.stats);
out.add("attack bonus=" + num(bonus) + " source=" + source.typeHolder().getRegisteredName() + " hurt=" + hurt);
for (int i = 0; i < targets.size(); i++) {
Entity e = targets.get(i);
var v = e.getDeltaMovement();
String health = e instanceof LivingEntity living && !(e instanceof net.minecraft.world.entity.decoration.ArmorStand) ? num(living.getHealth()) : "-";
out.add("V " + i + " " + health + " " + num(v.x) + " " + num(v.y) + " " + num(v.z));
}
var v = player.getDeltaMovement();
var impact = player.currentImpulseImpactPos;
Field grace = LivingEntity.class.getDeclaredField("currentImpulseContextResetGraceTime");
grace.setAccessible(true);
Field extra = net.minecraft.server.level.ServerPlayer.class.getDeclaredField("spawnExtraParticlesOnFall");
extra.setAccessible(true);
out.add("P " + num(v.x) + " " + num(v.y) + " " + num(v.z) + " fall=" + num(player.fallDistance)
+ " impact=" + (impact == null ? "-" : num(impact.x) + "," + num(impact.y) + "," + num(impact.z))
+ " grace=" + grace.getInt(player) + " extra=" + extra.getBoolean(player));
out.add("held " + ParityData.canon(player.hand));
return out;
}
/** The level's block entity positions by x, y, z. */
static List<BlockPos> sortedEntities(VanillaBlockUpdateOracle.World w) {
List<BlockPos> out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet());
+204
View File
@@ -0,0 +1,204 @@
"""Compare a player's melee hit with a mace (and other weapons) with vanilla's.
Every case has a stone floor, a target mob standing on it or hanging in the
air (health raised so no hit kills it, sometimes in armor), other mobs and
armor stands around it, and a player near the target holding a mace with
Density, Breach, Wind Burst and Unbreaking in any mix, or a sword, an axe, a
stick or nothing. The player has fallen some distance (sometimes gliding or
flying), moves, and may still have the impact point of an earlier impulse.
Vanilla runs, over the headless level of the dispenser harness
(`VanillaDispenserOracle.attack`), the steps of `Player.attack` after the
attack strength scaled the base damage: `Item.getAttackDamageBonus`
(`MaceItem`'s smash bonus with Density), the item's damage source
(`mace_smash` or `player_attack`), the target's real `hurtServer` (armor
thinned by Breach in `CombatRules.getDamageAfterAbsorb`), then
`itemAttackInteraction`: `ItemStack.hurtEnemy` (`MaceItem.hurtEnemy`: the
stopped fall, the waived fall damage, the smash sounds, the dust-pillar level
event and the knockback around the target), the post-attack enchantments
(Wind Burst's `ExplodeEffect` on the player) and `postHurtEnemy` (the fall
reset and the weapon's wear with Unbreaking). Horizon runs the same steps
through the helpers `Game::attack` uses (`smash_damage_bonus`,
`hurt_by_player`, `weapon_hit`) in a headless game
(`HORIZON_DISPENSE_FIXTURE`). Both print every target's health and
velocity, the player's velocity, fall distance, impulse impact and grace
time and its landing-particle flag, sounds, level and game events, the used
statistic, the held stack and the level random afterwards.
"""
import json
import math
import os
import random
try:
from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base
except ImportError:
import block_update_harness as h
import lab
import test_dispenser_parity as d
import test_rust_parity as base
TARGETS = ['pig', 'cow', 'sheep', 'zombie', 'husk', 'skeleton', 'zombie', 'pig']
AROUND = ['pig', 'cow', 'zombie', 'sheep', 'armor_stand']
ARMOR = ['iron', 'diamond', 'golden', 'chainmail', 'leather']
FALLS = [0.0, 0.5, 1.0, 1.5, 1.5000001, 2.0, 2.75, 3.0, 3.25, 5.0, 5.0001, 6.5, 8.0, 8.5, 12.0, 25.3, 60.0]
def stack(item, enchantments=None, damage=0):
components = []
if enchantments:
levels = ','.join(f'"minecraft:{e}":{lvl}' for e, lvl in enchantments.items())
components.append('"minecraft:enchantments":{%s}' % levels)
if damage:
components.append(f'"minecraft:damage":{damage}')
extra = ',components:{%s}' % ','.join(components) if components else ''
return '{id:"minecraft:%s",count:1%s}' % (item, extra)
def weapon(rng):
roll = rng.random()
if roll < 0.75:
enchantments = {}
for name, top in [('density', 5), ('breach', 4), ('wind_burst', 3), ('unbreaking', 3)]:
if rng.random() < 0.35:
enchantments[name] = rng.randint(1, top)
return stack('mace', enchantments, rng.choice([0, 0, 0, 7, 300]))
if roll < 0.85:
return stack(rng.choice(['diamond_sword', 'iron_axe', 'stone_pickaxe']),
{'breach': 2} if rng.random() < 0.2 else None, rng.choice([0, 0, 10]))
return rng.choice([stack('stick'), '-'])
def cases(facts, count, seed):
rng = random.Random(seed)
states = d.States(facts)
floors = [states.get(b) for b in ['stone', 'grass_block', 'dirt', 'sand', 'oak_planks']]
for n in range(count):
case = {**h.environment(rng), 'pos': [0, 0, 0]}
case.pop('raining', None)
case.pop('thundering', None)
floor = rng.choice(floors)
case['cells'] = [[x, -1, z, floor] for x in range(-6, 7) for z in range(-6, 7)]
if rng.random() < 0.2:
# A wall the burst and the dust have to get past.
wall = states.get(rng.choice(['stone', 'glass', 'oak_planks']))
x = rng.choice([-3, -2, 2, 3])
case['cells'] += [[x, y, z, wall] for y in range(0, 3) for z in range(-2, 3)]
item = weapon(rng)
wind = 'wind_burst' in item
grounded = rng.random() < 0.75
tx, tz = rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)
ty = 0.0 if grounded else rng.choice([0.5, 1.25, 2.0])
target = {'type': 'minecraft:' + rng.choice(TARGETS), 'pos': [tx, ty, tz], 'yaw': rng.uniform(-180, 180),
'health': 1000.0}
if grounded:
target['ground'] = True
if target['type'] in ('minecraft:zombie', 'minecraft:husk', 'minecraft:skeleton') and rng.random() < 0.6:
material = rng.choice(ARMOR)
target['equip'] = {'chest': d.plain(f'{material}_chestplate')}
if rng.random() < 0.5:
target['equip']['head'] = d.plain(f'{material}_helmet')
if rng.random() < 0.15:
target['knockback_resistance'] = rng.choice([0.25, 0.5, 1.0])
entities = [target]
for _ in range(rng.choice([0, 1, 2, 3, 5])):
kind = rng.choice(AROUND)
near = rng.random() < 0.8
spread = 3.2 if near else 5.0
e = {'type': 'minecraft:' + kind, 'pos': [tx + rng.uniform(-spread, spread), rng.choice([0.0, 0.0, 0.5, 1.0]),
tz + rng.uniform(-spread, spread)], 'yaw': rng.uniform(-180, 180)}
if kind == 'armor_stand':
# A marker is spared by the smash; Wind Burst's explosion would
# need its zero-size box.
if not wind and rng.random() < 0.4:
e['marker'] = True
else:
e['health'] = 1000.0
if rng.random() < 0.2:
e['knockback_resistance'] = rng.choice([0.4, 1.0])
if e['pos'][1] == 0.0 and rng.random() < 0.8:
e['ground'] = True
entities.append(e)
case['entities'] = entities
angle = rng.uniform(0, 6.283)
reach = rng.uniform(0.6, 2.8)
px, pz = tx + math.cos(angle) * reach, tz + math.sin(angle) * reach
py = ty + rng.choice([0.0, 0.3, 1.0, 1.7, 2.5])
fall = rng.choice(FALLS) if rng.random() < 0.7 else round(rng.uniform(0, 30), 3)
attack = {'item': item, 'creative': rng.random() < 0.15, 'player': [px, py, pz],
'motion': [rng.uniform(-0.3, 0.3), -rng.uniform(0, 2.5), rng.uniform(-0.3, 0.3)],
'fall': fall, 'fall_flying': rng.random() < 0.08, 'flying': rng.random() < 0.04,
'base': round(rng.uniform(1.2, 7.0), 3)}
if rng.random() < 0.3:
attack['impact'] = [px + rng.uniform(-1, 1), py + rng.choice([-3.0, -0.5, 0.0, 2.0]), pz + rng.uniform(-1, 1)]
case['attack'] = attack
case['items'] = []
case['mode'] = 'dispense'
yield case
def kind(case):
item = case['attack']['item']
name = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand'
smash = case['attack']['fall'] > 1.5 and not case['attack']['fall_flying']
if name == 'mace':
name += ' smash' if smash else ' hit'
if 'wind_burst' in item:
name += ' with wind burst'
return name
def main():
parser = h.argument_parser(__doc__)
args = parser.parse_args()
if args.count == 40000:
args.count = 3000
lock, jars, libraries = base.verify_artifacts()
facts = h.load_facts()
resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version']
work = lab.LOCAL / 'mace-parity'
work.mkdir(parents=True, exist_ok=True)
all_cases = list(cases(facts, args.count, args.seed))
(work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases))
classes = work / 'classes'
classes.mkdir(exist_ok=True)
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
java_root = lab.ROOT / 'mods/horizon/src/test/java'
d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn',
'-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')])
d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle',
str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')])
d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT,
env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')})
d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work,
env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'})
ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',)
native = h.split_cases((work / 'native.txt').read_text(), ignore)
rust = h.split_cases((work / 'rust.txt').read_text(), ignore)
assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases))
groups, errors = {}, {}
smashed = burst = 0
for case, a, b in zip(all_cases, native, rust):
if a and a[0].startswith('error'):
errors.setdefault(a[0], []).append(case)
continue
smashed += any('source=minecraft:mace_smash hurt=true' in line for line in a)
burst += any(line.endswith('minecraft:entity.wind_charge.wind_burst') for line in a)
if not d.same(a, b):
groups.setdefault(kind(case), []).append((case, a, b))
for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])):
print(f'oracle error x{len(entries)}: {name}')
for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])):
print(f'{name}: {len(entries)} differing')
for case, a, b in entries[:args.show]:
print(' case entities=' + json.dumps(case['entities']) + ' attack=' + json.dumps(case['attack']) + f' seed={case["seed"]}')
print(' native ' + ' | '.join(sorted(a)))
print(' rust ' + ' | '.join(sorted(b)))
total = sum(len(v) for v in groups.values())
skipped = sum(len(v) for v in errors.values())
print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); '
f'vanilla smashed in {smashed} and burst in {burst}')
h.finish(total + skipped)
if __name__ == '__main__':
main()