WIP passengers, mob gear enchantments, held blocks

Work in progress on riders, enchanted spawn gear and held block rendering.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 03:47:46 +02:00
parent 02d1507d39
commit 2c9045649f
20 changed files with 1533 additions and 190 deletions
+12 -1
View File
@@ -41,7 +41,7 @@ struct Out {
// Overlay 6 (beacon beams): the light bytes carry the sprite's v range.
out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0;
// Hurt overlay (OverlayTexture red tint).
if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
if overlay == 1u || overlay == 8u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
out.color = c;
// Overlay 5: OverlayTexture white flash (primed TNT), applied after texturing.
out.flash = select(0.0, 0.75, overlay == 5u);
@@ -67,6 +67,17 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
}
if color.a < 0.1 { discard; }
color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a);
if in.overlay == 7u || in.overlay == 8u {
// Enchantment glint (overlay 7, 8 with the hurt tint): the purple
// enchanted_glint sheen drifting diagonally over the item's shape.
let px = in.uv * vec2<f32>(textureDimensions(atlas));
let t = globals.misc.y * 0.05;
let band = sin((px.x + px.y) * 0.9 - t * 6.0) * 0.5 + 0.5;
let band2 = sin((px.x - px.y) * 0.6 + t * 4.0) * 0.5 + 0.5;
let shimmer = pow(band * 0.6 + band2 * 0.4, 2.0);
let glint = vec3(0.50, 0.25, 0.80) * (0.25 + 0.75 * shimmer);
color = vec4(min(color.rgb + glint * 0.6, vec3(1.0)), color.a);
}
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, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
+22 -2
View File
@@ -363,20 +363,33 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
_ => {}
}
crate::mobs::raider::write_nbt(m, map);
crate::mobs::riders::write_nbt(m, map);
// LivingEntity equipment: what the mob holds now.
if !crate::mobs::equine::is_equine(m.species()) {
let mut equipment = match map.get(&"equipment".into()) {
Some(Tag::Compound(c)) => c.clone(),
_ => horizon_world::nbt::Compound::new(),
};
for (slot, item) in [
for (index, (slot, item)) in [
("mainhand", &m.extra.main_hand),
("offhand", &m.extra.off_hand),
("head", &m.extra.head),
("chest", &m.extra.chest),
("legs", &m.extra.legs),
("feet", &m.extra.feet),
] {
]
.into_iter()
.enumerate()
{
// Enchanted gear is saved with its `minecraft:enchantments`.
if let (Some(id), Some(g)) = (item, crate::mobs::gear::gear(m))
&& !g.slots[index].is_empty()
{
let mut stack = crate::items::ItemStack::new(id, 1);
stack.data_mut().enchantments = g.slots[index].clone();
equipment.insert(slot.into(), crate::save::item_to_nbt(&stack));
continue;
}
match item {
Some(id) => {
let keep = matches!(
@@ -458,6 +471,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.legs = slot("legs");
m.extra.feet = slot("feet");
}
// Their enchantments.
for (index, key) in crate::mobs::gear::KEYS.iter().enumerate() {
if let Some(stack) = eq.get(key).and_then(crate::save::item_from_nbt) {
crate::mobs::gear::set(&mut m, index, stack.enchantments().to_vec());
}
}
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
@@ -632,6 +651,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.flag2 = flag(tag, "wasOnGround");
}
crate::mobs::raider::read_nbt(&mut m, tag);
crate::mobs::riders::read_nbt(&mut m, tag);
// A mob saved mid-death finishes dying; one saved dead is dropped.
if m.health <= 0.0 && m.death_time == 0 {
return None;
+3
View File
@@ -34,12 +34,15 @@ mod lightning;
mod machines;
mod maps;
mod minecarts;
mod mob_blocks;
mod mob_gear;
mod mounts;
mod music;
mod names;
mod options;
mod packs;
mod paintings;
mod passengers;
mod persist;
mod perspective;
mod piglins;
+52 -15
View File
@@ -244,6 +244,10 @@ impl Game<'_> {
}
let id = mob.id;
self.mobs.push(mob);
self.enchant_spawn_equipment(id);
if !persistent && !scripted {
self.spawn_jockeys(id, true);
}
Some(id)
}
/// The `summon` command: spawn a mob in front of the player or at a position.
@@ -266,6 +270,7 @@ impl Game<'_> {
if baby && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.extra.age = -24000;
}
self.spawn_jockeys(id, false);
Ok(id)
}
/// The `mobs` command: nearby mobs with position, health and running goals.
@@ -285,6 +290,9 @@ impl Game<'_> {
"target": m.ai.target.map(|t| format!("{t:?}")),
"goals": m.ai.goals.running_names(),
"held": m.extra.main_hand.as_deref(),
"mount": m.extra.mount,
"rider": m.extra.rider,
"enchants": horizon_client::mobs::gear::gear(m).map(|g| g.slots.iter().map(|s| s.iter().map(|(e, l)| format!("{e}:{l}")).collect::<Vec<_>>()).collect::<Vec<_>>()),
"ints": m.extra.ints,
"pois": [m.extra.home, m.extra.bed, m.extra.meeting],
"profession": m.extra.variant2,
@@ -306,7 +314,7 @@ impl Game<'_> {
"leader": s.patrol_leader,
"patrolling": s.patrolling,
"patrol_target": s.patrol_target,
"vehicle": s.vehicle,
"vehicle": m.extra.mount,
})),
})
})
@@ -678,6 +686,9 @@ impl Game<'_> {
}
self.mobs.append(&mut mobs);
self.sync_riders();
self.tick_skeleton_traps();
self.cache_mob_icons();
self.tick_apparition();
self.villager_reputation_tick();
self.villager_pickups();
for m in dead {
@@ -756,7 +767,16 @@ impl Game<'_> {
m.extra.feet.clone(),
]
};
for item in std::iter::once(m.extra.main_hand.clone()).chain(worn) {
for (index, item) in std::iter::once(m.extra.main_hand.clone())
.chain(worn)
.enumerate()
{
// Main hand, then head to feet (the enchantment slots).
let slot = if index == 0 {
horizon_client::mobs::gear::MAIN
} else {
horizon_client::mobs::gear::HEAD + index - 1
};
// Equipment drop chance 8.5% (+ player kill only).
// Vexes never drop their sword.
if let Some(item) = &item
@@ -765,17 +785,13 @@ impl Game<'_> {
&& m.species() != Species::Vex
&& self.world.random.next_float() < 0.085
{
self.spawn_item(
ItemStack {
item: item.clone(),
count: 1,
damage: 0,
extra: None,
},
pos,
[0.0, 0.2, 0.0],
10,
);
let mut stack = ItemStack::new(item, 1);
if let Some(g) = horizon_client::mobs::gear::gear(m) {
for (e, l) in &g.slots[slot] {
stack.enchant(e, *l);
}
}
self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10);
}
}
}
@@ -1262,7 +1278,7 @@ impl Game<'_> {
self.give_player_effect("minecraft:mining_fatigue", 6000, 2);
self.audio
.play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0);
self.creatures.elder_apparition = 30;
self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS;
}
/// Damage of a given type to the player from a point.
pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) {
@@ -1453,7 +1469,22 @@ impl Game<'_> {
};
match (&p.kind, hit) {
(ProjectileKind::Arrow { effect, .. }, Hit::Entity { who, .. }) => {
let amount = p.arrow_damage(&mut self.world.random);
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
// Punch pushes along the flight, Flame burns for five seconds.
let flight = (p.velocity.x * p.velocity.x + p.velocity.z * p.velocity.z).sqrt();
if p.bonus.punch > 0 && flight > 1e-6 {
let k = f64::from(p.bonus.punch) * 0.6 / flight;
self.handle_mob_events(vec![MobEvent::Push {
target: who,
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
}])?;
}
if p.bonus.flame {
self.handle_mob_events(vec![MobEvent::Ignite {
target: who,
seconds: 5,
}])?;
}
match who {
Who::Player => {
if !self.creative {
@@ -2269,6 +2300,7 @@ impl Game<'_> {
&self.res.mob_data,
out,
);
self.mob_block_geometry(mob, camera, alpha, packed, out);
// GuardianRenderer: the laser to the locked target.
if let Some((time, scale)) = horizon_client::mobs::guardian::beam(mob, alpha as f32)
&& let Some(target) = self.beam_target(mob.ai.target, alpha)
@@ -2290,6 +2322,7 @@ impl Game<'_> {
);
}
}
self.elder_apparition_geometry(alpha, out);
// Projectiles: arrows as crossed quads, the rest as item billboards.
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
@@ -2470,6 +2503,10 @@ fn push_apart(mobs: &mut [Mob]) {
if !mobs[j].alive() || !bi.intersects(mobs[j].bounds()) {
continue;
}
// A rider and its vehicle do not push each other.
if mobs[i].extra.mount == Some(mobs[j].id) || mobs[j].extra.mount == Some(mobs[i].id) {
continue;
}
let (dx, dz) = (
mobs[j].position.x - mobs[i].position.x,
mobs[j].position.z - mobs[i].position.z,
+7 -1
View File
@@ -58,7 +58,13 @@ impl Game<'_> {
&& !below.ends_with("lightning_rod");
if trap {
let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])];
let _ = self.spawn_mob("minecraft:skeleton_horse", at, false);
// ServerLevel.tickChunk: a trap horse waits for a player.
if let Some(id) = self.spawn_mob("minecraft:skeleton_horse", at, false)
&& let Some(h) = self.mobs.iter_mut().find(|m| m.id == id)
{
h.extra.trap = true;
h.extra.age = 0;
}
}
let at = [
f64::from(pos[0]) + 0.5,
@@ -0,0 +1,295 @@
//! Blocks mobs carry: block items in a hand (`ItemInHandLayer`) and the
//! block an enderman holds (`CarriedBlockLayer`), drawn as shaded cubes like
//! dropped block items.
use super::{Game, Icon};
use horizon_client::{
mesher::Vertex,
mobs::{Mob, Species, render},
};
/// The six faces of the unit cube with their shade: top, bottom, the two
/// z faces, the two x faces.
const FACES: [([[f32; 3]; 4], f32, u8); 6] = [
(
[[0., 1., 1.], [1., 1., 1.], [1., 1., 0.], [0., 1., 0.]],
1.0,
0,
),
(
[[0., 0., 0.], [1., 0., 0.], [1., 0., 1.], [0., 0., 1.]],
0.5,
0,
),
(
[[1., 0., 0.], [0., 0., 0.], [0., 1., 0.], [1., 1., 0.]],
0.8,
1,
),
(
[[0., 0., 1.], [1., 0., 1.], [1., 1., 1.], [0., 1., 1.]],
0.8,
1,
),
(
[[0., 0., 0.], [0., 0., 1.], [0., 1., 1.], [0., 1., 0.]],
0.6,
2,
),
(
[[1., 0., 1.], [1., 0., 0.], [1., 1., 0.], [1., 1., 1.]],
0.6,
2,
),
];
/// The sprites of a cube's top, z sides and x sides, and the top's tint.
struct Cube<'a> {
sprites: [&'a str; 3],
tint: u32,
}
/// `CustomHeadLayer.translateToHead` and the banner's `head` display.
fn banner_matrix(head: glam::Mat4) -> glam::Mat4 {
head * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.25, 0.0))
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
* glam::Mat4::from_scale(glam::Vec3::new(0.625, -0.625, -0.625))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 1.0, 7.0 / 16.0))
* glam::Mat4::from_rotation_y(std::f32::consts::PI)
* glam::Mat4::from_scale(glam::Vec3::splat(1.5))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0))
* glam::Mat4::from_scale(glam::Vec3::new(2.0 / 3.0, -2.0 / 3.0, -2.0 / 3.0))
}
/// `ElderGuardianParticle.lifetime`.
pub(super) const APPARITION_TICKS: i32 = 30;
impl Game<'_> {
/// Count the elder guardian's apparition down.
pub(super) fn tick_apparition(&mut self) {
self.creatures.elder_apparition = (self.creatures.elder_apparition - 1).max(0);
}
/// `ElderGuardianParticleGroup`: the ghostly elder guardian that swings
/// up in front of the camera while the curse is laid, fading in and out.
pub(super) fn elder_apparition_geometry(&self, alpha: f64, out: &mut Vec<Vertex>) {
let left = self.creatures.elder_apparition;
if left <= 0 {
return;
}
let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else {
return;
};
let Some(r) = self.res.atlas.sprites.get("entity/guardian_elder").copied() else {
return;
};
let age = (APPARITION_TICKS - left) as f32 + alpha as f32;
let t = (age / APPARITION_TICKS as f32).clamp(0.0, 1.0);
let fade = 0.05 + 0.5 * (t * std::f32::consts::PI).sin();
let color = (((fade * 255.0) as u32) << 24) | 0x00FF_FFFF;
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
let forward = glam::Vec3::new(
-yaw.sin() * pitch.cos(),
-pitch.sin(),
yaw.cos() * pitch.cos(),
);
let right = forward.cross(glam::Vec3::Y).normalize_or_zero();
let up = right.cross(forward).normalize_or_zero();
// The camera's rotation: local +x right, +y up, +z behind.
let camera = glam::Mat4::from_cols(
right.extend(0.0),
up.extend(0.0),
(-forward).extend(0.0),
glam::Vec4::W,
);
let k = 0.425_531_92;
let m = camera
* glam::Mat4::from_rotation_x((60.0 - 150.0 * t).to_radians())
* glam::Mat4::from_scale(glam::Vec3::new(k, -k, -k))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.56, 3.5));
let poses = horizon_client::mobs::anim::Poses::new(&kind.model);
render::draw(
&kind.model,
m,
&poses,
[r.u0, r.v0, r.u1, r.v1],
color,
240 | 240 << 8,
0,
out,
);
}
/// The ominous banner a raid captain wears on its head: the banner model
/// with its eight pattern layers (`CustomHeadLayer`).
fn captain_banner_geometry(
&self,
mob: &Mob,
camera: glam::DVec3,
alpha: f64,
light: u32,
out: &mut Vec<Vertex>,
) {
use horizon_client::mobs::{Part, anim::Poses, load_model};
static MODELS: std::sync::OnceLock<Option<(Part, Part)>> = std::sync::OnceLock::new();
if !horizon_client::mobs::raider::is_captain(mob) {
return;
}
let Some((pole, flag)) = MODELS.get_or_init(|| {
let root = &self.options.resources;
Some((
load_model(root, "minecraft:standing_banner#main")?,
load_model(root, "minecraft:standing_banner#flag")?,
))
}) else {
return;
};
let Some(head) =
render::part_transform(mob, alpha as f32, camera, &self.res.mob_data, "head")
else {
return;
};
let m = banner_matrix(head);
let atlas = &self.res.atlas;
let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
// BannerRenderer: the flag sways with a per-banner phase.
let phase =
(((u64::from(mob.id) * 7 + u64::from(mob.age)) % 100) as f32 + alpha as f32) / 100.0;
let mut flag_poses = Poses::new(flag);
flag_poses.xrot(
"flag",
(-0.0125 + 0.01 * (2.0 * std::f32::consts::PI * phase).cos()) * std::f32::consts::PI,
);
let still = Poses::new(pole);
let white = 0xFFFF_FFFF;
if let Some(r) = uv("entity/banner/banner_base") {
render::draw(pole, m, &still, r, white, light, 0, out);
render::draw(flag, m, &flag_poses, r, white, light, 0, out);
}
let layers =
std::iter::once(("base", "white")).chain(horizon_client::item_data::OMINOUS_LAYERS);
for (pattern, dye) in layers {
let Some(r) = uv(&format!("entity/banner/{pattern}")) else {
continue;
};
let index = render::DYE_NAMES
.iter()
.position(|n| *n == dye)
.unwrap_or(0);
let color = render::abgr(render::DYE[index]);
render::draw(flag, m, &flag_poses, r, color, light, 0, out);
}
}
/// Resolve the icons of the items mobs hold, so drawing can look them up.
pub(super) fn cache_mob_icons(&mut self) {
let items: Vec<String> = self
.mobs
.iter()
.filter(|m| m.extra.main_hand.is_some() || m.extra.off_hand.is_some())
.flat_map(|m| [m.extra.main_hand.clone(), m.extra.off_hand.clone()])
.flatten()
.map(|i| i.to_string())
.collect();
for item in items {
if !self.res.icons.contains_key(&item) {
let _ = self.icon(&item);
}
}
}
fn push_cube(
&self,
t: glam::Mat4,
cube: &Cube,
light: u32,
overlay: u32,
out: &mut Vec<Vertex>,
) {
for (corners, shade, side) in FACES {
let name = cube.sprites[usize::from(side)];
let Some(r) = self.res.atlas.sprites.get(name).copied() else {
continue;
};
let tint = if side == 0 { cube.tint } else { 0xFF_FFFF };
let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32;
let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16);
let uvs = [[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]];
for (corner, uv) in corners.iter().zip(uvs) {
let p = t.transform_point3(glam::Vec3::from(*corner));
out.push(Vertex {
pos: p.to_array(),
uv,
layer: overlay,
color,
light,
});
}
}
}
/// The blocks one mob holds or carries.
pub(super) fn mob_block_geometry(
&self,
mob: &Mob,
camera: glam::DVec3,
alpha: f64,
light: u32,
out: &mut Vec<Vertex>,
) {
let overlay = u32::from(mob.hurt_time > 0);
self.captain_banner_geometry(mob, camera, alpha, light, out);
for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
let Some(item) = item else { continue };
let Some(Icon::Cube {
top,
left: z,
right: x,
tint,
}) = self.res.icons.get(&**item).cloned().flatten()
else {
continue;
};
let Some(t) =
render::held_block_transform(mob, alpha as f32, camera, &self.res.mob_data, left)
else {
continue;
};
let slot = if left {
horizon_client::mobs::gear::OFF
} else {
horizon_client::mobs::gear::MAIN
};
let glint = horizon_client::mobs::gear::enchanted(mob, slot);
let overlay = if glint { 7 } else { overlay };
self.push_cube(
t,
&Cube {
sprites: [&top, &z, &x],
tint,
},
light,
overlay,
out,
);
}
if mob.species() == Species::Enderman
&& let Some(state) = mob.extra.carried
&& let Some((sprite, tint)) = self.particle_sprite(state)
{
// CarriedBlockLayer.
let base = render::base_transform(mob, alpha as f32, camera);
let t = base
* glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.6875, -0.75))
* glam::Mat4::from_rotation_x(20.0f32.to_radians())
* glam::Mat4::from_rotation_y(45.0f32.to_radians())
* glam::Mat4::from_translation(glam::Vec3::new(0.25, 0.1875, 0.25))
* glam::Mat4::from_scale(glam::Vec3::new(-0.5, -0.5, 0.5))
* glam::Mat4::from_rotation_y(90.0f32.to_radians())
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
self.push_cube(
t,
&Cube {
sprites: [&sprite, &sprite, &sprite],
tint,
},
light,
overlay,
out,
);
}
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Enchanting what mobs spawn with (`Mob.populateDefaultEquipmentEnchantments`
//! through the `mob_spawn_equipment` provider) and the raid buffs
//! (`Raider.applyRaidBuffs`).
use super::Game;
use horizon_client::{
mobs::{
Species,
gear::{self, ARMOR, MAIN},
},
raid::{self, RaiderType},
};
use horizon_core::random::RandomSource;
/// `EnchantmentsByCostWithDifficulty` of `mob_spawn_equipment`.
const MIN_COST: i32 = 5;
const MAX_COST_SPAN: f32 = 17.0;
/// The mobs that call `populateDefaultEquipmentEnchantments` when they spawn.
fn enchants_spawn_gear(s: Species) -> bool {
matches!(
s,
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
| Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::Parched
| Species::Pillager
| Species::Vindicator
| Species::Piglin
| Species::Vex
)
}
/// The item a mob holds or wears in an equipment slot.
fn slot_item(m: &horizon_client::mobs::Mob, slot: usize) -> Option<std::sync::Arc<str>> {
match slot {
gear::MAIN => m.extra.main_hand.clone(),
gear::OFF => m.extra.off_hand.clone(),
gear::HEAD => m.extra.head.clone(),
gear::CHEST => m.extra.chest.clone(),
gear::LEGS => m.extra.legs.clone(),
_ => m.extra.feet.clone(),
}
}
impl Game<'_> {
/// `Mob.populateDefaultEquipmentEnchantments`: the weapon one time in
/// four and each piece of armour one time in two, scaled by the local
/// difficulty, enchanted as if at an enchanting table of cost 5 to 22.
pub(super) fn enchant_spawn_equipment(&mut self, id: u32) {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return;
};
let species = m.species();
if !enchants_spawn_gear(species) {
return;
}
let special = self
.local_difficulty([m.position.x, m.position.y, m.position.z])
.special();
self.enchant_slot(id, MAIN, 0.25, special);
for slot in ARMOR {
self.enchant_slot(id, slot, 0.5, special);
}
// Pillager.enchantSpawnedWeapon: one crossbow in 300 pierces.
if species == Species::Pillager && self.world.random.next_int_bound(300).unwrap_or(1) == 0 {
self.enchant_single(id, MAIN, "minecraft:piercing", 1, "minecraft:crossbow");
}
}
fn enchant_slot(&mut self, id: u32, slot: usize, chance: f32, special: f32) {
let Some(item) = self
.mobs
.iter()
.find(|m| m.id == id)
.and_then(|m| slot_item(m, slot))
else {
return;
};
if self.world.random.next_float() >= chance * special {
return;
}
self.enchant_item(id, slot, &item, special);
}
/// `EnchantmentsByCostWithDifficulty.enchant` on the item in a slot.
pub(super) fn enchant_item(&mut self, id: u32, slot: usize, item: &str, special: f32) {
let random = &mut self.world.random;
let top = MIN_COST + (special * MAX_COST_SPAN) as i32;
let cost = random
.next_int_between_inclusive(MIN_COST, top)
.unwrap_or(MIN_COST);
let e = &self.res.stations.enchantments;
let pool = e.tag("minecraft:on_mob_spawn_equipment");
let picked = e.select(&self.res.items, random, item, cost, pool);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
for (enchantment, level) in picked {
gear::upgrade(m, slot, &enchantment, level);
}
}
}
/// A `SingleEnchantment` provider on the item in `slot`, when it is `item`.
fn enchant_single(&mut self, id: u32, slot: usize, enchantment: &str, level: u32, item: &str) {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
&& slot_item(m, slot).as_deref() == Some(item)
{
gear::upgrade(m, slot, enchantment, level);
}
}
/// `Pillager` / `Vindicator.applyRaidBuffs`: Quick Charge on a fresh
/// crossbow after waves 3 and 5, Sharpness on a fresh axe.
pub(super) fn apply_raid_buffs(&mut self, id: u32, kind: RaiderType, wave: i32, odds: f32) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
};
let enchant = m.random.next_float() <= odds;
match kind {
RaiderType::Pillager if enchant => {
let level = if wave > raid::num_groups(2) {
2
} else if wave > raid::num_groups(1) {
1
} else {
0
};
if level > 0 {
m.extra.main_hand = Some("minecraft:crossbow".into());
gear::set(m, MAIN, Vec::new());
gear::upgrade(m, MAIN, "minecraft:quick_charge", level);
}
}
RaiderType::Vindicator => {
m.extra.main_hand = Some("minecraft:iron_axe".into());
gear::set(m, MAIN, Vec::new());
if enchant {
let level = if wave > raid::num_groups(2) { 2 } else { 1 };
gear::upgrade(m, MAIN, "minecraft:sharpness", level);
}
}
_ => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_the_vanilla_mobs_enchant_their_spawn_gear() {
assert!(enchants_spawn_gear(Species::Skeleton));
assert!(enchants_spawn_gear(Species::Pillager));
assert!(!enchants_spawn_gear(Species::WitherSkeleton));
assert!(!enchants_spawn_gear(Species::PiglinBrute));
assert!(!enchants_spawn_gear(Species::Villager));
}
}
@@ -0,0 +1,272 @@
//! Mobs riding mobs: boarding and dismounting, keeping riders on their
//! vehicles, the jockeys that spawn mounted (chicken jockeys, spider
//! jockeys, strider jockeys, zombie horsemen) and the skeleton horse trap.
//! Saving riders under `Passengers` lives in `persist.rs`.
use super::Game;
use horizon_client::mobs::{Species, riders};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
/// `Zombie.finalizeSpawn`: a baby zombie takes a chicken one time in twenty,
/// and another one time in twenty of the rest.
const CHICKEN_JOCKEY_ODDS: f32 = 0.05;
/// The seconds a skeleton horse trap waits for a player: 15 minutes.
const TRAP_LIFETIME: i32 = 18000;
/// `SkeletonTrapGoal`: a player this close springs the trap.
const TRAP_RANGE: f64 = 10.0;
/// Ticks of invulnerability the trap's riders and horses start with.
const TRAP_INVULNERABLE: i32 = 60;
fn zombie_kind(s: Species) -> bool {
matches!(
s,
Species::Zombie | Species::Husk | Species::Drowned | Species::ZombieVillager
)
}
impl Game<'_> {
/// `Entity.startRiding` for two mobs.
pub(super) fn mount_mob(&mut self, rider: u32, vehicle: u32) {
if rider == vehicle {
return;
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == rider) {
m.extra.mount = Some(vehicle);
m.extra.passenger = true;
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == vehicle) {
m.extra.rider = Some(rider);
}
}
/// Riders sit on their vehicles (`Entity.positionRider`), and let go when
/// the vehicle dies or is gone.
pub(super) fn sync_riders(&mut self) {
let index: HashMap<u32, usize> = self
.mobs
.iter()
.enumerate()
.map(|(i, m)| (m.id, i))
.collect();
let mut riding: HashMap<u32, u32> = HashMap::new();
for i in 0..self.mobs.len() {
let Some(v) = self.mobs[i].extra.mount else {
continue;
};
let valid = self.mobs[i].alive()
&& !self.mobs[i].removed
&& index
.get(&v)
.is_some_and(|&j| self.mobs[j].alive() && !self.mobs[j].removed);
if valid {
riding.insert(v, self.mobs[i].id);
} else {
let m = &mut self.mobs[i];
m.extra.mount = None;
m.extra.passenger = false;
}
}
for m in &mut self.mobs {
m.extra.rider = riding.get(&m.id).copied();
}
// Riders of riders settle over a few passes.
for _ in 0..3 {
for i in 0..self.mobs.len() {
let Some(v) = self.mobs[i].extra.mount else {
continue;
};
let Some(&j) = index.get(&v) else { continue };
let vehicle = &self.mobs[j];
let attach = riders::passenger_attachment(vehicle);
let (pos, prev) = (vehicle.position, vehicle.previous);
let (yaw, prev_yaw) = (vehicle.yaw, vehicle.previous_yaw);
let (body, prev_body) = (vehicle.body_yaw, vehicle.previous_body_yaw);
let m = &mut self.mobs[i];
let offset = riders::vehicle_attachment(m);
m.position = riders::seat(attach, offset, pos, yaw);
m.previous = riders::seat(attach, offset, prev, prev_yaw);
m.velocity = Vec3::ZERO;
m.fall_distance = 0.0;
m.on_ground = false;
m.body_yaw = body;
m.previous_body_yaw = prev_body;
m.extra.passenger = true;
// A rider never walks off on its own.
m.ai.nav.stop();
}
}
}
/// `finalizeSpawn` jockeys of a naturally spawned mob: baby zombies on
/// chickens, skeletons on spiders, piglins and baby striders on striders,
/// zombies on zombie horses.
pub(super) fn spawn_jockeys(&mut self, id: u32, natural: bool) {
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return;
};
let (species, baby) = (m.species(), m.is_baby());
let at = [m.position.x, m.position.y, m.position.z];
match species {
s if zombie_kind(s) && baby => {
if self.world.random.next_float() < CHICKEN_JOCKEY_ODDS {
if let Some(chicken) = self.free_chicken_near(at) {
self.make_chicken_jockey(chicken);
self.mount_mob(id, chicken);
}
} else if self.world.random.next_float() < CHICKEN_JOCKEY_ODDS
&& let Some(chicken) = self.spawn_mob("minecraft:chicken", at, false)
{
self.make_chicken_jockey(chicken);
self.mount_mob(id, chicken);
}
}
// Spider.finalizeSpawn: one in a hundred carries a skeleton.
Species::Spider if self.world.random.next_int_bound(100).unwrap_or(1) == 0 => {
if let Some(skeleton) = self.spawn_mob("minecraft:skeleton", at, false) {
self.mount_mob(skeleton, id);
}
}
Species::Strider if !baby => self.spawn_strider_jockey(id, at),
// ZombieHorse.finalizeSpawn: a zombie with an iron spear.
Species::ZombieHorse if natural => {
if let Some(zombie) = self.spawn_mob("minecraft:zombie", at, false) {
if let Some(z) = self.mobs.iter_mut().find(|m| m.id == zombie) {
z.extra.main_hand = Some("minecraft:iron_spear".into());
}
self.mount_mob(zombie, id);
}
}
_ => {}
}
}
fn free_chicken_near(&self, at: [f64; 3]) -> Option<u32> {
self.mobs
.iter()
.find(|c| {
c.species() == Species::Chicken
&& c.alive()
&& c.extra.rider.is_none()
&& c.extra.mount.is_none()
&& (c.position.x - at[0]).abs() <= 5.3
&& (c.position.y - at[1]).abs() <= 3.0 + 1.0
&& (c.position.z - at[2]).abs() <= 5.3
})
.map(|c| c.id)
}
fn make_chicken_jockey(&mut self, chicken: u32) {
if let Some(c) = self.mobs.iter_mut().find(|m| m.id == chicken) {
c.extra.jockey = true;
}
}
/// `Strider.finalizeSpawn`: one strider in thirty carries a zombified
/// piglin holding a warped fungus on a stick (and wears a saddle), one in
/// ten of the rest a baby strider.
fn spawn_strider_jockey(&mut self, id: u32, at: [f64; 3]) {
if self.world.random.next_int_bound(30).unwrap_or(1) == 0 {
if !self.ui.rules.bool("spawn_mobs") {
return;
}
if let Some(piglin) = self.spawn_mob("minecraft:zombified_piglin", at, false) {
let baby = self.world.random.next_float() < CHICKEN_JOCKEY_ODDS;
if let Some(p) = self.mobs.iter_mut().find(|m| m.id == piglin) {
p.extra.main_hand = Some("minecraft:warped_fungus_on_a_stick".into());
p.extra.age = if baby { i32::MIN / 2 } else { 0 };
}
if let Some(s) = self.mobs.iter_mut().find(|m| m.id == id) {
s.extra.saddled = true;
}
self.mount_mob(piglin, id);
}
} else if self.world.random.next_int_bound(10).unwrap_or(1) == 0
&& let Some(baby) = self.spawn_mob("minecraft:strider", at, false)
{
if let Some(b) = self.mobs.iter_mut().find(|m| m.id == baby) {
b.extra.age = -24000;
}
self.mount_mob(baby, id);
}
}
/// `SkeletonHorse.customServerAiStep` and `SkeletonTrapGoal`: a trap
/// horse is a trap for fifteen minutes; a player within ten blocks springs
/// it.
pub(super) fn tick_skeleton_traps(&mut self) {
let player = self
.player
.as_ref()
.filter(|p| !p.health.dead_or_dying())
.map(|p| p.position);
let mut sprung = Vec::new();
for m in &mut self.mobs {
if m.species() != Species::SkeletonHorse || !m.extra.trap || !m.alive() {
continue;
}
if !m.persistent {
m.extra.trap_time += 1;
if m.extra.trap_time > TRAP_LIFETIME {
m.removed = true;
continue;
}
}
if player.is_some_and(|p| m.distance_sqr(p) < TRAP_RANGE * TRAP_RANGE) {
sprung.push(m.id);
}
}
for id in sprung {
self.spring_skeleton_trap(id);
}
}
fn spring_skeleton_trap(&mut self, id: u32) {
let Some(horse) = self.mobs.iter_mut().find(|m| m.id == id) else {
return;
};
horse.extra.trap = false;
horse.extra.tame = true;
horse.extra.age = 0;
let at = [horse.position.x, horse.position.y, horse.position.z];
self.spawn_bolt(at, true);
let Some(skeleton) = self.trap_skeleton(at) else {
return;
};
self.mount_mob(skeleton, id);
for _ in 0..3 {
let Some(other) = self.spawn_mob("minecraft:skeleton_horse", at, true) else {
continue;
};
let (dx, dz) = (
self.world.random.triangle(0.0, 1.1485),
self.world.random.triangle(0.0, 1.1485),
);
if let Some(h) = self.mobs.iter_mut().find(|m| m.id == other) {
h.invulnerable = TRAP_INVULNERABLE;
h.extra.tame = true;
h.extra.age = 0;
h.velocity = Vec3::new(h.velocity.x + dx, h.velocity.y, h.velocity.z + dz);
}
if let Some(rider) = self.trap_skeleton(at) {
self.mount_mob(rider, other);
}
}
}
/// `SkeletonTrapGoal.createSkeleton`: an iron helmet unless it already
/// has a helm.
fn trap_skeleton(&mut self, at: [f64; 3]) -> Option<u32> {
let id = self.spawn_mob("minecraft:skeleton", at, true)?;
let m = self.mobs.iter_mut().find(|m| m.id == id)?;
m.invulnerable = TRAP_INVULNERABLE;
if m.extra.head.is_none() {
m.extra.head = Some("minecraft:iron_helmet".into());
}
let (weapon, helmet) = (m.extra.main_hand.clone(), m.extra.head.clone());
let special = self.local_difficulty(at).special();
// `SkeletonTrapGoal.enchant`: the weapon and the helmet, always.
for (slot, item) in [
(horizon_client::mobs::gear::MAIN, weapon),
(horizon_client::mobs::gear::HEAD, helmet),
] {
if let Some(item) = item {
self.enchant_item(id, slot, &item, special);
}
}
Some(id)
}
}
+117 -45
View File
@@ -217,52 +217,116 @@ impl Game<'_> {
}
}
_ if self.res.mob_types.contains_key(&kind) => {
self.next_entity += 1;
// Structure entities placed with finalizeEntities.
let mut tag = tag;
let finalize = match &mut tag {
Tag::Compound(c) => c.remove(&"horizon:finalize".into()).is_some(),
_ => false,
};
if let Some(mut m) =
entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity)
{
if finalize {
let facts = self.biome_facts(
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let at = [m.position.x, m.position.y, m.position.z];
let difficulty = self.local_difficulty(at);
horizon_client::mobs::spawning::finalize(
&mut m,
&facts,
&difficulty,
);
// Cat.finalizeSpawn: black in #cats_spawn_as_black.
if m.species() == horizon_client::mobs::Species::Cat {
let p = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let black = self.structure_tag("minecraft:cats_spawn_as_black");
if self.structures_at(p).iter().any(|s| black.contains(s)) {
m.extra.variant = 10;
m.persistent = true;
}
}
}
self.remember(m.id, uuid, tag);
self.mobs.push(m);
}
self.load_mob(tag, None);
}
_ => self.persist.unknown.entry(key).or_default().push(tag),
}
}
}
}
/// A saved mob and, under `Passengers`, the mobs riding it.
fn load_mob(&mut self, tag: Tag, mount: Option<u32>) -> Option<u32> {
self.next_entity += 1;
let uuid = entity_nbt::uuid(&tag);
// Structure entities placed with finalizeEntities.
let mut tag = tag;
let mut finalize = false;
let mut riders = Vec::new();
let mut unknown = Vec::new();
if let Tag::Compound(c) = &mut tag {
finalize = c.remove(&"horizon:finalize".into()).is_some();
if let Some(Tag::List(list)) = c.remove(&"Passengers".into()) {
for p in list {
let known =
entity_nbt::kind(&p).is_some_and(|k| self.res.mob_types.contains_key(&k));
if known {
riders.push(p);
} else {
unknown.push(p);
}
}
}
if !unknown.is_empty() {
c.insert("Passengers".into(), Tag::List(unknown));
}
}
let mut m = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity)?;
m.extra.mount = mount;
m.extra.passenger = mount.is_some();
if finalize {
let facts = self.biome_facts(
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let at = [m.position.x, m.position.y, m.position.z];
let difficulty = self.local_difficulty(at);
horizon_client::mobs::spawning::finalize(&mut m, &facts, &difficulty);
// Cat.finalizeSpawn: black in #cats_spawn_as_black.
if m.species() == horizon_client::mobs::Species::Cat {
let p = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let black = self.structure_tag("minecraft:cats_spawn_as_black");
if self.structures_at(p).iter().any(|s| black.contains(s)) {
m.extra.variant = 10;
m.persistent = true;
}
}
}
let id = m.id;
self.remember(id, uuid, tag);
self.mobs.push(m);
if finalize {
self.enchant_spawn_equipment(id);
}
for rider in riders {
if let Some(r) = self.load_mob(rider, Some(id))
&& let Some(v) = self.mobs.iter_mut().find(|m| m.id == id)
{
v.extra.rider = Some(r);
}
}
Some(id)
}
/// The root of a stack of riders (`Entity.getRootVehicle`).
fn mob_root(&self, mut i: usize) -> usize {
for _ in 0..8 {
let Some(v) = self.mobs[i].extra.mount else {
break;
};
let Some(j) = self.mobs.iter().position(|m| m.id == v) else {
break;
};
i = j;
}
i
}
/// A mob's entity tag with the mobs riding it under `Passengers`.
fn mob_tree_nbt(&mut self, i: usize) -> Tag {
let id = self.mobs[i].id;
let uuid = self.uuid_for(id);
let mut tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id));
let riders: Vec<usize> = (0..self.mobs.len())
.filter(|&j| self.mobs[j].extra.mount == Some(id) && self.mobs[j].alive())
.collect();
let riders: Vec<Tag> = riders.into_iter().map(|j| self.mob_tree_nbt(j)).collect();
if let Tag::Compound(c) = &mut tag {
let mut list = match c.get(&"Passengers".into()) {
Some(Tag::List(l)) => l.clone(),
_ => Vec::new(),
};
list.extend(riders);
if list.is_empty() {
c.remove(&"Passengers".into());
} else {
c.insert("Passengers".into(), Tag::List(list));
}
}
tag
}
fn remember(&mut self, id: u32, uuid: Option<[i32; 4]>, tag: Tag) {
if let Some(u) = uuid {
self.persist.uuids.insert(id, u);
@@ -324,13 +388,16 @@ impl Game<'_> {
let mut out: HashMap<(i32, i32), Vec<Tag>> =
keys.iter().map(|k| (*k, Vec::new())).collect();
let player_uuid = self.level.player_uuid;
// A rider is saved inside its root vehicle, in the root's chunk.
let mobs: Vec<usize> = (0..self.mobs.len())
.filter(|&i| keys.contains(&chunk_of(self.mobs[i].position)) && self.mobs[i].alive())
.filter(|&i| {
self.mob_root(i) == i
&& keys.contains(&chunk_of(self.mobs[i].position))
&& self.mobs[i].alive()
})
.collect();
for i in mobs {
let id = self.mobs[i].id;
let uuid = self.uuid_for(id);
let tag = entity_nbt::mob_to_nbt(&self.mobs[i], uuid, self.persist.raw.get(&id));
let tag = self.mob_tree_nbt(i);
out.entry(chunk_of(self.mobs[i].position))
.or_default()
.push(tag);
@@ -520,8 +587,13 @@ impl Game<'_> {
}
keep
});
// Riders leave with their root vehicle.
let leaving: HashSet<u32> = (0..self.mobs.len())
.filter(|&i| gone(self.mobs[self.mob_root(i)].position))
.map(|i| self.mobs[i].id)
.collect();
self.mobs.retain(|m| {
let keep = !gone(m.position);
let keep = !leaving.contains(&m.id);
if !keep {
removed.push(m.id);
}
+3 -88
View File
@@ -424,13 +424,7 @@ impl Game<'_> {
if let Some(kind) = sp.rider
&& let Some(rider) = self.spawn_raider(kind, pos, raid_id, wave, false, odds)
{
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == rider) {
raider::state_mut(m).vehicle = Some(id);
m.extra.passenger = true;
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
raider::state_mut(m).rider = true;
}
self.mount_mob(rider, id);
}
}
}
@@ -462,33 +456,7 @@ impl Game<'_> {
s.ticks_outside_raid = 0;
s.active_raid = true;
m.on_ground = true;
// applyRaidBuffs: Quick Charge crossbows and Sharpness axes.
let enchant = m.random.next_float() <= odds;
match kind {
RaiderType::Pillager if enchant => {
raider::state_mut(m).enchant = if wave > raid::num_groups(2) {
2
} else if wave > raid::num_groups(1) {
1
} else {
0
};
}
RaiderType::Vindicator => {
let level = if !enchant {
0
} else if wave > raid::num_groups(2) {
2
} else {
1
};
raider::state_mut(m).enchant = level;
if level > 0 {
m.attrs.attack_damage += 1.0 + 0.5 * f32::from(level - 1);
}
}
_ => {}
}
self.apply_raid_buffs(id, kind, wave, odds);
Some(id)
}
@@ -515,7 +483,7 @@ impl Game<'_> {
if let (Some(id), true) = (s.raid_id, s.patrol_leader) {
leaders.insert((id, s.wave));
}
if let Some(v) = s.vehicle {
if let Some(v) = m.extra.mount {
ridden.insert(v);
}
positions.push((m.id, m.position, s.active_raid));
@@ -732,59 +700,6 @@ impl Game<'_> {
.map(|(id, (_, v))| (*id, v.clone()))
.collect()
}
/// A raider riding a ravager sits on its back (`Entity.positionRider`
/// with the ravager's passenger attachment and a 0.6 riding offset).
pub(super) fn sync_riders(&mut self) {
let vehicles: HashMap<u32, (Vec3, Vec3, f32, f32, bool)> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Ravager)
.map(|m| {
(
m.id,
(
m.position,
m.previous,
m.body_yaw,
m.previous_body_yaw,
m.alive(),
),
)
})
.collect();
for m in &mut self.mobs {
let Some(v) = raider::state(m).and_then(|s| s.vehicle) else {
continue;
};
match vehicles.get(&v) {
Some(&(pos, prev, yaw, prev_yaw, true)) => {
let place = |p: Vec3, yaw: f32| {
let a = f64::from(yaw).to_radians();
// The attachment's z offset of -0.0625, rotated.
Vec3::new(
p.x + a.sin() * -0.0625,
p.y + 2.2625 - 0.6,
p.z - a.cos() * -0.0625,
)
};
m.position = place(pos, yaw);
m.previous = place(prev, prev_yaw);
m.velocity = Vec3::ZERO;
m.fall_distance = 0.0;
m.on_ground = false;
m.body_yaw = yaw;
m.previous_body_yaw = prev_yaw;
m.extra.passenger = true;
// Raiders on a ravager never walk off on their own.
m.ai.nav.stop();
}
_ => {
raider::state_mut(m).vehicle = None;
m.extra.passenger = false;
}
}
}
}
/// `Raider.die`: the killing player becomes a hero of the village.
pub(super) fn raider_died(&mut self, m: &Mob, by_player: bool) {
let Some(id) = raider::state(m).and_then(|s| s.raid_id) else {
+17
View File
@@ -17,6 +17,7 @@ pub mod data;
pub mod enderman;
pub mod equine;
pub mod farm;
pub mod gear;
pub mod goals;
pub mod golem;
pub mod guardian;
@@ -32,6 +33,7 @@ pub mod piglin;
pub mod raider;
pub mod ravager;
pub mod render;
pub mod riders;
pub mod shulker;
pub mod spawning;
pub mod species;
@@ -482,6 +484,16 @@ pub struct Extra {
pub raider: Option<Box<raider::State>>,
/// A villager's raid activity and gossip.
pub villager: Option<Box<villager::Ext>>,
/// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`).
pub mount: Option<u32>,
pub rider: Option<u32>,
/// A chicken carrying a zombie (`IsChickenJockey`).
pub jockey: bool,
/// A skeleton horse waiting to spring its trap, and how long it has waited.
pub trap: bool,
pub trap_time: i32,
/// Enchantments on the equipment above.
pub gear: Option<Box<gear::Gear>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -946,6 +958,11 @@ impl Mob {
let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
amount *= 1.0 - effective / 25.0;
}
// CombatRules.getDamageAfterMagicAbsorb: enchantment protection.
let epf = gear::protection(self, source.kind);
if epf > 0.0 {
amount *= 1.0 - epf / 25.0;
}
let mut knock = true;
if self.invulnerable as f32 > 10.0 {
if amount <= self.last_hurt {
+38 -2
View File
@@ -508,6 +508,7 @@ fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
super::equine::ridden_step(m);
return;
}
super::riders::drive(m, w);
let tick_count = m.age as i64;
let id_based = tick_count + i64::from(m.id);
let mut targets = std::mem::take(&mut m.ai.targets);
@@ -598,14 +599,18 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
/// Mob.checkDespawn (players are the only despawn reference).
fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
let creature = m.kind.category == "creature";
if m.persistent || creature && m.kind.flags.animal {
// A jockey's chicken despawns like a monster (`Chicken.removeWhenFarAway`).
if m.persistent || creature && m.kind.flags.animal && !m.extra.jockey {
m.ai.no_action_time = 0;
return true;
}
let Some(p) = &w.player else { return true };
let d = m.distance_sqr(p.position);
// Patrols and raiders (`removeWhenFarAway`, `requiresCustomPersistence`).
if super::raider::keeps_alive(m, d) || super::zombie_villager::keeps_alive(m) {
if super::raider::keeps_alive(m, d)
|| super::zombie_villager::keeps_alive(m)
|| super::riders::keeps_alive(m)
{
return true;
}
let despawn = if m.kind.category == "water_ambient" {
@@ -757,6 +762,37 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if amount <= 0.0 {
amount = 1.0;
}
// The held weapon's enchantments: Sharpness, Smite, Bane of Arthropods,
// Fire Aspect and Knockback.
let target_species = match who {
Who::Mob(id) => cx.w.seen(id).map(|s| s.species),
Who::Player => None,
};
amount += super::gear::melee_bonus(m, target_species);
let burn = super::gear::fire_aspect(m);
if burn > 0 {
cx.events.push(MobEvent::Ignite {
target: who,
seconds: burn,
});
}
let knock = super::gear::knockback(m);
if knock > 0 {
let (dx, dz) = match who {
Who::Player => cx.w.player.as_ref().map_or((0.0, 0.0), |p| {
(p.position.x - m.position.x, p.position.z - m.position.z)
}),
Who::Mob(id) => cx.w.seen(id).map_or((0.0, 0.0), |s| {
(s.position.x - m.position.x, s.position.z - m.position.z)
}),
};
let len = (dx * dx + dz * dz).sqrt().max(1e-5);
let k = f64::from(knock) * 0.5;
cx.events.push(MobEvent::Push {
target: who,
velocity: [dx / len * k, 0.1, dz / len * k],
});
}
// Zombies set their target on fire while burning (Zombie.doHurtTarget).
if m.fire_ticks > 0 && matches!(m.species(), Species::Zombie) && m.random.next_float() < 0.3 {
cx.events.push(MobEvent::Ignite {
+1 -1
View File
@@ -81,7 +81,7 @@ pub fn chicken_ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
m.velocity.y *= 0.6;
}
a.flap += a.flapping * 2.0;
if m.alive() && !m.is_baby() {
if m.alive() && !m.is_baby() && !m.extra.jockey {
m.extra.egg_time -= 1;
if m.extra.egg_time <= 0 {
let pitch = (m.random.next_float() - m.random.next_float()) * 0.2 + 1.0;
+228
View File
@@ -0,0 +1,228 @@
//! Enchantments on the gear mobs wear and hold (`Mob.populateDefaultEquipmentEnchantments`,
//! raid buffs): the side table kept beside the plain item ids in `Extra`,
//! its saved form, and the combat numbers the enchantments give (Sharpness,
//! Smite, Bane of Arthropods, Fire Aspect, Knockback, Power, Punch, Flame,
//! Quick Charge and the protections).
use super::{DamageKind, Mob, Species};
use std::sync::Arc;
/// Equipment slots in the order `Extra` keeps them.
pub const MAIN: usize = 0;
pub const OFF: usize = 1;
pub const HEAD: usize = 2;
pub const CHEST: usize = 3;
pub const LEGS: usize = 4;
pub const FEET: usize = 5;
pub const ARMOR: [usize; 4] = [HEAD, CHEST, LEGS, FEET];
/// The `equipment` keys of each slot.
pub const KEYS: [&str; 6] = ["mainhand", "offhand", "head", "chest", "legs", "feet"];
pub type Levels = Vec<(Arc<str>, u32)>;
/// The enchantments of each equipment slot.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gear {
pub slots: [Levels; 6],
}
impl Gear {
pub fn is_empty(&self) -> bool {
self.slots.iter().all(Vec::is_empty)
}
pub fn level(&self, slot: usize, id: &str) -> u32 {
self.slots[slot]
.iter()
.find(|(e, _)| &**e == id)
.map_or(0, |(_, l)| *l)
}
/// `ItemEnchantments.Mutable.upgrade`: keep the higher level.
pub fn upgrade(&mut self, slot: usize, id: &str, level: u32) {
match self.slots[slot].iter_mut().find(|(e, _)| &**e == id) {
Some((_, l)) => *l = (*l).max(level),
None => self.slots[slot].push((Arc::from(id), level)),
}
}
}
pub fn gear(m: &Mob) -> Option<&Gear> {
m.extra.gear.as_deref()
}
/// The level of an enchantment on what `m` wears or holds in `slot`.
pub fn level(m: &Mob, slot: usize, id: &str) -> u32 {
gear(m).map_or(0, |g| g.level(slot, id))
}
/// Whether the item in `slot` is enchanted (the glint).
pub fn enchanted(m: &Mob, slot: usize) -> bool {
gear(m).is_some_and(|g| !g.slots[slot].is_empty())
}
/// Replace the enchantments of a slot; an empty list removes them.
pub fn set(m: &mut Mob, slot: usize, levels: Levels) {
let g = m.extra.gear.get_or_insert_with(Box::default);
g.slots[slot] = levels;
if g.is_empty() {
m.extra.gear = None;
}
}
pub fn upgrade(m: &mut Mob, slot: usize, id: &str, level: u32) {
m.extra
.gear
.get_or_insert_with(Box::default)
.upgrade(slot, id, level);
}
/// `#sensitive_to_smite` and `#sensitive_to_bane_of_arthropods`.
fn undead(s: Species) -> bool {
matches!(
s,
Species::Zombie
| Species::Husk
| Species::Drowned
| Species::ZombieVillager
| Species::ZombifiedPiglin
| Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::Parched
| Species::WitherSkeleton
| Species::Wither
| Species::Phantom
| Species::Zoglin
| Species::SkeletonHorse
| Species::ZombieHorse
)
}
fn arthropod(s: Species) -> bool {
matches!(
s,
Species::Spider
| Species::CaveSpider
| Species::Silverfish
| Species::Endermite
| Species::Bee
)
}
/// The `minecraft:damage` bonus of a weapon's levels against `target`.
pub fn damage_bonus(levels: &[(Arc<str>, u32)], target: Option<Species>) -> f32 {
let mut bonus = 0.0;
for (id, l) in levels {
let l = *l as f32;
match &**id {
"minecraft:sharpness" => bonus += 1.0 + 0.5 * (l - 1.0),
"minecraft:smite" if target.is_some_and(undead) => bonus += 2.5 * l,
"minecraft:bane_of_arthropods" if target.is_some_and(arthropod) => bonus += 2.5 * l,
_ => {}
}
}
bonus
}
/// The extra damage of the mob's held weapon against a target species.
pub fn melee_bonus(m: &Mob, target: Option<Species>) -> f32 {
gear(m).map_or(0.0, |g| damage_bonus(&g.slots[MAIN], target))
}
/// Seconds of fire a melee hit sets (`Fire Aspect`: 4 per level).
pub fn fire_aspect(m: &Mob) -> i32 {
4 * level(m, MAIN, "minecraft:fire_aspect") as i32
}
/// `minecraft:knockback` of the held weapon.
pub fn knockback(m: &Mob) -> u32 {
level(m, MAIN, "minecraft:knockback")
}
/// What a bow adds to its arrows.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ArrowBonus {
/// Power: 1 + 0.5 per level above the first.
pub damage: f32,
/// Punch: knockback levels.
pub punch: u32,
/// Flame: sets the target on fire.
pub flame: bool,
/// Piercing: entities an arrow passes through.
pub pierce: u32,
}
pub fn arrow_bonus(m: &Mob) -> ArrowBonus {
let power = level(m, MAIN, "minecraft:power");
ArrowBonus {
damage: if power > 0 {
1.0 + 0.5 * (power as f32 - 1.0)
} else {
0.0
},
punch: level(m, MAIN, "minecraft:punch"),
flame: level(m, MAIN, "minecraft:flame") > 0,
pierce: level(m, MAIN, "minecraft:piercing"),
}
}
/// Enchantment protection points of the worn armour against a damage kind
/// (`damage_protection`: 1 per level of Protection, 2 for the specialist
/// ones, 3 for Feather Falling), capped at 20.
pub fn protection(m: &Mob, kind: DamageKind) -> f32 {
let Some(g) = gear(m) else { return 0.0 };
protection_points(g, kind).min(20.0)
}
pub fn protection_points(g: &Gear, kind: DamageKind) -> f32 {
if kind == DamageKind::Generic {
return 0.0;
}
let fire = matches!(
kind,
DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava | DamageKind::Fireball
);
let projectile = matches!(
kind,
DamageKind::Arrow | DamageKind::Thrown | DamageKind::Fireball
);
let mut total = 0.0;
for slot in ARMOR {
for (id, l) in &g.slots[slot] {
let l = *l as f32;
total += match &**id {
"minecraft:protection" => l,
"minecraft:fire_protection" if fire => 2.0 * l,
"minecraft:blast_protection" if kind == DamageKind::Explosion => 2.0 * l,
"minecraft:projectile_protection" if projectile => 2.0 * l,
"minecraft:feather_falling" if kind == DamageKind::Fall => 3.0 * l,
_ => 0.0,
};
}
}
total
}
#[cfg(test)]
mod tests {
use super::*;
fn levels(list: &[(&str, u32)]) -> Levels {
list.iter().map(|(e, l)| (Arc::from(*e), *l)).collect()
}
#[test]
fn sharpness_adds_half_a_heart_per_level_above_one() {
let s = levels(&[("minecraft:sharpness", 3)]);
assert_eq!(damage_bonus(&s, Some(Species::Cow)), 2.0);
}
#[test]
fn smite_and_bane_need_the_right_target() {
let l = levels(&[("minecraft:smite", 2), ("minecraft:bane_of_arthropods", 1)]);
assert_eq!(damage_bonus(&l, Some(Species::Zombie)), 5.0);
assert_eq!(damage_bonus(&l, Some(Species::Spider)), 2.5);
assert_eq!(damage_bonus(&l, None), 0.0);
}
#[test]
fn protections_count_by_damage_kind() {
let mut g = Gear::default();
g.upgrade(HEAD, "minecraft:protection", 4);
g.upgrade(FEET, "minecraft:feather_falling", 4);
g.upgrade(CHEST, "minecraft:fire_protection", 2);
assert_eq!(protection_points(&g, DamageKind::MobAttack), 4.0);
assert_eq!(protection_points(&g, DamageKind::Fall), 16.0);
assert_eq!(protection_points(&g, DamageKind::OnFire), 8.0);
assert_eq!(protection_points(&g, DamageKind::Generic), 0.0);
}
#[test]
fn upgrading_keeps_the_higher_level() {
let mut g = Gear::default();
g.upgrade(MAIN, "minecraft:power", 2);
g.upgrade(MAIN, "minecraft:power", 1);
assert_eq!(g.level(MAIN, "minecraft:power"), 2);
assert!(!g.is_empty());
}
}
+2 -1
View File
@@ -386,7 +386,7 @@ pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal {
}
/// `CrossbowItem.getChargeDuration` (25 ticks, 5 fewer per level of Quick Charge).
pub fn charge_ticks(m: &Mob) -> i32 {
25 - 5 * i32::from(super::raider::state(m).map_or(0, |s| s.enchant))
25 - 5 * super::gear::level(m, super::gear::MAIN, "minecraft:quick_charge") as i32
}
fn holding_crossbow(m: &Mob) -> bool {
m.extra.main_hand.as_deref() == Some("minecraft:crossbow")
@@ -521,6 +521,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
start,
Some(Who::Mob(m.id)),
);
p.bonus = super::gear::arrow_bonus(m);
// rangedAttackUncertainty at normal difficulty: 14 - 2 * 4.
p.shoot(&mut m.random, [dx, dy, dz], 1.6, 6.0);
cx.events.push(MobEvent::Projectile(p));
+1 -5
View File
@@ -40,12 +40,8 @@ pub struct State {
pub banner_at: Option<[f64; 3]>,
/// Beds around the raid's centre.
pub homes: Option<std::sync::Arc<Vec<[i32; 3]>>>,
/// The ravager this raider rides, and (for a ravager) that it carries one.
pub vehicle: Option<u32>,
/// A ravager carrying a raider, set every tick from `Extra::rider`.
pub rider: bool,
/// Quick Charge (pillager crossbows) or Sharpness (vindicator axes) from
/// the raid's enchanting.
pub enchant: u8,
}
impl State {
/// A ravager carrying a raider (`hasControllingPassenger`).
+134 -29
View File
@@ -802,9 +802,28 @@ pub fn render_with(
} else {
light
};
let overlay = if armor_slot(&layer.model).is_some_and(|s| super::gear::enchanted(m, s)) {
glint_overlay(overlay)
} else {
overlay
};
draw(&part, base, &poses, uv, layer.color, light, overlay, out);
}
}
/// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`).
fn armor_slot(model: &str) -> Option<usize> {
Some(match model.rsplit('#').next()? {
"helmet" => super::gear::HEAD,
"chestplate" => super::gear::CHEST,
"leggings" => super::gear::LEGS,
"boots" => super::gear::FEET,
_ => return None,
})
}
/// The entity shader's glint overlay (7), keeping the hurt tint (8).
fn glint_overlay(overlay: u32) -> u32 {
if overlay == 1 { 8 } else { 7 }
}
/// Render with a fixed texture rect (the earlier API).
pub fn render_single(
m: &Mob,
@@ -903,6 +922,100 @@ fn item_sprite(m: &Mob, item: &str) -> String {
}
format!("item/{name}")
}
/// The hand of a mob in model space, up to the item's own transform
/// (`ItemInHandLayer.submitArmWithItem`).
fn hand_base(
m: &Mob,
model: &Part,
base: glam::Mat4,
poses: &Poses,
left: bool,
) -> Option<glam::Mat4> {
let skeleton = matches!(
m.species(),
Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::Parched
| Species::WitherSkeleton
);
let arm = if left { "left_arm" } else { "right_arm" };
let offset = if skeleton {
if left { -1.0 } else { 1.0 }
} else {
0.0
};
let mut t = part_matrix(model, base, poses, arm, offset)?;
let (ox, oy, oz) = if m.is_baby() {
(0.0, 1.0, -4.5)
} else {
(1.0, 2.0, -10.0)
};
t *= glam::Mat4::from_rotation_x((-90.0f32).to_radians()) * glam::Mat4::from_rotation_y(PI);
t *= glam::Mat4::from_translation(glam::Vec3::new(
if left { -ox } else { ox } / 16.0,
oy / 16.0,
oz / 16.0,
));
Some(t)
}
/// The transform of one of a mob's model parts, in camera space
/// (`ModelPart.translateAndRotate` down the tree).
pub fn part_transform(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
data: &MobData,
part: &str,
) -> Option<glam::Mat4> {
let base = base_transform(m, alpha, camera);
let s = anim::state(m, alpha);
let (model_key, _) = body(m);
let model = m
.kind
.layer(&model_key)
.cloned()
.unwrap_or_else(|| m.kind.model.clone());
let mut poses = Poses::new(&model);
anim::setup(m, &s, &mut poses, &data.animations);
part_matrix(&model, base, &poses, part, 0.0)
}
/// Where a mob holds a block item (`block/block` thirdperson display: turned
/// 75 and 45 degrees, at 0.375 scale), as the hand transform for `left`, or
/// `None` when the mob shows no held items.
pub fn held_block_transform(
m: &Mob,
alpha: f32,
camera: glam::DVec3,
data: &MobData,
left: bool,
) -> Option<glam::Mat4> {
if !super::illager::shows_item(m) {
return None;
}
let base = base_transform(m, alpha, camera);
let s = anim::state(m, alpha);
let (model_key, _) = body(m);
let model = m
.kind
.layer(&model_key)
.cloned()
.unwrap_or_else(|| m.kind.model.clone());
let mut poses = Poses::new(&model);
anim::setup(m, &s, &mut poses, &data.animations);
let mut t = hand_base(m, &model, base, &poses, left)?;
let ry = if left { -45.0f32 } else { 45.0 };
t *= glam::Mat4::from_translation(glam::Vec3::new(0.0, 2.5, 0.0) / 16.0);
t *= glam::Mat4::from_quat(glam::Quat::from_euler(
glam::EulerRot::XYZ,
75.0f32.to_radians(),
ry.to_radians(),
0.0,
));
t *= glam::Mat4::from_scale(glam::Vec3::splat(0.375));
t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
Some(t)
}
/// ItemInHandLayer: items in the mob's hands.
fn held_items(
m: &Mob,
@@ -913,43 +1026,17 @@ fn held_items(
light: u32,
out: &mut Vec<Vertex>,
) {
let skeleton = matches!(
m.species(),
Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::Parched
| Species::WitherSkeleton
);
if !super::illager::shows_item(m) {
return;
}
for (item, left) in [(&m.extra.main_hand, false), (&m.extra.off_hand, true)] {
let Some(item) = item else { continue };
let arm = if left { "left_arm" } else { "right_arm" };
let offset = if skeleton {
if left { -1.0 } else { 1.0 }
} else {
0.0
};
let Some(mut t) = part_matrix(model, base, poses, arm, offset) else {
let Some(mut t) = hand_base(m, model, base, poses, left) else {
continue;
};
let Some(uv) = atlas(&item_sprite(m, item)) else {
continue;
};
let baby = m.is_baby();
let (ox, oy, oz) = if baby {
(0.0, 1.0, -4.5)
} else {
(1.0, 2.0, -10.0)
};
t *= glam::Mat4::from_rotation_x((-90.0f32).to_radians()) * glam::Mat4::from_rotation_y(PI);
t *= glam::Mat4::from_translation(glam::Vec3::new(
if left { -ox } else { ox } / 16.0,
oy / 16.0,
oz / 16.0,
));
// ItemTransform.apply (mirrored for the left hand).
let (rot, tr, sc) = item_display(item);
let (ry, rz, tx) = if left {
@@ -966,11 +1053,29 @@ fn held_items(
));
t *= glam::Mat4::from_scale(glam::Vec3::from(sc));
t *= glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
draw_item_plane(t, uv, light, out);
let glint = super::gear::enchanted(
m,
if left {
super::gear::OFF
} else {
super::gear::MAIN
},
);
draw_item_plane_with(t, uv, light, if glint { 7 } else { 0 }, out);
}
}
/// A generated item model: the sprite on two faces 1/16 apart.
pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec<Vertex>) {
draw_item_plane_with(t, uv, light, 0, out);
}
/// `draw_item_plane` with an entity shader overlay (7: enchantment glint).
pub fn draw_item_plane_with(
t: glam::Mat4,
uv: [f32; 4],
light: u32,
overlay: u32,
out: &mut Vec<Vertex>,
) {
let (u0, v0, u1, v1) = (uv[0], uv[1], uv[2], uv[3]);
let south = 8.5 / 16.0;
let north = 7.5 / 16.0;
@@ -994,7 +1099,7 @@ pub fn draw_item_plane(t: glam::Mat4, uv: [f32; 4], light: u32, out: &mut Vec<Ve
out.push(Vertex {
pos: pos.to_array(),
uv,
layer: 0,
layer: overlay,
color: 0xFFFF_FFFF,
light,
});
+166
View File
@@ -0,0 +1,166 @@
//! Mobs riding mobs (`Entity.getPassengers`): where a rider sits on its
//! vehicle (`EntityAttachments`), the rider steering the vehicle toward its
//! target (`Mob.getControllingPassenger`, whose navigation and move control
//! the rider's goals use), and the saved jockey fields. The game links the
//! two (`game/passengers.rs`) and spawns the jockeys.
use super::{
Mob, MobWorld, Species,
goals::{JUMP, LOOK, MOVE},
};
use horizon_core::geometry::Vec3;
use horizon_world::nbt::{Compound, Tag};
/// The goal flags a controlling passenger takes from its vehicle.
const CONTROLLED: u8 = MOVE | JUMP | LOOK;
/// `EntityType` passenger attachment of a vehicle (before rotation): where a
/// rider's attachment point sits relative to the vehicle's feet.
pub fn passenger_attachment(v: &Mob) -> [f64; 3] {
match v.species() {
Species::Chicken => [0.0, 0.7, -0.1],
Species::Spider => [0.0, 0.765, 0.0],
Species::Ravager => [0.0, 2.2625, -0.0625],
Species::Horse => [0.0, 1.44375, 0.0],
Species::Donkey => [0.0, 1.1125, 0.0],
Species::Mule => [0.0, 1.2125, 0.0],
Species::SkeletonHorse | Species::ZombieHorse => [0.0, 1.31875, 0.0],
Species::Pig => [0.0, 0.86875, 0.0],
// The default attachments: the top of the bounding box.
_ => [0.0, f64::from(v.height()), 0.0],
}
}
/// The rider's own `VEHICLE` attachment height (`ridingOffset`): how far
/// below the vehicle's attachment point its feet hang.
pub fn vehicle_attachment(r: &Mob) -> f64 {
use Species as S;
match r.species() {
S::Zombie | S::Husk | S::Drowned if r.is_baby() => 0.1875,
S::ZombieVillager if r.is_baby() => 0.125,
S::Zombie
| S::Husk
| S::Drowned
| S::ZombieVillager
| S::ZombifiedPiglin
| S::Piglin
| S::PiglinBrute
| S::Skeleton
| S::Stray
| S::Bogged
| S::Parched
| S::WitherSkeleton => 0.7,
S::Pillager | S::Vindicator | S::Evoker => 0.6,
_ => 0.0,
}
}
/// `Vec3.yRot(-yaw)` of an attachment point.
fn rotated([x, y, z]: [f64; 3], yaw: f32) -> [f64; 3] {
let a = -f64::from(yaw).to_radians();
let (sin, cos) = (a.sin(), a.cos());
[x * cos + z * sin, y, z * cos - x * sin]
}
/// `Entity.positionRider`: the vehicle's position plus its rotated passenger
/// attachment, less the rider's own vehicle attachment.
pub fn seat(attachment: [f64; 3], rider_offset: f64, at: Vec3, yaw: f32) -> Vec3 {
let [x, y, z] = rotated(attachment, yaw);
Vec3::new(at.x + x, at.y + y - rider_offset, at.z + z)
}
/// Ranged riders keep this far from their target instead of closing in.
const RANGED_DISTANCE: f64 = 8.0;
fn ranged(s: Species) -> bool {
matches!(
s,
Species::Skeleton
| Species::Stray
| Species::Bogged
| Species::Parched
| Species::Pillager
| Species::Witch
| Species::Piglin
)
}
/// A mob rider steers: while it has a target, its vehicle gives up its own
/// movement goals and carries it toward the target (melee riders to contact,
/// archers to a shooting distance). Without a target the vehicle wanders.
pub fn drive(m: &mut Mob, w: &MobWorld) {
let Some(rider) = m.extra.rider else {
m.ai.goals.disabled &= !CONTROLLED;
return;
};
let seen = w.seen(rider).filter(|s| s.alive);
let info = seen
.and_then(|s| s.target)
.and_then(|t| w.target_info(t))
.filter(|t| t.alive && !(t.is_player && t.creative));
let (Some(seen), Some(t)) = (seen, info) else {
m.ai.goals.disabled &= !CONTROLLED;
return;
};
m.ai.goals.disabled |= CONTROLLED;
m.look_at_speed([t.position.x, t.eye_y, t.position.z], 30.0, 30.0);
let close =
ranged(seen.species) && m.distance_sqr(t.position) < RANGED_DISTANCE * RANGED_DISTANCE;
if close {
m.nav_stop();
} else if m.ai.nav.is_done() || (m.age + m.id).is_multiple_of(10) {
m.nav_move_to_entity(w, [t.position.x, t.position.y, t.position.z], 0, 1.0);
}
}
/// `Mob.requiresCustomPersistence`: a passenger never despawns.
pub fn keeps_alive(m: &Mob) -> bool {
m.extra.mount.is_some()
}
/// `IsChickenJockey`, `SkeletonTrap` and `SkeletonTrapTime`.
pub fn write_nbt(m: &Mob, map: &mut Compound) {
match m.species() {
Species::Chicken => {
map.insert(
"IsChickenJockey".into(),
Tag::Byte(i8::from(m.extra.jockey)),
);
}
Species::SkeletonHorse => {
map.insert("SkeletonTrap".into(), Tag::Byte(i8::from(m.extra.trap)));
map.insert("SkeletonTrapTime".into(), Tag::Int(m.extra.trap_time));
}
_ => {}
}
}
pub fn read_nbt(m: &mut Mob, tag: &Tag) {
let int = |key: &str| match tag.get(key) {
Some(Tag::Int(v)) => *v,
Some(Tag::Byte(v)) => i32::from(*v),
Some(Tag::Short(v)) => i32::from(*v),
_ => 0,
};
match m.species() {
Species::Chicken => m.extra.jockey = int("IsChickenJockey") != 0,
Species::SkeletonHorse => {
m.extra.trap = int("SkeletonTrap") != 0;
m.extra.trap_time = int("SkeletonTrapTime");
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn attachments_turn_with_the_vehicle() {
// A ravager's seat sits a sixteenth behind its centre.
let behind = [0.0, 2.2625, -0.0625];
let [x, y, z] = rotated(behind, 0.0);
assert!(x.abs() < 1e-9 && (z + 0.0625).abs() < 1e-9 && y == 2.2625);
// Facing west (yaw 90), behind is to the east.
let [x, _, z] = rotated(behind, 90.0);
assert!((x - 0.0625).abs() < 1e-9 && z.abs() < 1e-9);
}
#[test]
fn archers_keep_their_distance_and_brawlers_close_in() {
assert!(ranged(Species::Skeleton) && ranged(Species::Pillager));
assert!(!ranged(Species::Zombie) && !ranged(Species::Vindicator));
}
}
+1
View File
@@ -417,6 +417,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) {
start,
Some(Who::Mob(m.id)),
);
p.bonus = super::gear::arrow_bonus(m);
p.shoot(
&mut m.random,
[xd, yd + dist * 0.2, zd],
+3
View File
@@ -59,6 +59,8 @@ pub struct Projectile {
pub stuck: bool,
/// Whether the projectile has left its owner's box (Projectile.leftOwner).
pub left_owner: bool,
/// The shooter's bow enchantments (Power, Punch, Flame, Piercing).
pub bonus: crate::mobs::gear::ArrowBonus,
}
/// What a projectile struck this tick.
#[derive(Clone, Copy, Debug, PartialEq)]
@@ -118,6 +120,7 @@ impl Projectile {
age: 0,
stuck: false,
left_owner: false,
bonus: Default::default(),
}
}
pub fn is_arrow(&self) -> bool {