Files
horizon-airdef/crates/horizon-client/src/mobs/spawning.rs
T
2026-10-09 14:05:35 +02:00

426 lines
16 KiB
Rust

//! Natural spawning rules: `SpawnPlacements` placement types and each
//! species' spawn predicate (`checkAnimalSpawnRules`, `checkMonsterSpawnRules`,
//! water animals, bats...), and `finalizeSpawn` (variants, colours, babies,
//! equipment).
use super::{Mob, MobWorld, Species, data, farm::Climate};
use crate::blocks::Fluid;
use horizon_core::random::RandomSource;
/// Biome facts finalizeSpawn and the spawn rules read.
#[derive(Clone, Copy, Debug, Default)]
pub struct BiomeFacts {
pub climate: Climate,
/// Biome temperature at the position (strays in cold biomes, snow foxes).
pub temperature: f32,
pub snowy: bool,
pub swamp: bool,
pub ocean: bool,
pub mushroom: bool,
pub desert: bool,
pub jungle: bool,
/// Frog variant from `spawns_warm/cold_variant_frogs` (0 temperate, 1 warm, 2 cold).
pub frog: u8,
/// Wolf variant index (`tame::WOLF_VARIANTS`).
pub wolf: u8,
/// `MoonBrightnessCheck(>= 0.9)`: the full moon.
pub full_moon: bool,
}
/// SpawnPlacementTypes for the species.
pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
let id = format!("minecraft:{}", super::species::def(species).name);
match w.data.placement(&id) {
data::Placement::OnGround => {
let below = w.data.state(w.world.block(x, y - 1, z));
let valid = match species {
Species::Ocelot | Species::Parrot => below.flags & data::VALID_SPAWN_LEAVES != 0,
Species::PolarBear => below.flags & data::VALID_SPAWN_ICE != 0,
_ => below.flags & data::VALID_SPAWN != 0,
};
valid && empty(w, x, y, z) && empty(w, x, y + 1, z)
}
data::Placement::InWater => {
w.fluid(x, y, z) == Fluid::Water
&& w.data.state(w.world.block(x, y + 1, z)).flags & data::REDSTONE_CONDUCTOR == 0
}
data::Placement::InLava => w.fluid(x, y, z) == Fluid::Lava,
data::Placement::NoRestrictions => true,
}
}
fn empty(w: &MobWorld, x: i32, y: i32, z: i32) -> bool {
w.data.state(w.world.block(x, y, z)).flags & data::VALID_EMPTY_SPAWN != 0
}
/// Monster.isDarkEnoughToSpawn (overworld: sky light vs random(32), block light 0).
pub fn dark_enough(w: &MobWorld, random: &mut impl RandomSource, x: i32, y: i32, z: i32) -> bool {
let light = w.world.light(x, y, z);
let (sky, block) = (i32::from(light >> 4), i32::from(light & 15));
if sky > random.next_int_bound(32).unwrap_or(0) {
return false;
}
if block > 0 {
return false;
}
let darken = if w.thundering { 10 } else { w.sky_darken() };
(sky - darken).max(0) <= random.next_int_bound(8).unwrap_or(0)
}
/// The species' checkSpawnRules for natural spawns.
pub fn spawn_rules_ok(
species: Species,
w: &MobWorld,
random: &mut impl RandomSource,
x: i32,
y: i32,
z: i32,
) -> bool {
use Species as S;
let below = w.block_name(x, y - 1, z).to_owned();
let light = w.world.light(x, y, z);
let raw = i32::from(light >> 4).max(i32::from(light & 15));
match species {
// Guardian.checkGuardianSpawnRules.
S::Guardian | S::ElderGuardian => {
let sky_from_below = || {
let sea = 63;
if y >= sea {
return w.can_see_sky(x, y, z);
}
if !w.can_see_sky(x, sea, z) {
return false;
}
((y + 1)..sea).all(|yy| {
let f = w.facts.get(w.world.block(x, yy, z));
!f.full_collision || f.fluid != Fluid::None
})
};
(random.next_int_bound(20).unwrap_or(1) == 0 || !sky_from_below())
&& w.fluid(x, y, z) == Fluid::Water
&& w.fluid(x, y - 1, z) == Fluid::Water
}
// Animal.checkAnimalSpawnRules: animals_spawnable_on below and bright.
S::Pig
| S::Cow
| S::Sheep
| S::Chicken
| S::Horse
| S::Donkey
| S::Llama
| S::Wolf
| S::Cat
| S::Fox
| S::Rabbit
| S::Goat
| S::Panda
| S::Armadillo
| S::Mooshroom
| S::Turtle
| S::Frog
| S::Bee => {
let tag = match species {
S::Mooshroom => "minecraft:mooshrooms_spawnable_on",
S::Wolf => "minecraft:wolves_spawnable_on",
S::Fox => "minecraft:foxes_spawnable_on",
S::Rabbit => "minecraft:rabbits_spawnable_on",
S::Goat => "minecraft:goats_spawnable_on",
S::Armadillo => "minecraft:armadillo_spawnable_on",
S::Turtle => "minecraft:turtles_spawnable_on",
S::Frog => "minecraft:frogs_spawnable_on",
_ => "minecraft:animals_spawnable_on",
};
w.has_tag(tag, &below) && raw > 8
}
S::PolarBear => {
w.has_tag("minecraft:polar_bears_spawnable_on_alternate", &below)
|| w.has_tag("minecraft:animals_spawnable_on", &below) && raw > 8
}
S::Ocelot | S::Parrot => {
(w.has_tag("minecraft:parrots_spawnable_on", &below)
|| below.contains("leaves")
|| below == "minecraft:grass_block")
&& raw > 8
}
S::Bat => {
// Bat.checkBatSpawnRules: below sea level, dark.
if y >= 63 {
return false;
}
let block = i32::from(light & 15).max(i32::from(light >> 4));
block <= random.next_int_bound(4).unwrap_or(0)
}
S::Slime => {
// Swamp at night by moon brightness, or slime chunks below y 40.
y < 40 && random.next_int_bound(10).unwrap_or(1) == 0
}
// GlowSquid.checkGlowSquidSpawnRules: deep, pitch dark water.
S::GlowSquid => y <= 63 - 33 && light == 0 && w.block_name(x, y, z) == "minecraft:water",
S::Squid | S::Cod | S::Salmon | S::TropicalFish | S::Pufferfish | S::Dolphin => {
// WaterAnimal.checkSurfaceWaterAnimalSpawnRules: sea level - 13 ..= sea level.
(50..=63).contains(&y)
&& w.fluid(x, y - 1, z) == Fluid::Water
&& w.block_name(x, y + 1, z) == "minecraft:water"
}
S::Axolotl => w.block_name(x, y - 1, z) == "minecraft:clay",
S::Strider => w.fluid(x, y, z) == Fluid::Lava,
S::Ghast
| S::MagmaCube
| S::ZombifiedPiglin
| S::Piglin
| S::Hoglin
| S::Blaze
| S::WitherSkeleton
| S::Enderman
if w.nether =>
{
!w.block_name(x, y - 1, z).contains("nether_wart_block") || species == S::Ghast
}
S::Husk | S::Stray => dark_enough(w, random, x, y, z) && w.can_see_sky(x, y, z),
S::Drowned => w.fluid(x, y, z) == Fluid::Water && dark_enough(w, random, x, y, z),
_ => {
// Monster.checkMonsterSpawnRules
!w.nether && dark_enough(w, random, x, y, z) || w.nether
}
}
}
/// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs.
/// `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,
Climate::Warm => 1,
Climate::Cold => 2,
};
match m.species() {
// Warden.finalizeSpawn: a minute before it digs back down.
S::Warden => super::warden::finalize(m, false, &mut Vec::new()),
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0,
S::Frog => m.extra.variant = biome.frog,
S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
S::Zombie | S::Husk | S::Drowned | S::ZombieVillager => {
// Zombie.finalizeSpawn: pick up loot 55% of the time (scaled by
// difficulty), 5% babies (normal difficulty).
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
if m.random.next_float() < 0.05 {
m.extra.age = i32::MIN / 2;
}
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(
match r {
0 => "minecraft:iron_sword",
1 => "minecraft:iron_spear",
_ => "minecraft:iron_shovel",
}
.into(),
);
}
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"
} else {
"minecraft:fishing_rod"
}
.into(),
);
}
if m.species() == S::ZombieVillager {
m.extra.variant = villager_type(biome);
m.extra.variant2 = m.random.next_int_bound(15).unwrap_or(0) as u8;
}
}
// 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);
m.extra.pick_up_loot = m.random.next_float() < 0.55 * difficulty.special();
}
S::Pillager => {
m.extra.main_hand = Some("minecraft:crossbow".into());
m.extra.pick_up_loot = true;
}
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, and
// each piece of golden armour one time in ten.
S::Piglin if !m.is_baby() => {
m.extra.pick_up_loot = true;
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 {
"minecraft:crossbow"
} else {
"minecraft:golden_sword"
}
.into(),
);
}
S::PiglinBrute => {
m.extra.main_hand = Some("minecraft:golden_axe".into());
m.extra.pick_up_loot = true;
}
S::Vindicator => m.extra.main_hand = Some("minecraft:iron_axe".into()),
S::Villager => {
m.extra.variant = villager_type(biome);
m.extra.pick_up_loot = true;
}
S::Fox | S::Panda | S::Dolphin => m.extra.pick_up_loot = true,
S::TropicalFish => super::aquatic::finalize(m),
S::Slime | S::MagmaCube => super::cube::finalize(m),
_ => {}
}
}
/// VillagerType.byBiome
pub fn villager_type(b: &BiomeFacts) -> u8 {
if b.desert {
1
} else if b.jungle {
2
} else if b.snowy {
4
} else if b.swamp {
5
} else if b.climate == Climate::Warm {
3
} else if b.climate == Climate::Cold && b.temperature < 0.4 {
6
} else {
0
}
}