Add local difficulty and mob armour

Chunks gain inhabited time while a player is near (saved as
InhabitedTime), giving vanilla's local difficulty. Zombies, husks,
zombie villagers and skeletons spawn with armour sets by it, piglins with
golden pieces; worn armour protects them, is drawn with the humanoid
armour layers, drops 8.5% of the time and is saved. Zombie, drowned and
zombified piglin weapon odds now follow 26.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 11:31:25 +02:00
parent 78165ecdf6
commit f36b317569
7 changed files with 314 additions and 19 deletions
+11
View File
@@ -372,6 +372,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (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),
] {
match item {
Some(id) => {
@@ -432,6 +436,13 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
.get("offhand")
.and_then(|i| text(i.get("id")))
.map(Into::into);
if !crate::mobs::equine::is_equine(m.species()) {
let slot = |key| eq.get(key).and_then(|i| text(i.get("id"))).map(Into::into);
m.extra.head = slot("head");
m.extra.chest = slot("chest");
m.extra.legs = slot("legs");
m.extra.feet = slot("feet");
}
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
+55 -4
View File
@@ -206,7 +206,8 @@ impl Game<'_> {
at[1].floor() as i32,
at[2].floor() as i32,
);
spawning::finalize(&mut mob, &facts);
let difficulty = self.local_difficulty(at);
spawning::finalize(&mut mob, &facts, &difficulty);
let id = mob.id;
self.mobs.push(mob);
Some(id)
@@ -388,6 +389,46 @@ impl Game<'_> {
mob_griefing: self.ui.rules.bool("mob_griefing"),
}
}
/// `ServerLevel.getCurrentDifficultyAt`.
pub(super) fn local_difficulty(&self, at: [f64; 3]) -> spawning::LocalDifficulty {
use horizon_world::food::Difficulty;
let base = match self.world.health_rules.difficulty {
Difficulty::Peaceful => 0,
Difficulty::Easy => 1,
Difficulty::Normal => 2,
Difficulty::Hard => 3,
};
let key = ((at[0].floor() as i32) >> 4, (at[2].floor() as i32) >> 4);
let (inhabited, moon) = if self.world.chunks.contains_key(&key) {
let phase = self.world.day_time.div_euclid(24000).rem_euclid(8) as usize;
(
self.world.inhabited.get(&key).copied().unwrap_or(0),
spawning::MOON_BRIGHTNESS[phase],
)
} else {
(0, 0.0)
};
spawning::LocalDifficulty::new(base, self.world.day_time, inhabited, moon)
}
/// `ServerChunkCache.tickSpawningChunk`: chunks whose centre is within
/// 128 blocks of the player gain inhabited time.
fn tick_inhabited(&mut self) {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
return;
};
let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4);
for dx in -8..=8 {
for dz in -8..=8 {
let key = (pcx + dx, pcz + dz);
let (cx, cz) = (f64::from(key.0 * 16 + 8), f64::from(key.1 * 16 + 8));
if (cx - p.x).powi(2) + (cz - p.z).powi(2) < 128.0 * 128.0
&& self.world.chunks.contains_key(&key)
{
*self.world.inhabited.entry(key).or_insert(0) += 1;
}
}
}
}
/// NaturalSpawner.spawnForChunk over the chunks within 8 of the player.
fn spawn_natural(&mut self) {
let Some(p) = self.player.as_ref().map(|p| p.position) else {
@@ -559,6 +600,7 @@ impl Game<'_> {
}
self.spawn_generation_creatures(key.0, key.1);
}
self.tick_inhabited();
self.spawn_natural();
let snapshot: Vec<Seen> = self.mobs.iter().map(seen).collect();
let mut events = Vec::new();
@@ -646,11 +688,20 @@ impl Game<'_> {
for item in gear {
self.spawn_item(ItemStack::new(item, 1), pos, [0.0, 0.2, 0.0], 10);
}
{
let item = &m.extra.main_hand;
let worn = if horizon_client::mobs::equine::is_equine(m.species()) {
[None, None, None, None]
} else {
[
m.extra.head.clone(),
m.extra.chest.clone(),
m.extra.legs.clone(),
m.extra.feet.clone(),
]
};
for item in std::iter::once(m.extra.main_hand.clone()).chain(worn) {
// Equipment drop chance 8.5% (+ player kill only).
// Vexes never drop their sword.
if let Some(item) = item
if let Some(item) = &item
&& by_player
&& m.species() != Species::Vex
&& self.world.random.next_float() < 0.085
+19 -1
View File
@@ -56,6 +56,11 @@ impl Game<'_> {
extras.fluid_ticks.clear();
}
extras.last_update = time;
if let Some(t) = self.world.inhabited.get(&(chunk.x, chunk.z)) {
extras
.root
.insert("InhabitedTime".into(), horizon_world::nbt::Tag::Long(*t));
}
chunk.saved = Some(Arc::new(extras));
}
/// Register a newly resident chunk with the tick scheduler, with the
@@ -63,6 +68,13 @@ impl Game<'_> {
pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) {
let pos = ChunkPos::new(key.0, key.1);
let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone());
// ChunkAccess.inhabitedTime as saved.
if let Some(Tag::Long(t)) = saved
.as_deref()
.and_then(|s| s.root.get(&"InhabitedTime".into()))
{
self.world.inhabited.insert(key, *t);
}
let (blocks, fluids) = saved.as_deref().map_or((Vec::new(), Vec::new()), |s| {
(s.block_ticks.clone(), s.fluid_ticks.clone())
});
@@ -221,7 +233,13 @@ impl Game<'_> {
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
horizon_client::mobs::spawning::finalize(&mut m, &facts);
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 = [
+24 -3
View File
@@ -452,6 +452,10 @@ pub struct Extra {
pub main_hand: Option<Arc<str>>,
pub off_hand: Option<Arc<str>>,
pub head: Option<Arc<str>>,
/// Worn armour below the head (humanoid mobs).
pub chest: Option<Arc<str>>,
pub legs: Option<Arc<str>>,
pub feet: Option<Arc<str>>,
pub using_item: i32,
pub flag: bool,
pub flag2: bool,
@@ -837,6 +841,22 @@ impl Mob {
}
/// LivingEntity.hurtServer: invulnerability frames, armor, knockback and
/// the last-hurt-by bookkeeping goals read.
/// The `armor` and `armor_toughness` modifiers of worn humanoid armour.
pub fn worn_armor(&self) -> (f32, f32) {
if equine::is_equine(self.species()) {
return (0.0, 0.0);
}
[
&self.extra.head,
&self.extra.chest,
&self.extra.legs,
&self.extra.feet,
]
.into_iter()
.flatten()
.map(|i| spawning::armor_stats(i))
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
}
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
if !self.alive() || self.removed {
return false;
@@ -848,10 +868,11 @@ impl Mob {
return false;
}
let mut amount = amount;
if !source.bypasses_armor() && self.kind.armor > 0.0 {
let (worn, worn_toughness) = self.worn_armor();
if !source.bypasses_armor() && self.kind.armor + worn > 0.0 {
// CombatRules.getDamageAfterAbsorb
let armor = self.kind.armor;
let toughness = 2.0 + self.kind.armor_toughness / 4.0;
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;
}
+56
View File
@@ -533,8 +533,64 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
}
_ => {}
}
humanoid_armor(m, &mut v);
v
}
/// `HumanoidArmorLayer`: the armour models of the mob's main model with the
/// equipment textures (leather tinted, with its overlay).
fn humanoid_armor(m: &Mob, v: &mut Vec<Layer>) {
if super::equine::is_equine(m.species()) {
return;
}
let (model, _) = body(m);
let Some(base) = model.strip_suffix("#main") else {
return;
};
let slots = [
(&m.extra.head, "helmet"),
(&m.extra.chest, "chestplate"),
(&m.extra.legs, "leggings"),
(&m.extra.feet, "boots"),
];
for (item, layer) in slots {
let Some(name) = item.as_deref().and_then(|i| i.strip_prefix("minecraft:")) else {
continue;
};
let Some(material) = name.strip_suffix(&format!("_{layer}")) else {
continue;
};
let asset = match material {
"golden" => "gold",
"turtle" => "turtle_scute",
other => other,
};
let folder = if layer == "leggings" {
"humanoid_leggings"
} else {
"humanoid"
};
let model = format!("{base}#{layer}");
let tint = if asset == "leather" {
abgr(0xA06540)
} else {
0xFFFF_FFFF
};
v.push(Layer {
model: model.clone(),
texture: format!("entity/equipment/{folder}/{asset}"),
color: tint,
full_bright: false,
});
if asset == "leather" {
v.push(Layer {
model,
texture: format!("entity/equipment/{folder}/leather_overlay"),
color: 0xFFFF_FFFF,
full_bright: false,
});
}
}
}
impl super::MobType {
/// The main model layer key without the namespace.
pub fn model_key(&self) -> String {
+145 -11
View File
@@ -180,7 +180,111 @@ pub fn spawn_rules_ok(
}
}
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
pub fn finalize(m: &mut Mob, biome: &BiomeFacts) {
/// `DifficultyInstance`: the local difficulty at a position.
#[derive(Clone, Copy, Debug)]
pub struct LocalDifficulty {
pub effective: f32,
/// The world difficulty is hard.
pub hard: bool,
}
/// `DimensionType.MOON_BRIGHTNESS_PER_PHASE`.
pub const MOON_BRIGHTNESS: [f32; 8] = [1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75];
impl LocalDifficulty {
/// `calculateDifficulty` from the difficulty id (0 peaceful to 3 hard),
/// the overworld clock, the chunk's inhabited time and the moon.
pub fn new(base: u8, total: i64, inhabited: i64, moon: f32) -> Self {
let hard = base == 3;
if base == 0 {
return Self {
effective: 0.0,
hard,
};
}
let global = ((total as f32 - 72000.0) / 1_440_000.0).clamp(0.0, 1.0) * 0.25;
let mut local =
(inhabited as f32 / 3_600_000.0).clamp(0.0, 1.0) * if hard { 1.0 } else { 0.75 };
local += (moon * 0.25).clamp(0.0, global);
if base == 1 {
local *= 0.5;
}
Self {
effective: f32::from(base) * (0.75 + global + local),
hard,
}
}
/// `getSpecialMultiplier`.
pub fn special(&self) -> f32 {
if self.effective < 2.0 {
0.0
} else if self.effective > 4.0 {
1.0
} else {
(self.effective - 2.0) / 2.0
}
}
}
/// The armour and toughness each vanilla armour piece adds.
pub fn armor_stats(item: &str) -> (f32, f32) {
let Some(name) = item.strip_prefix("minecraft:") else {
return (0.0, 0.0);
};
let slot = ["helmet", "chestplate", "leggings", "boots"]
.iter()
.position(|p| name.ends_with(p));
let Some(slot) = slot else { return (0.0, 0.0) };
let (points, toughness): ([f32; 4], f32) = match name.split('_').next() {
Some("leather") => ([1.0, 3.0, 2.0, 1.0], 0.0),
Some("copper") => ([2.0, 4.0, 3.0, 1.0], 0.0),
Some("golden") => ([2.0, 5.0, 3.0, 1.0], 0.0),
Some("chainmail") => ([2.0, 5.0, 4.0, 1.0], 0.0),
Some("iron") => ([2.0, 6.0, 5.0, 2.0], 0.0),
Some("turtle") => ([2.0, 0.0, 0.0, 0.0], 0.0),
Some("diamond") => ([3.0, 8.0, 6.0, 3.0], 2.0),
Some("netherite") => ([3.0, 8.0, 6.0, 3.0], 3.0),
_ => return (0.0, 0.0),
};
(points[slot], toughness)
}
/// `Mob.populateDefaultEquipmentSlots`: sometimes a set of armour, from the
/// head down, of one random material.
fn populate_armor(m: &mut Mob, d: &LocalDifficulty) {
if m.random.next_float() >= 0.15 * d.special() {
return;
}
let mut kind = m.random.next_int_bound(3).unwrap_or(0);
for _ in 1..=3 {
if m.random.next_float() < 0.1087 {
kind += 1;
}
}
let partial = if d.hard { 0.1 } else { 0.25 };
let material = [
"leather",
"copper",
"golden",
"chainmail",
"iron",
"diamond",
][kind as usize];
for (i, piece) in ["helmet", "chestplate", "leggings", "boots"]
.into_iter()
.enumerate()
{
if i > 0 && m.random.next_float() < partial {
break;
}
let slot = match i {
0 => &mut m.extra.head,
1 => &mut m.extra.chest,
2 => &mut m.extra.legs,
_ => &mut m.extra.feet,
};
if slot.is_none() {
*slot = Some(format!("minecraft:{material}_{piece}").into());
}
}
}
pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
use Species as S;
let climate_index = match biome.climate {
Climate::Temperate => 0,
@@ -199,18 +303,22 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts) {
if m.random.next_float() < 0.05 {
m.extra.age = i32::MIN / 2;
}
if m.species() != S::Drowned && m.random.next_float() < 0.01 {
let r = m.random.next_int_bound(3).unwrap_or(0);
if m.species() != S::Drowned {
populate_armor(m, difficulty);
}
let weapon = if difficulty.hard { 0.05 } else { 0.01 };
if m.species() != S::Drowned && m.random.next_float() < weapon {
let r = m.random.next_int_bound(6).unwrap_or(0);
m.extra.main_hand = Some(
if r == 0 {
"minecraft:iron_sword"
} else {
"minecraft:iron_shovel"
match r {
0 => "minecraft:iron_sword",
1 => "minecraft:iron_spear",
_ => "minecraft:iron_shovel",
}
.into(),
);
}
if m.species() == S::Drowned && m.random.next_float() < 0.0625 {
if m.species() == S::Drowned && m.random.next_float() > 0.9 {
m.extra.main_hand = Some(
if m.random.next_int_bound(16).unwrap_or(1) < 10 {
"minecraft:trident"
@@ -225,16 +333,42 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts) {
m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8;
}
}
// ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword.
S::ZombifiedPiglin => m.extra.main_hand = Some("minecraft:golden_sword".into()),
// ZombifiedPiglin.populateDefaultEquipmentSlots: a golden sword, or
// one time in 20 a golden spear.
S::ZombifiedPiglin => {
let spear = m.random.next_int_bound(20).unwrap_or(1) == 0;
m.extra.main_hand = Some(
if spear {
"minecraft:golden_spear"
} else {
"minecraft:golden_sword"
}
.into(),
);
}
// AbstractSkeleton.populateDefaultEquipmentSlots (the bow is given on
// registration).
S::Skeleton | S::Stray | S::Bogged | S::Parched => populate_armor(m, difficulty),
S::Pillager => m.extra.main_hand = Some("minecraft:crossbow".into()),
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse => {
super::equine::finalize(m)
}
// Camel.finalizeSpawn: standing, with fixed attributes.
S::Camel => super::camel::stand_up_instantly(m),
// Piglin.createSpawnWeapon: half crossbows, half golden swords.
// Piglin.createSpawnWeapon: half crossbows, half golden swords, and
// each piece of golden armour one time in ten.
S::Piglin if !m.is_baby() => {
for i in 0..4 {
if m.random.next_float() < 0.1 {
let (slot, piece) = match i {
0 => (&mut m.extra.head, "helmet"),
1 => (&mut m.extra.chest, "chestplate"),
2 => (&mut m.extra.legs, "leggings"),
_ => (&mut m.extra.feet, "boots"),
};
*slot = Some(format!("minecraft:golden_{piece}").into());
}
}
let crossbow = m.random.next_float() < 0.5;
m.extra.main_hand = Some(
if crossbow {
+4
View File
@@ -26,6 +26,9 @@ pub struct World {
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
/// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent
/// within spawning range (local difficulty).
pub inhabited: HashMap<(i32, i32), i64>,
pub game_time: i64,
pub day_time: i64,
pub weather: Weather,
@@ -103,6 +106,7 @@ impl World {
loaded_entities: Vec::new(),
modified: HashSet::new(),
block_entities: HashMap::new(),
inhabited: HashMap::new(),
game_time: 0,
day_time: 1000,
weather: Weather::default(),