Merge main into the loom and recipe book work

# Conflicts:
#	crates/horizon-client/src/containers.rs
#	crates/horizon-client/src/game.rs
#	crates/horizon-client/src/game/creatures.rs
#	crates/horizon-client/src/item_data.rs
#	crates/horizon-client/src/lib.rs
#	crates/horizon-client/src/save.rs
This commit is contained in:
Ludovic Marie
2026-10-09 13:32:57 +02:00
57 changed files with 8644 additions and 458 deletions
+3
View File
@@ -94,6 +94,8 @@ pub struct Chunk {
/// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky.
pub heights: Arc<[i16; 256]>,
pub lit: bool,
/// Light read from a save with `isLightOn`: no light job is needed.
pub light_loaded: bool,
/// Newly generated (not loaded from a save): eligible for generation-time spawns.
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
@@ -120,6 +122,7 @@ impl Chunk {
biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]),
heights: Arc::new([MIN_Y as i16; 256]),
lit: false,
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
structure_refs: Vec::new(),
@@ -111,6 +111,28 @@ pub fn build() -> Dispatcher {
d.executes(dur, "weather");
}
// raid start <omenlvl> | stop | check | sound <type> | spawnleader | setomen <level> | glow
let raid = d.literal(root, "raid");
d.requires(raid, 3);
let start = d.literal(raid, "start");
let level = d.argument(start, "omenlvl", integer(0));
d.executes(level, "raid.start");
for (name, id) in [
("stop", "raid.stop"),
("check", "raid.check"),
("spawnleader", "raid.spawnleader"),
("glow", "raid.glow"),
] {
let n = d.literal(raid, name);
d.executes(n, id);
}
let sound = d.literal(raid, "sound");
let kind = d.argument(sound, "type", ArgType::Greedy);
d.executes(kind, "raid.sound");
let setomen = d.literal(raid, "setomen");
let level = d.argument(setomen, "level", integer(0));
d.executes(level, "raid.setomen");
// kill [<targets>]
let kill = d.literal(root, "kill");
d.requires(kill, GAMEMASTERS);
+21 -1
View File
@@ -58,6 +58,8 @@ pub enum BlockEntity {
Beacon(Box<Beacon>),
/// `LecternBlockEntity`: the book and the open page.
Lectern(Lectern),
/// `CreakingHeartBlockEntity`: its protector and the hurt emitter.
CreakingHeart(Box<CreakingHeart>),
/// `BannerBlockEntity`: the pattern layers.
Banner(Banner),
/// `CrafterBlockEntity`.
@@ -116,6 +118,18 @@ pub struct Banner {
pub layers: Vec<crate::banner::BannerLayer>,
pub name: Option<String>,
}
/// `CreakingHeartBlockEntity` (the logic is in `game/creaking.rs`).
#[derive(Clone, Debug, Default)]
pub struct CreakingHeart {
/// The protector: its entity id once resolved, and its UUID (the saved form).
pub creaking: Option<(Option<u32>, [i32; 4])>,
pub ticks_existed: i64,
pub ticker: i32,
/// Ticks left of the hurt effect (`emitter`) and where it heads.
pub emitter: i32,
pub emitter_target: Option<[f64; 3]>,
pub output_signal: i32,
}
#[derive(Clone, Debug, Default)]
pub struct Lectern {
pub book: Option<ItemStack>,
@@ -158,6 +172,9 @@ impl BlockEntity {
speed: 1.0,
}));
}
if name == "minecraft:creaking_heart" {
return Some(Self::CreakingHeart(Box::default()));
}
if name == "minecraft:lectern" {
return Some(Self::Lectern(Lectern::default()));
}
@@ -221,6 +238,7 @@ impl BlockEntity {
Self::Lectern(_) => "minecraft:lectern",
Self::Banner(_) => "minecraft:banner",
Self::Crafter(_) => "minecraft:crafter",
Self::CreakingHeart(_) => "minecraft:creaking_heart",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -230,7 +248,7 @@ impl BlockEntity {
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
Self::Sign(_) => Vec::new(),
Self::Jukebox(j) => j.record.iter().cloned().collect(),
Self::Beacon(_) => Vec::new(),
Self::Beacon(_) | Self::CreakingHeart(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
@@ -247,6 +265,7 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Banner(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_) => &[],
}
}
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
@@ -260,6 +279,7 @@ impl BlockEntity {
| Self::Lectern(_)
| Self::Banner(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_) => &mut [],
}
}
}
+40 -3
View File
@@ -124,7 +124,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
for (key, value) in [
("AbsorptionAmount", Tag::Float(0)),
("FallFlying", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(0)),
("CanPickUpLoot", Tag::Byte(i8::from(m.extra.pick_up_loot))),
("LeftHanded", Tag::Byte(0)),
(
"Brain",
@@ -251,6 +251,14 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
map.insert("equipment".into(), Tag::Compound(equipment));
}
"minecraft:creaking" => {
// home_pos: the heart it is bound to.
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
} else {
map.remove(&"home_pos".into());
}
}
"minecraft:villager" => {
use crate::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
let data = Tag::compound([
@@ -277,6 +285,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.insert("RestocksToday".into(), Tag::Int(t.restocks_today));
put_offers(map, m);
put_memories(map, m);
crate::mobs::villager::write_nbt(m, map);
}
"minecraft:wandering_trader" => put_offers(map, m),
"minecraft:allay" => {
@@ -368,6 +377,7 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
_ => {}
}
crate::mobs::raider::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()) {
@@ -388,7 +398,22 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
equipment.get(&slot.into()).and_then(|e| e.get("id")),
Some(Tag::String(s)) if s.to_string_lossy() == **id
);
if !keep {
if slot == "head"
&& &**id == crate::mobs::raider::BANNER
&& crate::mobs::raider::is_raider(m.species())
{
// The captain's ominous banner keeps its patterns.
let has_patterns = equipment
.get(&slot.into())
.and_then(|e| e.get("components"))
.is_some();
if !has_patterns {
equipment.insert(
slot.into(),
crate::save::item_to_nbt(&crate::mobs::raider::ominous_banner()),
);
}
} else if !keep {
equipment.insert(
slot.into(),
Tag::compound([
@@ -451,6 +476,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
}
m.death_time = number(tag.get("DeathTime")).unwrap_or(0) as i32;
m.persistent = flag(tag, "PersistenceRequired");
m.extra.pick_up_loot = flag(tag, "CanPickUpLoot");
m.custom_name = custom_name(tag);
if m.kind.category == "creature" {
m.extra.age = number(tag.get("Age")).unwrap_or(0) as i32;
@@ -570,6 +596,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.egg_time = -1 - 400;
}
}
if m.species() == crate::mobs::Species::Creaking
&& let Some(Tag::IntArray(home)) = tag.get("home_pos")
&& home.len() == 3
{
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
}
if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
}
@@ -609,6 +641,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.health = health;
m.extra.flag2 = flag(tag, "wasOnGround");
}
crate::mobs::raider::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;
@@ -1022,7 +1055,7 @@ fn put_offers(map: &mut Compound, m: &Mob) {
}
/// The villager brain's `job_site`, `home` and `meeting_point` memories.
fn put_memories(map: &mut Compound, m: &Mob) {
let memories: Vec<(&str, Tag)> = [
let mut memories: Vec<(&str, Tag)> = [
("minecraft:job_site", m.extra.home),
("minecraft:home", m.extra.bed),
("minecraft:meeting_point", m.extra.meeting),
@@ -1036,6 +1069,7 @@ fn put_memories(map: &mut Compound, m: &Mob) {
Some((key, Tag::compound([("value", pos)])))
})
.collect();
crate::mobs::villager::write_memories(m, &mut memories);
map.insert(
"Brain".into(),
Tag::compound([("memories", Tag::compound(memories))]),
@@ -1069,6 +1103,9 @@ fn read_villager(m: &mut Mob, tag: &Tag) {
m.extra.home = memory("minecraft:job_site");
m.extra.bed = memory("minecraft:home");
m.extra.meeting = memory("minecraft:meeting_point");
if m.species() == crate::mobs::Species::Villager {
crate::mobs::villager::read_nbt(m, tag);
}
let Some(Tag::List(recipes)) = tag.get("Offers").and_then(|o| o.get("Recipes")) else {
return;
};
+29 -2
View File
@@ -14,8 +14,10 @@ mod chat;
mod combat;
mod commands;
mod control;
mod creaking;
mod creatures;
mod crossbow;
mod dispenser;
mod dragon;
mod enchant_effects;
mod end;
@@ -26,6 +28,7 @@ mod fishing;
mod fov;
mod frames;
mod game_mode;
mod golems;
mod growth;
mod jukebox;
mod lightning;
@@ -45,6 +48,7 @@ mod perspective;
mod piglins;
mod postprocess;
mod potions;
mod raids;
mod recipe_book;
mod remote;
mod render_control;
@@ -63,6 +67,7 @@ mod tnt;
mod totem;
mod trading;
mod trident;
mod villagers;
mod wither;
use horizon_client::{
Result,
@@ -309,6 +314,17 @@ impl LevelAccess for GameLevel<'_> {
if let Some((_, comparator)) = jukebox::jukebox_signals(self.world, self.items, pos) {
return comparator;
}
if let Some(signal) = creaking::heart_signal(self.world, pos) {
return if self.registry.state(_state).is_some_and(|s| {
s.properties
.get("creaking_heart_state")
.is_some_and(|v| v == "uprooted")
}) {
0
} else {
signal
};
}
if let Some(signal) = books::lectern_signal(self.world, pos) {
return signal;
}
@@ -521,6 +537,7 @@ struct Game<'a> {
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
raiding: raids::Raiding,
attack_ticks: u32,
last_hurt_by_player: HashSet<u32>,
chest_open: HashMap<(i32, i32, i32), (f32, f32)>,
@@ -621,6 +638,7 @@ struct Game<'a> {
hook: Option<fishing::Hook>,
tridents: Vec<trident::ThrownTrident>,
rockets: Vec<fireworks::Rocket>,
creaking: creaking::CreakingState,
trident_model: Option<horizon_client::mobs::Part>,
tnts: Vec<tnt::PrimedTnt>,
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
@@ -1618,6 +1636,7 @@ impl Game<'_> {
None
}
.unwrap_or(self.world.air);
self.creaking_heart_broken(pos);
if let Some(entity) = self.world.block_entities.remove(&(pos[0], pos[1], pos[2])) {
// Containers.dropContents (shulker boxes keep theirs).
let name = facts.name.clone();
@@ -1842,6 +1861,7 @@ impl Game<'_> {
self.stats.add("used", &stack.item, 1);
self.trigger_block("minecraft:placed_block", target, &stack);
self.check_wither_spawn(target)?;
self.check_golem_spawn(target)?;
self.consume_held();
Ok(())
}
@@ -2435,6 +2455,7 @@ impl Game<'_> {
self.screen = Screen::Dead;
self.capture(false);
}
self.tick_omens();
self.tick_effects();
self.tick_burning();
self.tick_using();
@@ -3059,7 +3080,8 @@ impl Game<'_> {
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_),
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -3258,7 +3280,8 @@ impl Game<'_> {
| BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_),
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -4336,6 +4359,7 @@ impl Game<'_> {
self.tick_mount_menu();
self.tick_jukeboxes();
self.tick_beacons();
self.tick_creaking_hearts()?;
// ChestLidController: 0.1 per tick towards open/closed.
if let Some(key) = self.container {
self.chest_open.entry(key).or_insert((0.0, 0.0));
@@ -6531,6 +6555,7 @@ impl Game<'_> {
.save(&chunks, self.res.assets.registry, &self.res.biomes)?;
self.save_entities()?;
self.save_maps();
self.save_raids();
self.save_fight();
self.save_stats();
self.save_advancements();
@@ -7648,6 +7673,7 @@ pub fn run() -> Result<()> {
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
raiding: Default::default(),
attack_ticks: 100,
last_hurt_by_player: HashSet::new(),
chest_open: HashMap::new(),
@@ -7722,6 +7748,7 @@ pub fn run() -> Result<()> {
hook: None,
tridents: Vec::new(),
rockets: Vec::new(),
creaking: Default::default(),
trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"),
tnts: Vec::new(),
hoppers: HashMap::new(),
@@ -281,12 +281,26 @@ impl Game<'_> {
}
}
pub(super) fn mob_entity(&self, m: &horizon_client::mobs::Mob) -> EntityView {
// mainhand, offhand, head, chest, legs, feet.
let slot = |i: &Option<std::sync::Arc<str>>| {
i.as_ref().map(|id| item_view(&ItemStack::new(id, 1)))
};
let mut equipment: [Option<ItemView>; 7] = Default::default();
if !horizon_client::mobs::equine::is_equine(m.species()) {
equipment[0] = slot(&m.extra.main_hand);
equipment[1] = slot(&m.extra.off_hand);
equipment[2] = slot(&m.extra.head);
equipment[3] = slot(&m.extra.chest);
equipment[4] = slot(&m.extra.legs);
equipment[5] = slot(&m.extra.feet);
}
EntityView {
kind: m.kind.id.clone(),
position: [m.position.x, m.position.y, m.position.z],
on_fire: m.fire_ticks > 0,
baby: m.is_baby(),
on_ground: m.on_ground,
equipment,
..Default::default()
}
}
@@ -2,6 +2,7 @@
//! entity selectors resolved against the game, vanilla feedback and errors.
mod effects;
pub(super) mod execute;
mod raid;
mod text_commands;
use super::{Dim, Game, Screen, chat::PLAYER_NAME};
@@ -418,6 +419,7 @@ impl Game<'_> {
| "teleport.targets.location"
| "teleport.targets.destination" => self.cmd_teleport(id, ctx),
id if id.starts_with("time.") => self.cmd_time(id, ctx),
id if id.starts_with("raid.") => self.cmd_raid(id, ctx),
"weather" => self.cmd_weather(ctx),
"kill" => self.cmd_kill(ctx),
"summon" => self.cmd_summon(ctx),
@@ -0,0 +1,108 @@
//! `RaidCommand`: `/raid start|stop|check|spawnleader|setomen|glow|sound`.
use super::{Game, R, Text, err};
use horizon_client::{command::Context, mobs::raider};
impl Game<'_> {
pub(in crate::game) fn cmd_raid(&mut self, id: &str, ctx: &Context) -> R<i32> {
let Some(player) = self.player.as_ref().map(|p| p.position) else {
return Ok(0);
};
let at = [
player.x.floor() as i32,
player.y.floor() as i32,
player.z.floor() as i32,
];
let fail = |game: &mut Self, message: &str| {
game.command_failure(Text::literal(message));
};
match id {
"raid.start" => {
if self.raiding_nearby(at).is_some() {
fail(self, "Raid already started close by");
return Ok(-1);
}
let level = Self::int(ctx, "omenlvl").unwrap_or(0);
match self.raid_command_create(at, level) {
true => self.feedback(Text::literal("Created a raid in your local village")),
false => fail(self, "Failed to create a raid in your local village"),
}
Ok(1)
}
"raid.stop" => match self.raiding_nearby(at) {
Some(raid) => {
self.raid_command_stop(raid);
self.feedback(Text::literal("Stopped raid"));
Ok(1)
}
None => {
fail(self, "No raid here");
Ok(-1)
}
},
"raid.check" => match self.raiding_nearby(at).filter(|id| self.raid_started(*id)) {
Some(raid) => {
self.feedback(Text::literal("Found a started raid!"));
let status = self.raid_status_text(raid);
self.feedback(Text::literal(&status));
Ok(1)
}
None => {
fail(self, "Found no started raids");
Ok(0)
}
},
"raid.spawnleader" => {
let kind = "minecraft:pillager";
match self.spawn_mob_for(kind, [player.x, player.y, player.z], true, true) {
Some(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
raider::set_patrol_leader(m, true);
raider::finalize(m, raider::Reason::Other);
}
self.feedback(Text::literal("Spawned a raid captain"));
Ok(1)
}
None => {
fail(self, "Pillager failed to spawn");
Ok(0)
}
}
}
"raid.setomen" => {
let level = Self::int(ctx, "level").unwrap_or(0);
let Some(raid) = self.raiding_nearby(at) else {
fail(self, "No raid found here");
return Ok(1);
};
if level > horizon_client::raid::MAX_OMEN_LEVEL {
fail(
self,
&format!(
"Sorry, the max raid omen level you can set is {}",
horizon_client::raid::MAX_OMEN_LEVEL
),
);
} else {
let before = self.raid_set_omen(raid, level);
self.feedback(Text::literal(format!(
"Changed village's raid omen level from {before} to {level}"
)));
}
Ok(1)
}
"raid.glow" => {
if let Some(raid) = self.raiding_nearby(at) {
self.raid_glow(raid);
}
Ok(1)
}
"raid.sound" => {
let at = [player.x + 5.0, player.y, player.z];
self.audio
.play("minecraft:event.raid.horn", Some(at), 1.0, 1.0);
Ok(1)
}
_ => Err(err("commands.help.failed", &[])),
}
}
}
+663
View File
@@ -0,0 +1,663 @@
//! The creaking heart block entity (`CreakingHeartBlockEntity`): at night an
//! awake heart in a pale oak trunk spawns a creaking that protects it,
//! hurting the creaking makes the heart emit trails and spread resin over
//! the logs, and breaking the heart tears the creaking down.
use super::Game;
use horizon_client::{
Result,
containers::{BlockEntity, CreakingHeart},
mobs::creaking,
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Aabb, position::BlockPos, random::RandomSource};
use horizon_world::registry::BlockStateId;
use std::collections::{HashSet, VecDeque};
type Pos = (i32, i32, i32);
/// `Creaking.CREAKING_ORANGE` and `CREAKING_GRAY`.
const ORANGE: u32 = 16_545_810;
const GRAY: u32 = 6_250_335;
/// `CreakingHeartBlockEntity.DISTANCE_CREAKING_TOO_FAR`.
const TOO_FAR: f64 = 34.0;
/// `Direction.values()`: down, up, north, south, west, east.
const DIRECTIONS: [[i32; 3]; 6] = [
[0, -1, 0],
[0, 1, 0],
[0, 0, -1],
[0, 0, 1],
[-1, 0, 0],
[1, 0, 0],
];
const FACE_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"];
/// Comparator input of a heart (`getAnalogOutputSignal`).
pub(super) fn heart_signal(world: &horizon_client::world::World, pos: BlockPos) -> Option<i32> {
match world.block_entities.get(&(pos.x, pos.y, pos.z))? {
BlockEntity::CreakingHeart(h) => Some(h.output_signal),
_ => None,
}
}
impl Game<'_> {
fn heart_state_name(&self, state: BlockStateId) -> String {
self.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("creaking_heart_state").cloned())
.unwrap_or_default()
}
/// `Util.shuffledCopy(Direction.values(), random)`.
fn shuffled_directions(&mut self) -> [usize; 6] {
let mut order = [0, 1, 2, 3, 4, 5];
for i in (2..=6).rev() {
let j = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
order.swap(i - 1, j);
}
order
}
fn is_pale_oak_log(&self, p: Pos) -> bool {
let name = &self.res.facts.get(self.world.block(p.0, p.1, p.2)).name;
self.res
.items
.block_tags
.get("minecraft:pale_oak_logs")
.is_some_and(|s| s.contains(&**name))
}
fn mob_center(&self, id: u32) -> Option<([f64; 3], Aabb)> {
let m = self.mobs.iter().find(|m| m.id == id && !m.removed)?;
Some((m.center(), m.bounds()))
}
/// The protector's entity, resolving a UUID read from a save.
fn heart_protector(&mut self, heart: &mut CreakingHeart) -> Option<u32> {
let (id, uuid) = heart.creaking?;
if let Some(id) = id {
if self.mobs.iter().any(|m| m.id == id && !m.removed) {
return Some(id);
}
// The entity is gone: remember it by UUID until it reappears.
heart.creaking = Some((None, uuid));
}
if let Some(id) = self.mob_id_for_uuid(uuid) {
heart.creaking = Some((Some(id), uuid));
return Some(id);
}
if heart.ticks_existed >= 30 {
heart.creaking = None;
}
None
}
/// `CreakingHeartBlockEntity.removeProtector`: the creaking falls apart.
fn heart_remove_protector(&mut self, heart: &mut CreakingHeart, by_player: bool) {
let Some(id) = self.heart_protector(heart) else {
return;
};
if by_player {
// creakingDeathEffects: a twitching death.
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
creaking::set_tearing_down(m);
m.health = 0.0;
m.death_time = m.death_time.max(0);
let at = m.center();
self.audio
.play("minecraft:entity.creaking.twitch", Some(at), 1.0, 1.0);
}
} else if let Some(i) = self.mobs.iter().position(|m| m.id == id) {
let mut events = Vec::new();
creaking::tear_down(&mut self.mobs[i], &mut events);
let _ = self.handle_mob_events(events);
}
heart.creaking = None;
}
fn heart_distance_to_creaking(&self, id: u32, pos: Pos) -> f64 {
self.mob_center(id).map_or(0.0, |_| {
let m = self.mobs.iter().find(|m| m.id == id).unwrap();
let at = (
f64::from(pos.0) + 0.5,
f64::from(pos.1),
f64::from(pos.2) + 0.5,
);
((m.position.x - at.0).powi(2)
+ (m.position.y - at.1).powi(2)
+ (m.position.z - at.2).powi(2))
.sqrt()
})
}
/// `emitParticles`: trails between the creaking and the heart.
fn heart_emit(&mut self, heart: &mut CreakingHeart, pos: Pos, count: i32, towards: bool) {
let Some(id) = self.heart_protector(heart) else {
return;
};
let Some((_, b)) = self.mob_center(id) else {
return;
};
let (lo, hi) = (b.min_position(), b.max_position());
for _ in 0..count {
let r = &mut self.world.random;
let mut source = [
lo.x + r.next_double() * (hi.x - lo.x),
lo.y + r.next_double() * (hi.y - lo.y),
lo.z + r.next_double() * (hi.z - lo.z),
];
let mut destination = [
f64::from(pos.0) + r.next_double(),
f64::from(pos.1) + r.next_double(),
f64::from(pos.2) + r.next_double(),
];
if towards {
std::mem::swap(&mut source, &mut destination);
}
let duration = r.next_int_bound(40).unwrap_or(0) + 10;
let color = if towards { ORANGE } else { GRAY };
self.particles.add(
&ParticleOptions::trail(destination, color, duration),
source,
[0.0; 3],
);
}
}
/// `CreakingHeartBlockEntity.spreadResin`: a resin clump on the first log
/// face found within two steps of pale oak logs.
fn heart_spread_resin(&mut self, pos: Pos) -> Option<Pos> {
let mut visited: HashSet<Pos> = HashSet::new();
let mut queue: VecDeque<(Pos, i32)> = VecDeque::new();
queue.push_back((pos, 0));
let mut count = 0;
while let Some((current, depth)) = queue.pop_front() {
if !visited.insert(current) {
continue;
}
// The node processor.
if self.is_pale_oak_log(current) {
for d in self.shuffled_directions() {
let n = (
current.0 + DIRECTIONS[d][0],
current.1 + DIRECTIONS[d][1],
current.2 + DIRECTIONS[d][2],
);
let neighbour = self.world.block(n.0, n.1, n.2);
let opposite = d ^ 1;
let clump = self.resin_clump_for(neighbour);
let Some(clump) = clump else { continue };
if self.prop_is(clump, FACE_NAMES[opposite]) {
continue;
}
let Some(placed) = self.with_face(clump, FACE_NAMES[opposite]) else {
continue;
};
let _ = self.level_set([n.0, n.1, n.2], placed);
return Some(n);
}
}
count += 1;
if count >= 64 {
return None;
}
if depth < 2 {
// The neighbour provider: adjacent pale oak logs.
for d in self.shuffled_directions() {
let n = (
current.0 + DIRECTIONS[d][0],
current.1 + DIRECTIONS[d][1],
current.2 + DIRECTIONS[d][2],
);
if self.is_pale_oak_log(n) {
queue.push_back((n, depth + 1));
}
}
}
}
None
}
/// The state a face of resin can be added to: air, a source of water, or
/// a clump already there.
fn resin_clump_for(&self, neighbour: BlockStateId) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
let clump = registry.default_state("minecraft:resin_clump")?;
let facts = self.res.facts.get(neighbour);
if self.res.facts.is_air(neighbour) {
Some(clump)
} else if &*facts.name == "minecraft:water"
&& facts.fluid_level == 8
&& !facts.fluid_falling
{
let mut s = registry.state(clump)?.clone();
s.properties.insert("waterlogged".into(), "true".into());
registry.resolve(&s).ok()
} else if &*facts.name == "minecraft:resin_clump" {
Some(neighbour)
} else {
None
}
}
fn prop_is(&self, state: BlockStateId, key: &str) -> bool {
self.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get(key))
.is_some_and(|v| v == "true")
}
fn with_face(&self, state: BlockStateId, face: &str) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
s.properties.insert(face.to_owned(), "true".to_owned());
self.res.assets.registry.resolve(&s).ok()
}
/// A creaking bound to the heart at `home` was hurt (`creakingHurt`).
pub(super) fn creaking_hurt(&mut self, home: [i32; 3], id: u32, by_player: bool) {
if !by_player {
return;
}
let key = (home[0], home[1], home[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
else {
return;
};
if self.heart_protector(&mut heart) == Some(id) && heart.emitter <= 0 {
self.heart_emit(&mut heart, key, 20, false);
let state = self.world.block(key.0, key.1, key.2);
if self.heart_state_name(state) == "awake" {
let clumps = 2 + self.world.random.next_int_bound(2).unwrap_or(0);
for _ in 0..clumps {
if let Some(at) = self.heart_spread_resin(key) {
self.audio.play(
"minecraft:block.resin.place",
Some([
f64::from(at.0) + 0.5,
f64::from(at.1) + 0.5,
f64::from(at.2) + 0.5,
]),
1.0,
1.0,
);
}
}
}
heart.emitter = 100;
heart.emitter_target = self.mob_center(id).map(|(c, _)| c);
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
/// `Creaking.tearDown`: the crumble particles.
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
let registry = self.res.assets.registry;
let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| {
let Some(mut state) = registry
.default_state(name)
.and_then(|s| registry.state(s).cloned())
else {
return;
};
for (k, v) in props {
state.properties.insert((*k).to_owned(), (*v).to_owned());
}
let Ok(id) = registry.resolve(&state) else {
return;
};
let Some((sprite, tint)) = this.particle_sprite(id) else {
return;
};
for _ in 0..count {
let r = &mut this.world.random;
let p = [
center[0] + r.next_gaussian() * spread[0],
center[1] + r.next_gaussian() * spread[1],
center[2] + r.next_gaussian() * spread[2],
];
this.particles.add(
&ParticleOptions::block(ParticleType::BlockCrumble, sprite.clone(), tint),
p,
[0.0; 3],
);
}
};
crumble(self, "minecraft:pale_oak_wood", &[], 100);
crumble(
self,
"minecraft:creaking_heart",
&[("creaking_heart_state", "awake")],
10,
);
}
/// `CreakingHeartBlock.playerWillDestroy`: the heart's creaking twitches to
/// death and a natural heart drops experience.
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
let key = (pos[0], pos[1], pos[2]);
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
else {
return;
};
self.heart_remove_protector(&mut heart, true);
let state = self.world.block(key.0, key.1, key.2);
if self.prop_is(state, "natural") && !self.creative && !self.spectator() {
let xp = 20 + self.world.random.next_int_bound(5).unwrap_or(0) as u32;
self.spawn_orbs(
[
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
],
xp,
);
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
/// `SpawnUtil.trySpawnMob(CREAKING, .., 5, 16, 8, ON_TOP_OF_COLLIDER_NO_LEAVES, true)`.
fn spawn_protector(&mut self, pos: Pos) -> Option<u32> {
let t = self.res.mob_types.get("minecraft:creaking").cloned()?;
for _ in 0..5 {
let r = &mut self.world.random;
let dx = r.next_int_bound(33).unwrap_or(16) - 16;
let dz = r.next_int_bound(33).unwrap_or(16) - 16;
let mut at = (pos.0 + dx, pos.1 + 8, pos.2 + dz);
if !self.world.loaded(at.0, at.2) {
continue;
}
// moveToPossibleSpawnPosition: scan down for a collider with room above.
let mut above = self.world.block(at.0, at.1, at.2);
let mut found = false;
for _ in 0..=16 {
at.1 -= 1;
let current = self.world.block(at.0, at.1, at.2);
let facts = self.res.facts.get(current);
let leaves = self
.res
.items
.block_tags
.get("minecraft:leaves")
.is_some_and(|s| s.contains(&*facts.name));
let clear_above = self
.res
.behaviours
.collision_shape(above)
.map_or(!self.res.facts.get(above).full_collision, |s| s.is_empty());
if clear_above && !leaves && facts.sturdy_full & (1 << 1) != 0 {
at.1 += 1;
found = true;
break;
}
above = current;
}
if !found {
continue;
}
// noCollision(spawn box) and no liquid.
let w = t.width / 2.0;
let bounds = Aabb::new(
horizon_core::geometry::Vec3::new(
f64::from(at.0) + 0.5 - w,
f64::from(at.1),
f64::from(at.2) + 0.5 - w,
),
horizon_core::geometry::Vec3::new(
f64::from(at.0) + 0.5 + w,
f64::from(at.1) + t.height,
f64::from(at.2) + 0.5 + w,
),
);
let mut scene = horizon_client::collisions::SceneCollisions {
world: &self.world,
binding: self.collision,
};
let free = scene.unobstructed(bounds).unwrap_or(false);
let wet = self.res.facts.get(self.world.block(at.0, at.1, at.2)).fluid
!= horizon_client::blocks::Fluid::None;
if !free || wet {
continue;
}
let id = self.spawn_mob(
"minecraft:creaking",
[
f64::from(at.0) + 0.5,
f64::from(at.1),
f64::from(at.2) + 0.5,
],
false,
)?;
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
creaking::set_transient(m, [pos.0, pos.1, pos.2]);
}
return Some(id);
}
None
}
/// `CreakingHeartBlockEntity.computeAnalogOutputSignal`.
fn heart_output(&mut self, heart: &mut CreakingHeart, pos: Pos) -> i32 {
if heart.creaking.is_none() {
return 0;
}
let Some(id) = self.heart_protector(heart) else {
return 0;
};
let distance = self.heart_distance_to_creaking(id, pos).clamp(0.0, 32.0) / 32.0;
15 - (distance * 15.0).floor() as i32
}
/// `CreakingHeartBlockEntity.serverTick` for every heart.
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
let keys: Vec<Pos> = self
.world
.block_entities
.iter()
.filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_)))
.map(|(k, _)| *k)
.collect();
for key in keys {
let Some(BlockEntity::CreakingHeart(mut heart)) =
self.world.block_entities.remove(&key)
else {
continue;
};
let state = self.world.block(key.0, key.1, key.2);
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
// The block is gone: preRemoveSideEffects.
self.heart_remove_protector(&mut heart, false);
continue;
}
if self.heart_state_name(state) != "uprooted" {
self.heart_tick(&mut heart, key, state)?;
}
self.world
.block_entities
.insert(key, BlockEntity::CreakingHeart(heart));
}
self.scan_for_hearts();
Ok(())
}
fn heart_tick(
&mut self,
heart: &mut CreakingHeart,
key: Pos,
state: BlockStateId,
) -> Result<()> {
heart.ticks_existed += 1;
let output = self.heart_output(heart, key);
if output != heart.output_signal {
heart.output_signal = output;
self.container_changed(key);
}
if heart.emitter > 0 {
if heart.emitter > 50 {
self.heart_emit(heart, key, 1, true);
self.heart_emit(heart, key, 1, false);
}
if heart.emitter % 10 == 0 && heart.emitter_target.is_some() {
if let Some(id) = self.heart_protector(heart)
&& let Some((c, _)) = self.mob_center(id)
{
heart.emitter_target = Some(c);
}
if let Some(target) = heart.emitter_target {
let center = [
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
f64::from(key.2) + 0.5,
];
let progress = 0.2 + 0.8 * f64::from(100 - heart.emitter) / 100.0;
let at = [
(center[0] - target[0]) * progress + target[0],
(center[1] - target[1]) * progress + target[1],
(center[2] - target[2]) * progress + target[2],
];
let volume = heart.emitter as f32 / 2.0 / 100.0 + 0.5;
self.audio
.play("minecraft:block.creaking_heart.hurt", Some(at), volume, 1.0);
}
}
heart.emitter -= 1;
}
let ticker = heart.ticker;
heart.ticker -= 1;
if ticker >= 0 {
return Ok(());
}
heart.ticker = self.world.random.next_int_bound(5).unwrap_or(0) + 20;
// updateCreakingState: logs gone and no creaking means uprooted.
let active = self.creaking_active();
let has_logs = self.with_level(|b, level, ticks| {
b.creaking_heart_has_logs(level, ticks, BlockPos::new(key.0, key.1, key.2), state)
});
let wanted = if !has_logs && heart.creaking.is_none() {
"uprooted"
} else if active {
"awake"
} else {
"dormant"
};
let mut current = self.heart_state_name(state);
if wanted != current
&& let Some(next) = self.heart_with_state(state, wanted)
{
self.level_set([key.0, key.1, key.2], next)?;
current = wanted.to_owned();
if wanted == "uprooted" {
return Ok(());
}
}
if heart.creaking.is_none() {
if current == "awake" && self.spawning_monsters() {
let near = self.player.as_ref().is_some_and(|p| {
let (dx, dy, dz) = (
p.position.x - (f64::from(key.0) + 0.5),
p.position.y - (f64::from(key.1) + 0.5),
p.position.z - (f64::from(key.2) + 0.5),
);
dx * dx + dy * dy + dz * dz < 32.0 * 32.0
}) && !self.spectator();
if near && let Some(id) = self.spawn_protector(key) {
let uuid = self.uuid_for(id);
heart.creaking = Some((Some(id), uuid));
heart.ticks_existed = 0;
let at = self.mob_center(id).map(|(c, _)| c);
self.audio
.play("minecraft:entity.creaking.spawn", at, 1.0, 1.0);
self.audio.play(
"minecraft:block.creaking_heart.spawn",
Some([
f64::from(key.0) + 0.5,
f64::from(key.1) + 0.5,
f64::from(key.2) + 0.5,
]),
1.0,
1.0,
);
}
}
} else if let Some(id) = self.heart_protector(heart) {
let persistent = self
.mobs
.iter()
.find(|m| m.id == id)
.is_some_and(|m| m.persistent);
let eye = self.player_view().map(|v| v.eye);
let stuck = self
.mobs
.iter_mut()
.find(|m| m.id == id)
.is_some_and(|m| creaking::player_is_stuck(m, eye));
if (!active && !persistent)
|| self.heart_distance_to_creaking(id, key) > TOO_FAR
|| stuck
{
self.heart_remove_protector(heart, false);
}
}
Ok(())
}
fn heart_with_state(&self, state: BlockStateId, wanted: &str) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
s.properties
.insert("creaking_heart_state".to_owned(), wanted.to_owned());
self.res.assets.registry.resolve(&s).ok()
}
/// `ServerLevel.isSpawningMonsters`.
fn spawning_monsters(&self) -> bool {
self.ui.difficulty != 0 && self.ui.rules.bool("spawn_monsters")
}
/// `EnvironmentAttributes.CREAKING_ACTIVE`.
pub(super) fn creaking_active(&mut self) -> bool {
self.with_level(|b, level, ticks| b.creaking_active(level, ticks))
}
/// Hearts that came with generated or loaded chunks get their block
/// entity (`newBlockEntity`) the first time their chunk is seen.
fn scan_for_hearts(&mut self) {
let Some(heart) = self
.res
.assets
.registry
.default_state("minecraft:creaking_heart")
else {
return;
};
let keys: Vec<(i32, i32)> = self
.world
.chunks
.iter()
.filter(|(k, c)| c.lit && !self.creaking.scanned.contains(k))
.map(|(k, _)| *k)
.collect();
for key in keys {
self.creaking.scanned.insert(key);
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
continue;
};
let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name;
let _ = heart;
for (si, section) in chunk.sections.iter().enumerate() {
if section.is_uniform(0) {
continue;
}
for i in 0..4096 {
let id = section.get(i);
if name(id) != "minecraft:creaking_heart" {
continue;
}
let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32);
let pos = (
key.0 * 16 + lx,
horizon_client::chunk::MIN_Y + si as i32 * 16 + ly,
key.1 * 16 + lz,
);
self.world
.block_entities
.entry(pos)
.or_insert_with(|| BlockEntity::CreakingHeart(Box::default()));
}
}
}
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
self.creaking.scanned.retain(|k| loaded.contains(k));
}
}
/// What the creaking code remembers between ticks.
#[derive(Default)]
pub(super) struct CreakingState {
/// Chunks already scanned for heart blocks.
scanned: HashSet<(i32, i32)>,
}
+119 -4
View File
@@ -93,7 +93,8 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
.full_collision
}
}
fn seen(m: &Mob) -> Seen {
fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
let villager = m.species() == Species::Villager;
Seen {
id: m.id,
species: m.species(),
@@ -102,7 +103,12 @@ fn seen(m: &Mob) -> Seen {
eye_y: m.eye_y(),
alive: m.alive(),
baby: m.is_baby(),
in_love: m.extra.in_love > 0,
// A villager is "in love" when it is willing to breed (`canBreed`).
in_love: if villager {
horizon_client::mobs::villager::can_breed(m)
} else {
m.extra.in_love > 0
},
tame: m.extra.tame,
hostile: m.hostile(),
target: m.ai.target,
@@ -115,6 +121,13 @@ fn seen(m: &Mob) -> Seen {
bed: (m.species() == Species::Villager)
.then_some(m.extra.bed)
.flatten(),
active_raid: horizon_client::mobs::raider::has_active_raid(m),
player_rep: match (villager, player) {
(true, Some(uuid)) => {
horizon_client::mobs::villager::ext(m).map_or(0, |e| e.gossips.reputation(uuid))
}
_ => 0,
},
}
}
impl Game<'_> {
@@ -150,6 +163,8 @@ impl Game<'_> {
gold_armor: self.wearing_gold(),
hurt_by: self.player_hurt_by(),
last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)),
hero: self.potions.effects.get("hero_of_the_village").is_some(),
uuid: self.level.player_uuid.unwrap_or_default(),
})
}
/// Biome facts at a position for finalizeSpawn and variant rules.
@@ -191,6 +206,17 @@ impl Game<'_> {
}
/// Create a mob of `kind` at a position, finalized like a natural spawn.
pub(super) fn spawn_mob(&mut self, kind: &str, at: [f64; 3], persistent: bool) -> Option<u32> {
self.spawn_mob_for(kind, at, persistent, false)
}
/// `spawn_mob` for a patrol or raid (`EntitySpawnReason.PATROL` / `EVENT`),
/// which never rolls a patrol leader.
pub(super) fn spawn_mob_for(
&mut self,
kind: &str,
at: [f64; 3],
persistent: bool,
scripted: bool,
) -> Option<u32> {
let kind = if kind.contains(':') {
kind.to_owned()
} else {
@@ -208,6 +234,14 @@ impl Game<'_> {
);
let difficulty = self.local_difficulty(at);
spawning::finalize(&mut mob, &facts, &difficulty);
if !scripted {
let reason = if persistent {
horizon_client::mobs::raider::Reason::Other
} else {
horizon_client::mobs::raider::Reason::Natural
};
horizon_client::mobs::raider::finalize(&mut mob, reason);
}
let id = mob.id;
self.mobs.push(mob);
Some(id)
@@ -259,13 +293,28 @@ impl Game<'_> {
"on_ground": m.on_ground,
"variant": m.extra.variant,
"color": m.extra.color,
"villager": horizon_client::mobs::villager::ext(m).map(|e| serde_json::json!({
"food_level": e.food_level,
"inventory": e.inventory.iter().map(|s| format!("{}x{}", s.count, s.item)).collect::<Vec<_>>(),
"gossips": e.gossips.len(),
"last_slept": e.last_slept,
"raid": e.raid,
})),
"raider": horizon_client::mobs::raider::state(m).map(|s| serde_json::json!({
"raid": s.raid_id,
"wave": s.wave,
"leader": s.patrol_leader,
"patrolling": s.patrolling,
"patrol_target": s.patrol_target,
"vehicle": s.vehicle,
})),
})
})
.collect();
serde_json::json!({ "count": self.mobs.len(), "near": list, "projectiles": self.creatures.projectiles.len() })
}
/// Highest motion-blocking (no leaves) block + 1 (Heightmap MOTION_BLOCKING_NO_LEAVES).
fn motion_top(&self, x: i32, z: i32) -> i32 {
pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 {
let top = if self.dim == Dim::Nether { 127 } else { 319 };
for y in (horizon_client::chunk::MIN_Y..=top).rev() {
let f = self.res.facts.get(self.world.block(x, y, z));
@@ -602,7 +651,10 @@ impl Game<'_> {
}
self.tick_inhabited();
self.spawn_natural();
let snapshot: Vec<Seen> = self.mobs.iter().map(seen).collect();
self.tick_patrol_spawner();
self.tick_raids();
let uuid = self.level.player_uuid;
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
let mut events = Vec::new();
let mut mobs = std::mem::take(&mut self.mobs);
let mut dead = Vec::new();
@@ -625,6 +677,9 @@ impl Game<'_> {
push_apart(&mut mobs);
}
self.mobs.append(&mut mobs);
self.sync_riders();
self.villager_reputation_tick();
self.villager_pickups();
for m in dead {
self.mob_died(&m);
}
@@ -645,6 +700,8 @@ impl Game<'_> {
let view = self.mob_entity(m);
self.trigger_entity("minecraft:player_killed_entity", "entity", &view);
}
self.raider_died(m, by_player);
self.villager_murdered(m, by_player);
let held = self.held().cloned();
let pos = [m.position.x, m.position.y + 0.5, m.position.z];
if !m.is_baby() {
@@ -692,6 +749,7 @@ impl Game<'_> {
for stack in m.extra.items.clone().into_iter().flatten() {
self.spawn_item(stack, pos, [0.0, 0.2, 0.0], 10);
}
self.raider_death_loot(m, pos);
let worn = if horizon_client::mobs::equine::is_equine(m.species()) {
[None, None, None, None]
} else {
@@ -707,6 +765,7 @@ impl Game<'_> {
// Vexes never drop their sword.
if let Some(item) = &item
&& by_player
&& &**item != horizon_client::mobs::raider::BANNER
&& m.species() != Species::Vex
&& self.world.random.next_float() < 0.085
{
@@ -974,6 +1033,36 @@ impl Game<'_> {
}
},
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
MobEvent::CreakingHurt {
home,
by_player,
id,
} => self.creaking_hurt(home, id, by_player),
MobEvent::CreakingTearDown { center, spread } => {
self.creaking_tear_down(center, spread)
}
MobEvent::VillagerMeet { mob, other } => self.villager_meet(mob, other),
MobEvent::VillagerBirth { parent, partner } => self.villager_birth(parent, partner),
MobEvent::GolemCheck { mob, needed } => self.villager_golem_check(mob, needed),
MobEvent::Firework { at, color, flight } => {
self.villager_firework(at, color, flight)
}
MobEvent::ThrowGift { table, from, to } => self.throw_gift(&table, from, to),
MobEvent::PatrolTarget { mob, target } => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
horizon_client::mobs::raider::set_patrol_target(m, target);
}
}
MobEvent::RaiderTarget {
mob,
target,
aggressive,
} => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.ai.target = Some(target);
m.ai.aggressive |= aggressive;
}
}
MobEvent::GiftLoot { table, at } => {
let drops =
self.res
@@ -1551,6 +1640,32 @@ impl Game<'_> {
}
}
}
// A witch's healing potions reach the raiders around the splash.
if matches!(
*effect,
"minecraft:instant_health" | "minecraft:regeneration"
) {
let center = at;
for m in &mut self.mobs {
let d2 = m.position.distance_squared(center);
if !m.alive()
|| d2 >= 16.0
|| !horizon_client::mobs::raider::is_raider(m.species())
{
continue;
}
let scale = 1.0 - d2.sqrt() / 4.0;
if *effect == "minecraft:instant_health" {
let heal = (4 << *amplifier) as f64 * scale;
m.health = (m.health + heal as f32).min(m.attrs.max_health);
} else {
let t = (f64::from(*ticks) * scale + 0.5) as i32;
if t > 20 {
m.add_effect(effect, t, *amplifier);
}
}
}
}
self.audio.play(
"minecraft:entity.splash_potion.break",
Some(atp),
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1842,7 +1842,8 @@ impl Game<'_> {
/// The boss bar (`BossHealthOverlay`): name and the pink progress bar.
pub(super) fn draw_boss_bar(&self, batch: &mut HudBatch) {
let dragon = self.dragon.as_ref().filter(|_| self.dim == Dim::End);
self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
let y = self.draw_wither_bars(batch, if dragon.is_some() { 31.0 } else { 12.0 });
self.draw_raid_bar(batch, y);
let Some(d) = dragon else {
return;
};
+28 -6
View File
@@ -24,6 +24,9 @@ pub(super) struct Rocket {
explosions: Vec<FireworkExplosion>,
/// Boosting the player (attachedToEntity).
attached: bool,
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
/// the first block it hits.
angled: bool,
icon: Option<String>,
}
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
@@ -34,7 +37,7 @@ fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
.unwrap_or((1, Vec::new()))
}
impl Game<'_> {
fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
pub(super) fn new_rocket(&mut self, at: Vec3, stack: &ItemStack, attached: bool) -> Rocket {
let (flight, explosions) = fireworks_of(stack);
let r = &mut self.world.random;
let tri = |r: &mut horizon_core::random::LegacyRandom| {
@@ -52,6 +55,7 @@ impl Game<'_> {
lifetime,
explosions,
attached,
angled: false,
icon: Some("item/firework_rocket".into()),
}
}
@@ -73,6 +77,13 @@ impl Game<'_> {
self.swing_arm();
true
}
/// `FireworkRocketItem.asProjectile` shot out of a dispenser.
pub(super) fn launch_dispensed_rocket(&mut self, at: Vec3, velocity: Vec3, stack: &ItemStack) {
let mut rocket = self.new_rocket(at, stack, false);
rocket.velocity = velocity;
rocket.angled = true;
self.rockets.push(rocket);
}
/// `FireworkRocketItem.use` while gliding: a rocket attached to the player.
pub(super) fn boost_firework(&mut self, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:firework_rocket"
@@ -118,12 +129,23 @@ impl Game<'_> {
Vec3::new(r.position.x - h, r.position.y, r.position.z - h),
Vec3::new(r.position.x + h, r.position.y + 2.0 * h, r.position.z + h),
);
let wanted = Vec3::new(
r.velocity.x * 1.15,
r.velocity.y + 0.04,
r.velocity.z * 1.15,
);
let wanted = if r.angled {
r.velocity
} else {
Vec3::new(
r.velocity.x * 1.15,
r.velocity.y + 0.04,
r.velocity.z * 1.15,
)
};
if let Ok(moved) = scene.resolve(bounds, wanted, 0.0, false) {
let blocked = (moved.x - wanted.x).abs() > 1e-7
|| (moved.y - wanted.y).abs() > 1e-7
|| (moved.z - wanted.z).abs() > 1e-7;
if r.angled && blocked {
// hitTargetOrDeflectSelf: explode on the block.
r.life = r.lifetime;
}
let horizontal =
(moved.x - wanted.x).abs() > 1e-7 || (moved.z - wanted.z).abs() > 1e-7;
r.position = Vec3::new(
+82
View File
@@ -0,0 +1,82 @@
//! Building golems from blocks (`CarvedPumpkinBlock.trySpawnGolem`): a carved
//! pumpkin or jack o'lantern on two snow blocks makes a snow golem, and on a
//! T of four iron blocks (arms along X or Z, nothing beside the legs) an iron
//! golem. Players placing the pumpkin and dispensers share it.
use super::Game;
use horizon_client::Result;
impl Game<'_> {
fn golem_block(&self, p: [i32; 3]) -> &str {
let state = self.world.block(p[0], p[1], p[2]);
&self.res.facts.get(state).name
}
fn is_golem_head(&self, p: [i32; 3]) -> bool {
matches!(
self.golem_block(p),
"minecraft:carved_pumpkin" | "minecraft:jack_o_lantern"
)
}
/// The blocks of the golem whose head is at `head` and its spawn base
/// (`BlockPattern.find`), snow golems first.
fn find_golem(&self, head: [i32; 3]) -> Option<(&'static str, Vec<[i32; 3]>, [i32; 3])> {
let below = |n: i32| [head[0], head[1] - n, head[2]];
if self.golem_block(below(1)) == "minecraft:snow_block"
&& self.golem_block(below(2)) == "minecraft:snow_block"
{
return Some((
"minecraft:snow_golem",
vec![head, below(1), below(2)],
below(2),
));
}
for (ax, az) in [(1, 0), (0, 1)] {
let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s];
let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block");
let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2]));
if arms
&& self.golem_block(side(0, 2)) == "minecraft:iron_block"
&& [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2)))
{
let mut blocks = vec![head];
blocks.extend((-1..=1).map(|s| side(s, 1)));
blocks.push(side(0, 2));
return Some(("minecraft:iron_golem", blocks, side(0, 2)));
}
}
None
}
/// `CarvedPumpkinBlock.canSpawnGolem`.
pub(super) fn can_spawn_golem(&self, head: [i32; 3]) -> bool {
self.find_golem(head).is_some()
}
/// `CarvedPumpkinBlock.trySpawnGolem`, after a pumpkin was placed.
pub(super) fn check_golem_spawn(&mut self, head: [i32; 3]) -> Result<()> {
if !self.is_golem_head(head) {
return Ok(());
}
let Some((kind, blocks, base)) = self.find_golem(head) else {
return Ok(());
};
for p in blocks {
let state = self.world.block(p[0], p[1], p[2]);
self.destroy_particles(p, state);
self.level_set(p, self.world.air)?;
}
let at = [
f64::from(base[0]) + 0.5,
f64::from(base[1]) + 0.05,
f64::from(base[2]) + 0.5,
];
if let Some(id) = self.spawn_mob(kind, at, false)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
m.previous_yaw = 0.0;
m.previous_body_yaw = 0.0;
m.previous_head_yaw = 0.0;
}
Ok(())
}
}
+4 -381
View File
@@ -8,15 +8,10 @@ mod crafter;
use horizon_client::{
Result,
containers::BlockEntity,
entities::Arrow,
items::{ItemStack, Items},
world::World,
};
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
use horizon_world::{level::Behaviours, registry::BlockStateId};
type Pos = (i32, i32, i32);
@@ -76,11 +71,6 @@ impl View {
}
}
thread_local! {
/// Entity-owned randomness (projectile spread), separate from the level random.
static ENTITY_RANDOM: std::cell::RefCell<LegacyRandom> = std::cell::RefCell::new(LegacyRandom::new(0x0d15_7e45));
}
fn dir_from_name(name: &str) -> Option<Direction> {
Some(match name {
"down" => Direction::Down,
@@ -612,14 +602,8 @@ impl Game<'_> {
odds += 1;
}
}
let center = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 0.5,
f64::from(pos.z) + 0.5,
];
let Some(slot) = slot else {
self.audio
.play("minecraft:block.dispenser.fail", Some(center), 1.0, 1.2);
self.dispenser_event(1001, key, 0);
return Ok(());
};
let Some(facing) = self
@@ -635,7 +619,7 @@ impl Game<'_> {
let target = offset(key, facing);
let remaining = if dropper {
match self.containers().view(target, false) {
None => self.default_dispense(key, facing, stack),
None => self.dispense_default(key, facing, stack),
Some(into) => {
let one = ItemStack {
count: 1,
@@ -657,7 +641,7 @@ impl Game<'_> {
}
}
} else {
self.dispense_behaviour(key, facing, stack)?
self.dispense_item(key, facing, stack)?
};
if let Some(entry) = self.slot_mut_at(&view, slot) {
*entry = remaining;
@@ -665,367 +649,6 @@ impl Game<'_> {
self.container_changed(key);
Ok(())
}
/// `DefaultDispenseItemBehavior.dispense`: drop one item, click and smoke.
fn default_dispense(
&mut self,
pos: Pos,
facing: Direction,
mut stack: ItemStack,
) -> Option<ItemStack> {
let one = ItemStack {
count: 1,
..stack.clone()
};
stack.count -= 1;
self.spawn_dispensed(pos, facing, one, 6);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
(stack.count > 0).then_some(stack)
}
fn dispenser_sound(&mut self, pos: Pos, sound: &str, pitch: f32) {
let center = [
f64::from(pos.0) + 0.5,
f64::from(pos.1) + 0.5,
f64::from(pos.2) + 0.5,
];
self.audio.play(sound, Some(center), 1.0, pitch);
}
/// `DefaultDispenseItemBehavior.spawnItem` at `DispenserBlock.getDispensePosition`.
fn spawn_dispensed(&mut self, pos: Pos, facing: Direction, stack: ItemStack, accuracy: i32) {
let s = step(facing);
let mut at = [
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]),
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
];
at[1] -= if s[1] != 0 { 0.125 } else { 0.156_25 };
let r = &mut self.world.random;
// new ItemEntity(level, x, y, z, stack): its default motion draws first.
let _ = (r.next_double(), r.next_double());
let pow = r.next_double() * 0.1 + 0.2;
let spread = 0.017_227_5 * f64::from(accuracy);
let v = [
r.triangle(f64::from(s[0]) * pow, spread),
r.triangle(0.2, spread),
r.triangle(f64::from(s[2]) * pow, spread),
];
self.spawn_item(stack, at, v, 0);
}
/// `DefaultDispenseItemBehavior.consumeWithRemainder`.
fn consume_with_remainder(
&mut self,
pos: Pos,
facing: Direction,
mut stack: ItemStack,
remainder: ItemStack,
) -> Option<ItemStack> {
stack.count -= 1;
if stack.count == 0 {
return Some(remainder);
}
// DispenserBlockEntity.insertItem, then drop what does not fit.
let mut rest = remainder;
if let Some(view) = self.containers().view(pos, false) {
let max = self.containers().max_stack(&rest);
for i in 0..view.len() {
let Some(entry) = self.slot_mut_at(&view, i) else {
continue;
};
match entry {
None => {
let n = rest.count.min(max);
*entry = Some(ItemStack {
count: n,
..rest.clone()
});
rest.count -= n;
}
Some(e) if e.item == rest.item && e.damage == rest.damage => {
let n = rest.count.min(max.saturating_sub(e.count));
e.count += n;
rest.count -= n;
}
Some(_) => {}
}
if rest.count == 0 {
break;
}
}
}
if rest.count > 0 {
self.spawn_dispensed(pos, facing, rest, 6);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
}
Some(stack)
}
/// `DispenserBlock.getDispenseMethod(..).dispense(source, stack)`.
fn dispense_behaviour(
&mut self,
pos: Pos,
facing: Direction,
stack: ItemStack,
) -> Result<Option<ItemStack>> {
let target = offset(pos, facing);
let target_pos = BlockPos::new(target.0, target.1, target.2);
let item = stack.item.to_string();
let result = match item.as_str() {
"minecraft:bone_meal" => {
let grown = self.with_level(|b, level, ticks| {
b.grow_crop(level, ticks, target_pos)
|| b.grow_water_plant(level, ticks, target_pos, None)
});
self.process_level_events()?;
if grown {
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.audio.play(
"minecraft:item.bone_meal.use",
Some([
f64::from(target.0) + 0.5,
f64::from(target.1) + 0.5,
f64::from(target.2) + 0.5,
]),
1.0,
1.0,
);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
} else {
self.dispenser_sound(pos, "minecraft:block.dispenser.fail", 1.2);
Some(stack)
}
}
"minecraft:tnt" => {
self.spawn_primed_tnt(target_pos, false);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
}
"minecraft:flint_and_steel" => {
let target_state = self.world.block(target.0, target.1, target.2);
let target_name = self.res.facts.get(target_state).name.clone();
let fire = self.res.assets.registry.default_state("minecraft:fire");
let success = if self.res.facts.is_air(target_state)
&& let Some(fire) = fire
&& self
.with_level(|b, level, ticks| b.can_survive(level, ticks, target_pos, fire))
{
self.level_set([target.0, target.1, target.2], fire)?;
true
} else if &*target_name == "minecraft:tnt" {
self.spawn_primed_tnt(target_pos, false);
self.with_level(|b, level, ticks| {
b.remove_block(level, ticks, target_pos, false)
});
self.process_level_events()?;
true
} else if self.containers().prop(target_state, "lit") == Some("false")
&& (target_name.contains("campfire") || target_name.contains("candle"))
&& self.containers().prop(target_state, "waterlogged") != Some("true")
{
let lit = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("lit".into(), "true".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(lit) = lit {
self.level_set([target.0, target.1, target.2], lit)?;
}
true
} else {
false
};
self.dispenser_sound(
pos,
if success {
"minecraft:block.dispenser.dispense"
} else {
"minecraft:block.dispenser.fail"
},
if success { 1.0 } else { 1.2 },
);
let mut stack = stack;
if success {
stack.damage += 1;
let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage);
if max > 0 && stack.damage >= max {
return Ok(None);
}
}
Some(stack)
}
"minecraft:water_bucket" | "minecraft:lava_bucket" => {
let fluid = if item == "minecraft:water_bucket" {
"minecraft:water"
} else {
"minecraft:lava"
};
let target_state = self.world.block(target.0, target.1, target.2);
let f = self.res.facts.get(target_state).clone();
let waterloggable = item == "minecraft:water_bucket"
&& self.containers().prop(target_state, "waterlogged") == Some("false");
if waterloggable {
let wet = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("waterlogged".into(), "true".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(wet) = wet {
self.level_set([target.0, target.1, target.2], wet)?;
}
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: "minecraft:bucket".into(),
count: 1,
damage: 0,
extra: None,
},
)
} else if (self.res.facts.is_air(target_state) || f.replaceable)
&& !(f.fluid_level == 8 && !f.fluid_falling && &*f.name == fluid)
&& let Some(source) = self.res.assets.registry.default_state(fluid)
{
self.level_set([target.0, target.1, target.2], source)?;
let sound = if fluid == "minecraft:water" {
"minecraft:item.bucket.empty"
} else {
"minecraft:item.bucket.empty_lava"
};
self.audio.play(
sound,
Some([
f64::from(target.0) + 0.5,
f64::from(target.1) + 0.5,
f64::from(target.2) + 0.5,
]),
1.0,
1.0,
);
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: "minecraft:bucket".into(),
count: 1,
damage: 0,
extra: None,
},
)
} else {
self.default_dispense(pos, facing, stack)
}
}
"minecraft:bucket" => {
let target_state = self.world.block(target.0, target.1, target.2);
let f = self.res.facts.get(target_state).clone();
let picked = if f.waterlogged
&& self.containers().prop(target_state, "waterlogged") == Some("true")
{
let dry = self
.res
.assets
.registry
.state(target_state)
.cloned()
.and_then(|mut s| {
s.properties.insert("waterlogged".into(), "false".into());
self.res.assets.registry.resolve(&s).ok()
});
if let Some(dry) = dry {
self.level_set([target.0, target.1, target.2], dry)?;
}
Some("minecraft:water_bucket")
} else if f.fluid_level == 8
&& !f.fluid_falling
&& matches!(&*f.name, "minecraft:water" | "minecraft:lava")
{
self.level_set([target.0, target.1, target.2], self.world.air)?;
Some(if &*f.name == "minecraft:water" {
"minecraft:water_bucket"
} else {
"minecraft:lava_bucket"
})
} else if &*f.name == "minecraft:powder_snow" {
self.level_set([target.0, target.1, target.2], self.world.air)?;
Some("minecraft:powder_snow_bucket")
} else {
None
};
match picked {
Some(filled) => {
self.dispenser_sound(pos, "minecraft:block.dispenser.dispense", 1.0);
self.consume_with_remainder(
pos,
facing,
stack,
ItemStack {
item: filled.into(),
count: 1,
damage: 0,
extra: None,
},
)
}
None => self.default_dispense(pos, facing, stack),
}
}
"minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:tipped_arrow" => {
// ProjectileDispenseBehavior: power 1.1, uncertainty 6, from 0.7 ahead and 0.1 up.
let s = step(facing);
let at = Vec3::new(
f64::from(pos.0) + 0.5 + 0.7 * f64::from(s[0]),
f64::from(pos.1) + 0.5 + 0.7 * f64::from(s[1]) + 0.1,
f64::from(pos.2) + 0.5 + 0.7 * f64::from(s[2]),
);
let spread = 0.017_227_5 * 6.0;
let v = ENTITY_RANDOM.with(|r| {
let r = &mut *r.borrow_mut();
[
(f64::from(s[0]) + r.triangle(0.0, spread)) * 1.1,
(f64::from(s[1]) + r.triangle(0.0, spread)) * 1.1,
(f64::from(s[2]) + r.triangle(0.0, spread)) * 1.1,
]
});
self.arrows.push(Arrow {
from_player: true,
critical: false,
position: at,
previous: at,
velocity: Vec3::new(v[0], v[1], v[2]),
stuck: false,
age: 0,
base_damage: 2.0,
});
self.dispenser_sound(pos, "minecraft:block.dispenser.launch", 1.2);
Some(ItemStack {
count: stack.count - 1,
..stack
})
.filter(|s| s.count > 0)
}
_ => self.default_dispense(pos, facing, stack),
};
Ok(result)
}
}
// ---- hopper, dispenser and dropper screens ----
+5 -5
View File
@@ -90,7 +90,7 @@ const SEAT: f64 = 0.1875 - 0.6;
pub(super) const CART_KEY_Y: i32 = -100_000;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Shape {
pub(super) enum Shape {
NorthSouth,
EastWest,
AscendingEast,
@@ -117,7 +117,7 @@ impl Shape {
_ => Self::NorthSouth,
}
}
fn is_slope(self) -> bool {
pub(super) fn is_slope(self) -> bool {
matches!(
self,
Self::AscendingEast | Self::AscendingWest | Self::AscendingNorth | Self::AscendingSouth
@@ -141,9 +141,9 @@ impl Shape {
}
}
}
struct Rail {
pub(super) struct Rail {
name: Arc<str>,
shape: Shape,
pub(super) shape: Shape,
powered: bool,
}
impl Minecart {
@@ -203,7 +203,7 @@ impl CartModels {
}
}
impl Game<'_> {
fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option<Rail> {
let state = self.world.block(x, y, z);
let name = self.res.facts.get(state).name.clone();
if !matches!(
+9 -1
View File
@@ -269,9 +269,17 @@ impl Game<'_> {
}
self.persist.raw.insert(id, tag);
}
fn uuid_for(&mut self, id: u32) -> [i32; 4] {
pub(super) fn uuid_for(&mut self, id: u32) -> [i32; 4] {
*self.persist.uuids.entry(id).or_insert_with(random_uuid)
}
/// The loaded mob with a saved UUID.
pub(super) fn mob_id_for_uuid(&self, uuid: [i32; 4]) -> Option<u32> {
self.persist
.uuids
.iter()
.find(|(id, u)| **u == uuid && self.mobs.iter().any(|m| m.id == **id && !m.removed))
.map(|(id, _)| *id)
}
/// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`).
fn state_from_nbt(&self, tag: &Tag) -> Option<BlockStateId> {
let registry = self.res.assets.registry;
+77 -21
View File
@@ -19,6 +19,18 @@ pub(super) struct ThrownPotion {
velocity: Vec3,
age: u32,
}
impl Game<'_> {
/// A splash potion, lingering potion or experience bottle in flight (the
/// player's throws and dispensers both end up here).
pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) {
self.potions.thrown.push(ThrownPotion {
stack,
position,
velocity,
age: 0,
});
}
}
/// Effects, thrown potions and the attribute modifiers last applied.
#[derive(Default)]
pub(super) struct PotionState {
@@ -40,21 +52,25 @@ impl Game<'_> {
/// Right-click with a potion, splash/lingering potion or glass bottle.
pub(super) fn use_potion_item(&mut self, stack: &ItemStack) -> horizon_client::Result<bool> {
match &*stack.item {
"minecraft:potion" => {
"minecraft:potion" | "minecraft:ominous_bottle" => {
if self.using.is_none() {
self.using = Some((self.selected, 0));
}
Ok(true)
}
"minecraft:splash_potion" | "minecraft:lingering_potion" => {
"minecraft:splash_potion"
| "minecraft:lingering_potion"
| "minecraft:experience_bottle" => {
let Some(eye) = self.eye_position() else {
return Ok(true);
};
let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8);
let sound = if &*stack.item == "minecraft:splash_potion" {
"minecraft:entity.splash_potion.throw"
} else {
"minecraft:entity.lingering_potion.throw"
let (sound, power) = match &*stack.item {
"minecraft:splash_potion" => ("minecraft:entity.splash_potion.throw", 0.5),
"minecraft:experience_bottle" => {
("minecraft:entity.experience_bottle.throw", 0.7)
}
_ => ("minecraft:entity.lingering_potion.throw", 0.5),
};
self.audio.play(sound, Some(eye), 0.5, pitch);
// Projectile.shootFromRotation(xRot, yRot, -20, 0.5, 1.0).
@@ -74,9 +90,9 @@ impl Game<'_> {
let r = &mut self.world.random;
let mut jitter = || r.triangle(0.0, 0.0172275);
let v = Vec3::new(
(f64::from(dir[0]) / l + jitter()) * 0.5,
(f64::from(dir[1]) / l + jitter()) * 0.5,
(f64::from(dir[2]) / l + jitter()) * 0.5,
(f64::from(dir[0]) / l + jitter()) * power,
(f64::from(dir[1]) / l + jitter()) * power,
(f64::from(dir[2]) / l + jitter()) * power,
);
let pv = self.player.as_ref().map_or(Vec3::ZERO, |p| p.velocity);
let on_ground = self.player.as_ref().is_some_and(|p| p.ground.on_ground);
@@ -85,15 +101,14 @@ impl Game<'_> {
v.y + if on_ground { 0.0 } else { pv.y },
v.z + pv.z,
);
self.potions.thrown.push(ThrownPotion {
stack: ItemStack {
self.launch_thrown(
ItemStack {
count: 1,
..stack.clone()
},
position: Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
velocity: v,
age: 0,
});
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
v,
);
self.swing_arm();
self.consume_held();
Ok(true)
@@ -137,7 +152,8 @@ impl Game<'_> {
}
/// Drinking a potion while right-click is held; true when handled.
pub(super) fn tick_drinking(&mut self, slot: usize, ticks: u32, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:potion" {
let ominous = &*stack.item == "minecraft:ominous_bottle";
if &*stack.item != "minecraft:potion" && !ominous {
return false;
}
let ticks = ticks + 1;
@@ -154,6 +170,10 @@ impl Game<'_> {
return true;
}
self.using = None;
if ominous {
self.drink_ominous_bottle(slot, stack);
return true;
}
let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0);
for e in lasting {
self.potions.effects.add(e);
@@ -326,19 +346,25 @@ impl Game<'_> {
}
t.position = next;
// ThrowableItemProjectile: drag 0.99 then gravity 0.05.
// ThrownExperienceBottle.getDefaultGravity is 0.07.
let gravity = if &*t.stack.item == "minecraft:experience_bottle" {
0.07
} else {
0.05
};
t.velocity = Vec3::new(
t.velocity.x * 0.99,
t.velocity.y * 0.99 - 0.05,
t.velocity.y * 0.99 - gravity,
t.velocity.z * 0.99,
);
t.age < 1200 && t.position.y > -128.0
});
// ThrownItemRenderer stand-in: a short-lived sprite of the potion at its position.
for t in &thrown {
let sprite = if &*t.stack.item == "minecraft:lingering_potion" {
"item/lingering_potion"
} else {
"item/splash_potion"
let sprite = match &*t.stack.item {
"minecraft:lingering_potion" => "item/lingering_potion",
"minecraft:experience_bottle" => "item/experience_bottle",
_ => "item/splash_potion",
};
let mut fixed = horizon_core::random::LegacyRandom::new(0);
let mut p = horizon_client::particles::Particle::terrain(
@@ -362,6 +388,36 @@ impl Game<'_> {
}
/// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash).
fn splash(&mut self, stack: &ItemStack, at: Vec3) {
if &*stack.item == "minecraft:experience_bottle" {
// ThrownExperienceBottle.onHit: the water-coloured splash (level
// event 2002) and 3 to 11 experience.
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.audio.play(
"minecraft:entity.splash_potion.break",
Some([at.x, at.y, at.z]),
1.0,
pitch,
);
for _ in 0..8 {
let v = [
f64::from(self.world.random.next_float() - 0.5) * 0.3,
0.2,
f64::from(self.world.random.next_float() - 0.5) * 0.3,
];
let p = horizon_client::particles::Particle::terrain(
&mut self.world.random,
[at.x, at.y, at.z],
v,
"item/splash_potion".into(),
0x38_5DC6,
);
self.particles.push(p);
}
let r = &mut self.world.random;
let value = 3 + r.next_int_bound(5).unwrap_or(0) + r.next_int_bound(5).unwrap_or(0);
self.spawn_orbs([at.x, at.y, at.z], value as u32);
return;
}
let lingering = &*stack.item == "minecraft:lingering_potion";
let event = if lingering {
"minecraft:entity.lingering_potion.break"
File diff suppressed because it is too large Load Diff
@@ -1772,6 +1772,10 @@ impl Game<'_> {
let e: &Enchantments = &self.res.stations.enchantments;
let props = e.props(&stack.item);
let mut rarity = props.map_or("common", |p| p.rarity.as_str());
// The ominous banner's rarity component.
if stack.data().is_some_and(|d| d.ominous_banner) {
rarity = "uncommon";
}
if !stack.enchantments().is_empty() {
rarity = match rarity {
"common" | "uncommon" => "rare",
@@ -1787,6 +1791,9 @@ impl Game<'_> {
};
let name = if let Some(n) = stack.custom_name() {
n.to_owned()
} else if stack.data().is_some_and(|d| d.ominous_banner) {
e.translate("block.minecraft.ominous_banner")
.map_or_else(|| "Ominous Banner".to_owned(), str::to_owned)
} else if stack.data().and_then(|d| d.potion.as_ref()).is_some()
|| stack.item.ends_with("potion")
|| &*stack.item == "minecraft:tipped_arrow"
+29 -1
View File
@@ -148,7 +148,13 @@ impl Game<'_> {
}));
}
let m = &self.mobs[index];
let trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
let mut trade = m.extra.trade.as_deref().cloned().unwrap_or_default();
// Villager.updateSpecialPrices: reputation and Hero of the Village.
if species == Species::Villager {
let reputation = self.villager_reputation(m.id);
merchant::update_special_prices(&mut trade.offers, reputation, self.hero_amplifier());
}
let m = &self.mobs[index];
if trade.offers.is_empty() {
let mut events = Vec::new();
villager::set_unhappy(&mut self.mobs[index], &mut events);
@@ -190,6 +196,10 @@ impl Game<'_> {
let trade = m.extra.trade.get_or_insert_default();
trade.xp = state.xp;
trade.offers = state.offers.clone();
// setTradingPlayer(null) resets the special prices.
for offer in &mut trade.offers {
offer.special_price_diff = 0;
}
}
/// Opens a merchant menu for a villager (or a generated one for tests).
pub(super) fn open_merchant(&mut self, profession: &str, variant: &str, level: i32) {
@@ -244,6 +254,16 @@ impl Game<'_> {
.map(|p| [p.position.x, p.position.y + 0.5, p.position.z]);
self.audio
.play("minecraft:entity.villager.yes", at, 1.0, 1.0);
// Villager.notifyTrade: the villager remembers the trade.
let villager = s
.merchant
.as_ref()
.filter(|m| m.progress())
.and_then(|m| m.mob);
if let Some(mob) = villager {
self.villager_traded(mob);
}
let Some(m) = s.merchant.as_mut() else { return };
if level_up {
let (profession, variant, level) =
(m.profession.clone(), m.variant.clone(), m.level + 1);
@@ -254,6 +274,14 @@ impl Game<'_> {
}
pop += 5;
}
// The prices follow the villager's new reputation.
if let Some(mob) = villager {
let reputation = self.villager_reputation(mob);
let hero = self.hero_amplifier();
if let Some(m) = s.merchant.as_mut() {
merchant::update_special_prices(&mut m.offers, reputation, hero);
}
}
if offer.reward_exp
&& let Some(at) = at
{
+467
View File
@@ -0,0 +1,467 @@
//! What villagers do with each other and with the player: gossip and
//! reputation, sharing food and wares, picking up dropped items, making
//! babies, calling iron golems and the prices they ask.
use super::Game;
use horizon_client::{
gossip::{self, GossipType},
items::ItemStack,
mobs::{Mob, Species, spawning, villager},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
}
/// `SpawnUtil.Strategy.LEGACY_IRON_GOLEM`: what a golem will not land on.
fn golem_floor_ok(name: &str) -> bool {
!matches!(
name,
"minecraft:cobweb"
| "minecraft:cactus"
| "minecraft:glass_pane"
| "minecraft:conduit"
| "minecraft:ice"
| "minecraft:tnt"
| "minecraft:glowstone"
| "minecraft:beacon"
| "minecraft:sea_lantern"
| "minecraft:frosted_ice"
| "minecraft:tinted_glass"
| "minecraft:glass"
) && !name.ends_with("_stained_glass_pane")
&& !name.ends_with("_stained_glass")
&& !name.ends_with("leaves")
}
impl Game<'_> {
fn villager_index(&self, id: u32) -> Option<usize> {
self.mobs
.iter()
.position(|m| m.id == id && m.species() == Species::Villager)
}
fn item_max_stack(&self, item: &str) -> u32 {
self.res.items.get(item).map_or(64, |i| i.max_stack)
}
/// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward
/// a point.
fn villager_throw(&mut self, from: Vec3, eye: f64, to: Vec3, stack: ItemStack) {
let at = [from.x, eye - 0.3, from.z];
let d = Vec3::new(to.x - from.x, to.y - from.y, to.z - from.z).normalize();
self.spawn_item(stack, at, [d.x * 0.3, d.y * 0.3, d.z * 0.3], 10);
}
/// `TradeWithVillager.tick` for one pair: gossip (at most once in 1200
/// ticks for both), then surplus food and wanted wares tossed over.
pub(super) fn villager_meet(&mut self, a: u32, b: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(a), self.villager_index(b)) else {
return;
};
let now = self.world.game_time;
let items = &self.res.items;
let max = |item: &str| items.get(item).map_or(64, |i| i.max_stack);
// Villager.gossip: both must be past their cool-down.
let ready = {
let ea = villager::ext(&self.mobs[ia]);
let eb = villager::ext(&self.mobs[ib]);
ea.is_none_or(|e| e.can_gossip(now)) && eb.is_none_or(|e| e.can_gossip(now))
};
let mut golem = false;
if ready {
let source = villager::ext(&self.mobs[ib]).cloned().unwrap_or_default();
let me = &mut self.mobs[ia];
let mut random = me.random.clone();
let e = villager::ext_mut(me);
e.gossips.transfer_from(&source.gossips, &mut random, 10);
e.last_gossip_time = now;
me.random = random;
villager::ext_mut(&mut self.mobs[ib]).last_gossip_time = now;
golem = true;
}
// Surplus food goes to a hungry neighbour (farmers hand it to anyone).
let farmer = villager::is_farmer(&self.mobs[ia]);
let (from, eye, to) = (
self.mobs[ia].position,
self.mobs[ia].eye_y(),
self.mobs[ib].position,
);
let wants_more = villager::ext(&self.mobs[ib]).is_none_or(|e| e.wants_more_food());
let excess = villager::ext(&self.mobs[ia]).is_some_and(|e| e.has_excess_food());
let mut thrown = Vec::new();
if excess
&& (farmer || wants_more)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| villager::food_points(&s.item) > 0, max)
{
thrown.push(s);
}
// A farmer's wheat.
if farmer
&& villager::ext(&self.mobs[ia]).is_some_and(|e| e.count_item("minecraft:wheat") > 32)
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
{
thrown.push(s);
}
// Wares the neighbour's profession asks for and ours does not.
let theirs = villager::requested_items(&self.mobs[ib]);
let mine = villager::requested_items(&self.mobs[ia]);
let wanted: Vec<&str> = theirs
.iter()
.copied()
.filter(|i| !mine.contains(i))
.collect();
if !wanted.is_empty()
&& let Some(s) = villager::ext_mut(&mut self.mobs[ia])
.take_half_stack(|s| wanted.contains(&&*s.item), max)
{
thrown.push(s);
}
for stack in thrown {
self.villager_throw(from, eye, to, stack);
}
if golem {
self.villager_golem_check(a, 5);
}
}
/// `Villager.spawnGolemIfNeeded`: when enough villagers nearby that
/// slept recently and saw no golem agree, an iron golem appears.
pub(super) fn villager_golem_check(&mut self, id: u32, needed: usize) {
let Some(i) = self.villager_index(id) else {
return;
};
let now = self.world.game_time;
if !villager::ext(&self.mobs[i]).is_some_and(|e| e.wants_golem(now)) {
return;
}
let at = self.mobs[i].position;
let nearby: Vec<usize> = self
.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.species() == Species::Villager
&& m.alive()
&& (m.position.x - at.x).abs() <= 10.0
&& (m.position.y - at.y).abs() <= 10.0
&& (m.position.z - at.z).abs() <= 10.0
})
.map(|(j, _)| j)
.collect();
let wanting = nearby
.iter()
.filter(|j| villager::ext(&self.mobs[**j]).is_some_and(|e| e.wants_golem(now)))
.take(5)
.count();
if wanting < needed {
return;
}
if self.try_spawn_iron_golem(block_of(at)) {
for j in nearby {
villager::ext_mut(&mut self.mobs[j]).golem_until = now + 599;
}
}
}
/// `SpawnUtil.trySpawnMob(IRON_GOLEM, ..., 10 attempts, 8 across, 6 up
/// and down, LEGACY_IRON_GOLEM)`.
fn try_spawn_iron_golem(&mut self, start: [i32; 3]) -> bool {
for _ in 0..10 {
let r = &mut self.world.random;
let dx = r.next_int_bound(17).unwrap_or(8) - 8;
let dz = r.next_int_bound(17).unwrap_or(8) - 8;
let (x, z) = (start[0] + dx, start[2] + dz);
let mut y = start[1] + 6;
let mut above = self.world.block(x, y, z);
let mut found = None;
for _ in 0..=12 {
y -= 1;
let here = self.world.block(x, y, z);
let f = self.res.facts.get(here);
let above_f = self.res.facts.get(above);
let air_or_liquid = self.res.facts.is_air(above)
|| above_f.fluid != horizon_client::blocks::Fluid::None;
let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID
!= 0
|| f.name.as_ref() == "minecraft:powder_snow";
if golem_floor_ok(&f.name) && air_or_liquid && solid {
found = Some(y + 1);
break;
}
above = here;
}
let Some(y) = found else { continue };
// IronGolem.checkSpawnRules: a floor and three free blocks.
let free = |g: &Self, yy: i32| {
g.res.mob_data.state(g.world.block(x, yy, z)).flags
& horizon_client::mobs::data::VALID_EMPTY_SPAWN
!= 0
};
if !(0..4).all(|k| free(self, y + k)) {
continue;
}
let at = [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5];
if let Some(id) = self.spawn_mob_for("minecraft:iron_golem", at, false, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
let sound = m.kind.sounds[0];
if !sound.is_empty() {
let at = m.center();
self.audio
.play(&format!("minecraft:{sound}"), Some(at), 1.0, 1.0);
}
return true;
}
}
false
}
/// `VillagerMakeLove.tryToGiveBirth`: both eat, a free bed within 48
/// blocks is taken for the child, who is a baby villager of one of
/// three villager types.
pub(super) fn villager_birth(&mut self, parent: u32, partner: u32) {
let (Some(ia), Some(ib)) = (self.villager_index(parent), self.villager_index(partner))
else {
return;
};
villager::ext_mut(&mut self.mobs[ia]).eat_and_digest();
villager::ext_mut(&mut self.mobs[ib]).eat_and_digest();
let from = self.mobs[ia].position;
let angry = |g: &mut Self| {
for i in [ia, ib] {
let p = g.mobs[i].position;
g.particles_at("angry_villager", [p.x, p.y + 1.8, p.z]);
}
};
let Some(bed) = self.take_vacant_bed(block_of(from)) else {
angry(self);
return;
};
// Villager.getBreedOffspring: half the biome's type, a quarter each parent's.
let roll = self.mobs[ia].random.next_double();
let kind_of = |m: &Mob| m.extra.variant;
let facts = self.biome_facts(
from.x.floor() as i32,
from.y.floor() as i32,
from.z.floor() as i32,
);
let variant = if roll < 0.5 {
spawning::villager_type(&facts)
} else if roll < 0.75 {
kind_of(&self.mobs[ia])
} else {
kind_of(&self.mobs[ib])
};
let Some(id) =
self.spawn_mob_for("minecraft:villager", [from.x, from.y, from.z], true, true)
else {
return;
};
self.mobs[ia].extra.age = 6000;
self.mobs[ib].extra.age = 6000;
if let Some(child) = self.mobs.iter_mut().find(|m| m.id == id) {
child.extra.variant = variant;
child.extra.variant2 = villager::NONE;
child.extra.age = -24000;
child.extra.bed = Some(bed);
}
self.particles_at("heart", [from.x, from.y + 1.8, from.z]);
}
/// `PoiManager.take(HOME, ..., 48)`: the nearest unclaimed bed head.
fn take_vacant_bed(&self, from: [i32; 3]) -> Option<[i32; 3]> {
let claimed: Vec<[i32; 3]> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Villager)
.filter_map(|m| m.extra.bed)
.collect();
let mut known: HashMap<u32, bool> = HashMap::new();
let mut best: Option<(i32, [i32; 3])> = None;
for y in from[1] - 8..=from[1] + 8 {
for z in from[2] - 48..=from[2] + 48 {
for x in from[0] - 48..=from[0] + 48 {
let state = self.world.block(x, y, z);
if self.res.facts.is_air(state) {
continue;
}
let free_head = *known.entry(state.0).or_insert_with(|| {
self.res.facts.get(state).name.ends_with("_bed")
&& self.res.assets.registry.state(state).is_some_and(|s| {
s.properties.get("part").map(String::as_str) == Some("head")
&& s.properties.get("occupied").map(String::as_str)
!= Some("true")
})
});
let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2);
if free_head
&& d <= 48 * 48
&& !claimed.contains(&[x, y, z])
&& best.is_none_or(|(b, _)| d < b)
{
best = Some((d, [x, y, z]));
}
}
}
}
best.map(|(_, p)| p)
}
fn particles_at(&mut self, kind: &'static str, at: [f64; 3]) {
if let Some(ty) = horizon_client::particles::ParticleType::from_name(kind) {
let options = horizon_client::particles::ParticleOptions::simple(ty);
self.particles.add(&options, at, [0.0; 3]);
}
}
/// `Mob.aiStep` item pickup for villagers (`InventoryCarrier`): food,
/// seeds and what their profession wants, from within a block.
pub(super) fn villager_pickups(&mut self) {
if self.dropped.is_empty() || !self.ui.rules.bool("mob_griefing") {
return;
}
let picks_up = self
.res
.items
.item_tags
.get("minecraft:villager_picks_up")
.cloned();
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Villager || !m.alive() {
continue;
}
let (pos, half) = (m.position, f64::from(m.width()) / 2.0 + 1.0);
let top = f64::from(m.height());
let requested = villager::requested_items(m);
let mut j = 0;
while j < self.dropped.len() {
let e = &self.dropped[j];
let near = (e.position.x - pos.x).abs() <= half
&& (e.position.z - pos.z).abs() <= half
&& e.position.y >= pos.y - 0.25
&& e.position.y <= pos.y + top;
let item = e.stack.item.clone();
let wants = villager::food_points(&item) > 0
|| picks_up.as_ref().is_some_and(|t| t.contains(&*item))
|| requested.contains(&&*item);
if !near || e.pickup_delay > 0 || !wants {
j += 1;
continue;
}
let max = self.item_max_stack(&item);
let stack = self.dropped[j].stack.clone();
if !villager::ext_mut(&mut self.mobs[i]).can_add(&stack, max) {
j += 1;
continue;
}
let rest = villager::ext_mut(&mut self.mobs[i]).add_item(stack, max);
match rest {
None => {
self.dropped.remove(j);
}
Some(rest) => {
self.dropped[j].stack.count = rest.count;
j += 1;
}
}
}
}
}
/// `Villager.setLastHurtByMob` and `ServerLevel.onReputationEvent`: a hit
/// from the player counts against it with the villager that was hit.
pub(super) fn villager_reputation_tick(&mut self) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let mut angry = Vec::new();
for m in &mut self.mobs {
if m.species() != Species::Villager
|| m.ai.last_hurt_by != Some(horizon_client::mobs::Who::Player)
{
continue;
}
let time = m.ai.last_hurt_by_time;
let alive = m.alive();
let at = m.position;
let e = villager::ext_mut(m);
if e.hurt_seen != time {
e.hurt_seen = time;
e.gossips.add(
uuid,
GossipType::MinorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
if alive {
angry.push(at);
}
}
}
for at in angry {
self.particles_at("angry_villager", [at.x, at.y + 1.8, at.z]);
}
}
/// `Villager.tellWitnessesThatIWasMurdered`: the villagers that saw a
/// player kill one remember it as a major wrong.
pub(super) fn villager_murdered(&mut self, victim: &Mob, by_player: bool) {
if victim.species() != Species::Villager || !by_player {
return;
}
let Some(uuid) = self.level.player_uuid else {
return;
};
let eye = Vec3::new(victim.position.x, victim.eye_y(), victim.position.z);
let witnesses: Vec<usize> = {
let w = self.mob_world_base(&[]);
self.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
m.id != victim.id
&& m.species() == Species::Villager
&& m.alive()
&& (m.position.x - victim.position.x).abs() <= 16.0
&& (m.position.y - victim.position.y).abs() <= 16.0
&& (m.position.z - victim.position.z).abs() <= 16.0
&& w.line_of_sight(eye, Vec3::new(m.position.x, m.eye_y(), m.position.z))
})
.map(|(i, _)| i)
.collect()
};
for i in witnesses {
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::MajorNegative,
gossip::REPUTATION_CHANGE_PER_EVENT,
);
}
}
/// `ReputationEventType.TRADE`: each trade earns a little trust.
pub(super) fn villager_traded(&mut self, id: u32) {
let Some(uuid) = self.level.player_uuid else {
return;
};
let Some(i) = self.villager_index(id) else {
return;
};
villager::ext_mut(&mut self.mobs[i]).gossips.add(
uuid,
GossipType::Trading,
gossip::REPUTATION_CHANGE_PER_TRADE,
);
let p = self.mobs[i].position;
self.particles_at("happy_villager", [p.x, p.y + 1.8, p.z]);
}
/// `Villager.getPlayerReputation` of the local player.
pub(super) fn villager_reputation(&self, id: u32) -> i32 {
let Some(uuid) = self.level.player_uuid else {
return 0;
};
self.villager_index(id)
.and_then(|i| villager::ext(&self.mobs[i]))
.map_or(0, |e| e.gossips.reputation(uuid))
}
/// The Hero of the Village amplifier of the player, if any.
pub(super) fn hero_amplifier(&self) -> Option<i32> {
self.potions.effects.amplifier("hero_of_the_village")
}
}
+3 -2
View File
@@ -75,9 +75,9 @@ impl Game<'_> {
Ok(())
}
/// The wither boss bars (purple, below the dragon's), within range.
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) {
pub(super) fn draw_wither_bars(&self, batch: &mut HudBatch, mut y: f32) -> f32 {
let Some(p) = self.player.as_ref() else {
return;
return y;
};
let atlas = &self.res.atlas;
for m in self
@@ -117,6 +117,7 @@ impl Game<'_> {
);
y += 19.0;
}
y
}
pub(super) fn wither_near(&self) -> bool {
self.player.as_ref().is_some_and(|p| {
+386
View File
@@ -0,0 +1,386 @@
//! Villager gossip (`GossipContainer` and `GossipType`): what a villager
//! remembers about each player, how it fades by the day, how it spreads from
//! villager to villager and the reputation it adds up to.
use horizon_core::random::{LegacyRandom, RandomSource};
use horizon_world::nbt::Tag;
use std::collections::BTreeMap;
/// `ReputationEventType` amounts.
pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25;
pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20;
pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2;
/// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten.
const DISCARD_THRESHOLD: i32 = 2;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum GossipType {
MajorNegative,
MinorNegative,
MinorPositive,
MajorPositive,
Trading,
}
impl GossipType {
pub const ALL: [Self; 5] = [
Self::MajorNegative,
Self::MinorNegative,
Self::MinorPositive,
Self::MajorPositive,
Self::Trading,
];
pub fn id(self) -> &'static str {
match self {
Self::MajorNegative => "major_negative",
Self::MinorNegative => "minor_negative",
Self::MinorPositive => "minor_positive",
Self::MajorPositive => "major_positive",
Self::Trading => "trading",
}
}
pub fn from_id(id: &str) -> Option<Self> {
Self::ALL.into_iter().find(|t| t.id() == id)
}
fn index(self) -> usize {
self as usize
}
pub fn weight(self) -> i32 {
match self {
Self::MajorNegative => -5,
Self::MinorNegative => -1,
Self::MinorPositive => 1,
Self::MajorPositive => 5,
Self::Trading => 1,
}
}
pub fn max(self) -> i32 {
match self {
Self::MajorNegative => 100,
Self::MinorNegative => 200,
Self::MinorPositive | Self::Trading => 25,
Self::MajorPositive => 20,
}
}
pub fn decay_per_day(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 1,
Self::MajorPositive => 0,
Self::Trading => 2,
}
}
pub fn decay_per_transfer(self) -> i32 {
match self {
Self::MajorNegative => 10,
Self::MinorNegative => 20,
Self::MinorPositive => 5,
Self::MajorPositive | Self::Trading => 20,
}
}
}
/// A UUID as four ints.
pub type Target = [i32; 4];
/// One gossip entry (`GossipContainer.GossipEntry`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Entry {
target: Target,
kind: GossipType,
value: i32,
}
impl Entry {
fn weighted(self) -> i32 {
self.value * self.kind.weight()
}
}
/// `GossipContainer`: per target, the value of each gossip type (0: none).
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Gossips {
map: BTreeMap<Target, [i32; 5]>,
}
impl Gossips {
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
pub fn len(&self) -> usize {
self.map.len()
}
pub fn clear(&mut self) {
self.map.clear();
}
pub fn get(&self, target: Target, kind: GossipType) -> i32 {
self.map.get(&target).map_or(0, |e| e[kind.index()])
}
/// `getReputation`: the weighted sum of every type for a target.
pub fn reputation(&self, target: Target) -> i32 {
self.map.get(&target).map_or(0, |e| {
GossipType::ALL
.into_iter()
.map(|t| e[t.index()] * t.weight())
.sum()
})
}
/// How many targets have a gossip of `kind` whose weighted value passes `test`.
pub fn count_for_type(&self, kind: GossipType, test: impl Fn(f64) -> bool) -> usize {
self.map
.values()
.filter(|e| test(f64::from(e[kind.index()] * kind.weight())))
.count()
}
/// `add`: sums up to the type's maximum and forgets values below 2.
pub fn add(&mut self, target: Target, kind: GossipType, amount: i32) {
let entries = self.map.entry(target).or_insert([0; 5]);
let old = entries[kind.index()];
entries[kind.index()] = if old == 0 {
amount
} else {
let sum = old + amount;
if sum > kind.max() {
kind.max().max(old)
} else {
sum
}
};
let value = entries[kind.index()];
if value > kind.max() {
entries[kind.index()] = kind.max();
}
if value < DISCARD_THRESHOLD {
entries[kind.index()] = 0;
}
if entries.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
pub fn remove(&mut self, target: Target, kind: GossipType) {
if let Some(e) = self.map.get_mut(&target) {
e[kind.index()] = 0;
if e.iter().all(|v| *v == 0) {
self.map.remove(&target);
}
}
}
/// `decay` (once per day): every type loses its daily amount.
pub fn decay(&mut self) {
self.map.retain(|_, e| {
for kind in GossipType::ALL {
let v = e[kind.index()];
if v == 0 {
continue;
}
let next = v - kind.decay_per_day();
e[kind.index()] = if next < DISCARD_THRESHOLD { 0 } else { next };
}
e.iter().any(|v| *v != 0)
});
}
fn unpack(&self) -> Vec<Entry> {
let mut out = Vec::new();
for (target, e) in &self.map {
for kind in GossipType::ALL {
if e[kind.index()] != 0 {
out.push(Entry {
target: *target,
kind,
value: e[kind.index()],
});
}
}
}
out
}
/// `selectGossipsForTransfer`: `max_count` picks weighted by magnitude,
/// duplicates counted once.
fn select_for_transfer(&self, random: &mut LegacyRandom, max_count: usize) -> Vec<Entry> {
let entries = self.unpack();
if entries.is_empty() {
return Vec::new();
}
let mut ends = Vec::with_capacity(entries.len());
let mut total = 0;
for e in &entries {
total += e.weighted().abs();
ends.push(total - 1);
}
let mut picked: Vec<usize> = Vec::new();
for _ in 0..max_count {
let choice = random.next_int_bound(total).unwrap_or(0);
// Arrays.binarySearch on the strictly increasing range ends.
let index = match ends.binary_search(&choice) {
Ok(i) | Err(i) => i,
};
if !picked.contains(&index) {
picked.push(index);
}
}
picked.into_iter().map(|i| entries[i]).collect()
}
/// `transferFrom`: gossip heard from another villager, weakened by the
/// retelling. Returns how many gossips were picked.
pub fn transfer_from(
&mut self,
source: &Gossips,
random: &mut LegacyRandom,
max_count: usize,
) -> usize {
let picked = source.select_for_transfer(random, max_count);
for g in &picked {
let decayed = g.value - g.kind.decay_per_transfer();
if decayed >= DISCARD_THRESHOLD {
let e = self.map.entry(g.target).or_insert([0; 5]);
let slot = &mut e[g.kind.index()];
*slot = (*slot).max(decayed);
}
}
picked.len()
}
pub fn to_nbt(&self) -> Tag {
Tag::List(
self.unpack()
.into_iter()
.map(|e| {
Tag::compound([
("Target", Tag::IntArray(e.target.to_vec())),
("Type", Tag::String(e.kind.id().into())),
("Value", Tag::Int(e.value)),
])
})
.collect(),
)
}
pub fn from_nbt(tag: &Tag) -> Self {
let mut out = Self::default();
let Tag::List(list) = tag else { return out };
for g in list {
let target = match g.get("Target") {
Some(Tag::IntArray(v)) if v.len() == 4 => [v[0], v[1], v[2], v[3]],
_ => continue,
};
let kind = match g.get("Type") {
Some(Tag::String(s)) => GossipType::from_id(&s.to_string_lossy()),
_ => None,
};
let value = match g.get("Value") {
Some(Tag::Int(v)) => *v,
_ => continue,
};
if let Some(kind) = kind
&& value > 0
{
out.map.entry(target).or_insert([0; 5])[kind.index()] = value;
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
const PLAYER: Target = [1, 2, 3, 4];
const OTHER: Target = [5, 6, 7, 8];
#[test]
fn reputation_adds_up_weighted() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MinorPositive, 25);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.add(PLAYER, GossipType::Trading, 2);
// 25 + 20 * 5 + 2
assert_eq!(g.reputation(PLAYER), 127);
g.add(PLAYER, GossipType::MajorNegative, 25);
assert_eq!(g.reputation(PLAYER), 127 - 125);
assert_eq!(g.reputation(OTHER), 0);
}
#[test]
fn values_stop_at_their_maximum() {
let mut g = Gossips::default();
for _ in 0..10 {
g.add(PLAYER, GossipType::MajorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 100);
// The minor negative cap is 200: eight hits of 25 fill it.
for _ in 0..12 {
g.add(PLAYER, GossipType::MinorNegative, 25);
}
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 200);
assert_eq!(g.reputation(PLAYER), -500 - 200);
}
#[test]
fn small_values_are_forgotten() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::Trading, 1);
assert!(g.is_empty());
g.add(PLAYER, GossipType::Trading, 2);
assert_eq!(g.get(PLAYER, GossipType::Trading), 2);
g.remove(PLAYER, GossipType::Trading);
assert!(g.is_empty());
}
#[test]
fn gossip_decays_by_the_day() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::MinorNegative, 25);
g.add(PLAYER, GossipType::MinorPositive, 3);
g.add(PLAYER, GossipType::MajorPositive, 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 15);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 2);
// Major positive gossip never fades.
assert_eq!(g.get(PLAYER, GossipType::MajorPositive), 20);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 5);
assert_eq!(g.get(PLAYER, GossipType::MinorNegative), 0);
assert_eq!(g.get(PLAYER, GossipType::MinorPositive), 0);
g.decay();
assert_eq!(g.get(PLAYER, GossipType::MajorNegative), 0);
assert_eq!(g.len(), 1);
}
#[test]
fn retold_gossip_is_weaker() {
let mut source = Gossips::default();
source.add(PLAYER, GossipType::MajorNegative, 25);
source.add(OTHER, GossipType::Trading, 25);
let mut heard = Gossips::default();
let mut random = LegacyRandom::new(11);
let n = heard.transfer_from(&source, &mut random, 50);
assert!((1..=2).contains(&n));
// 25 - 10 per transfer for major negative, 25 - 20 for trading.
let major = heard.get(PLAYER, GossipType::MajorNegative);
let trading = heard.get(OTHER, GossipType::Trading);
assert!(major == 0 || major == 15);
assert!(trading == 0 || trading == 5);
assert!(major + trading > 0);
// A second hearing keeps the stronger value.
heard.transfer_from(&source, &mut random, 50);
assert!(heard.get(PLAYER, GossipType::MajorNegative) <= 15);
// Gossip too weak to survive retelling is dropped.
let mut faint = Gossips::default();
faint.add(PLAYER, GossipType::Trading, 5);
let mut heard = Gossips::default();
heard.transfer_from(&faint, &mut random, 10);
assert!(heard.is_empty());
}
#[test]
fn gossip_round_trips_through_nbt() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(PLAYER, GossipType::Trading, 2);
g.add(OTHER, GossipType::MinorPositive, 25);
assert_eq!(Gossips::from_nbt(&g.to_nbt()), g);
}
#[test]
fn counts_by_type() {
let mut g = Gossips::default();
g.add(PLAYER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::MajorNegative, 25);
g.add(OTHER, GossipType::Trading, 25);
assert_eq!(g.count_for_type(GossipType::MajorNegative, |v| v < 0.0), 2);
assert_eq!(g.count_for_type(GossipType::Trading, |v| v < 0.0), 0);
}
}
+71
View File
@@ -39,7 +39,23 @@ pub struct StackData {
pub banner_patterns: Vec<crate::banner::BannerLayer>,
/// `minecraft:base_color` (a shield's dye).
pub base_color: Option<Arc<str>>,
/// The raid captain's banner: `minecraft:banner_patterns` with the
/// ominous layers, its item name, rarity and hidden tooltip.
pub ominous_banner: bool,
/// `minecraft:ominous_bottle_amplifier` (None: the item's default, 0).
pub ominous_amplifier: Option<u8>,
}
/// `Raid.getBannerComponentPatch`: the ominous banner's pattern layers.
pub const OMINOUS_LAYERS: [(&str, &str); 8] = [
("rhombus", "cyan"),
("stripe_bottom", "light_gray"),
("stripe_center", "gray"),
("border", "light_gray"),
("stripe_middle", "black"),
("half_horizontal", "light_gray"),
("circle", "light_gray"),
("border", "black"),
];
/// `WrittenBookContent` with the pages as plain text.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct WrittenBook {
@@ -343,6 +359,39 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option<Tag> {
Tag::List(d.charged.iter().map(crate::save::item_to_nbt).collect()),
));
}
if d.ominous_banner {
let layer = |pattern: &str, color: &str| {
Tag::compound([
(
"pattern",
Tag::String(format!("minecraft:{pattern}").as_str().into()),
),
("color", Tag::String(color.into())),
])
};
entries.push((
"minecraft:banner_patterns",
Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()),
));
entries.push((
"minecraft:tooltip_display",
Tag::compound([(
"hidden_components",
Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]),
)]),
));
entries.push((
"minecraft:item_name",
Tag::compound([(
"translate",
Tag::String("block.minecraft.ominous_banner".into()),
)]),
));
entries.push(("minecraft:rarity", Tag::String("uncommon".into())));
}
if let Some(a) = d.ominous_amplifier {
entries.push(("minecraft:ominous_bottle_amplifier", Tag::Int(i32::from(a))));
}
if !d.container.is_empty() {
let slots = d
.container
@@ -453,6 +502,15 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option<Box<StackData
.collect(),
_ => Vec::new(),
},
ominous_banner: matches!(
c.get("minecraft:banner_patterns"),
Some(Tag::List(layers)) if layers.first().is_some_and(|l|
l.get("pattern").and_then(string).as_deref() == Some("minecraft:rhombus"))
),
ominous_amplifier: c
.get("minecraft:ominous_bottle_amplifier")
.and_then(int)
.map(|v| v.clamp(0, 4) as u8),
trim: c.get("minecraft:trim").and_then(|t| {
Some((
Arc::from(t.get("material").and_then(string)?.as_str()),
@@ -532,6 +590,19 @@ mod tests {
assert_eq!(extra.banner_patterns, stack.data().unwrap().banner_patterns);
}
#[test]
fn ominous_items_round_trip() {
let mut banner = ItemStack::new("minecraft:white_banner", 1);
banner.data_mut().ominous_banner = true;
let tag = encode_components(&banner).unwrap();
assert!(tag.get("minecraft:banner_patterns").is_some());
let (_, back) = decode_components(Some(&tag));
assert!(back.unwrap().ominous_banner);
let mut bottle = ItemStack::new("minecraft:ominous_bottle", 1);
bottle.data_mut().ominous_amplifier = Some(3);
let (_, back) = decode_components(encode_components(&bottle).as_ref());
assert_eq!(back.unwrap().ominous_amplifier, Some(3));
}
#[test]
fn plain_stacks_have_no_components() {
let stack = ItemStack::new("minecraft:stone", 64);
+25
View File
@@ -53,6 +53,10 @@ pub struct ItemInfo {
pub glider: bool,
/// `equippable.swappable` and `equip_sound`.
pub swappable: bool,
/// `equippable.dispensable` (dispensers may put it on an entity).
pub equip_dispensable: bool,
/// `equippable.allowed_entities` resolved to entity type ids; None allows all.
pub equip_allowed: Option<HashSet<String>>,
pub equip_sound: Option<String>,
/// `jukebox_playable`: the jukebox song it plays.
pub jukebox_song: Option<String>,
@@ -251,6 +255,13 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
})
.collect())
}
/// An entity type id or `#tag` as the set of entity type ids it names.
fn entity_spec(tags: &HashMap<String, HashSet<String>>, spec: &str) -> HashSet<String> {
match spec.strip_prefix('#') {
Some(tag) => tags.get(tag).cloned().unwrap_or_default(),
None => HashSet::from([spec.to_owned()]),
}
}
impl Items {
pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> Result<Self> {
let raw: BTreeMap<String, Value> =
@@ -264,6 +275,7 @@ impl Items {
.or_insert(BlockStateId(i as u32));
}
}
let entity_tags = load_tags(root, "entity_type")?;
let mut items = HashMap::new();
let mut order = Vec::new();
for (name, c) in &raw {
@@ -323,6 +335,19 @@ impl Items {
swappable: c["minecraft:equippable"]["swappable"]
.as_bool()
.unwrap_or(true),
equip_dispensable: c["minecraft:equippable"]["dispensable"]
.as_bool()
.unwrap_or(true),
equip_allowed: match &c["minecraft:equippable"]["allowed_entities"] {
Value::String(spec) => Some(entity_spec(&entity_tags, spec)),
Value::Array(list) => Some(
list.iter()
.filter_map(Value::as_str)
.flat_map(|spec| entity_spec(&entity_tags, spec))
.collect(),
),
_ => None,
},
equip_sound: c["minecraft:equippable"]["equip_sound"]
.as_str()
.map(str::to_owned),
+2
View File
@@ -31,6 +31,7 @@ pub mod fog;
pub mod font;
pub mod gamerules;
pub mod gfx;
pub mod gossip;
pub mod health;
pub mod hud;
pub mod hunger;
@@ -54,6 +55,7 @@ pub mod packs;
pub mod particles;
pub mod pose;
pub mod projectiles;
pub mod raid;
pub mod recipe_book;
pub mod save;
pub mod screen_effects;
+43
View File
@@ -98,6 +98,23 @@ impl Trader {
}
}
/// `Villager.updateSpecialPrices`: the reputation and Hero of the Village
/// discounts of a player, from scratch.
pub fn update_special_prices(offers: &mut [MerchantOffer], reputation: i32, hero: Option<i32>) {
// 0.3F + 0.0625F * amplifier, widened from float.
let hero_modifier = hero.map_or(0.0, |a| f64::from(0.3f32 + 0.0625f32 * a as f32));
for offer in offers {
offer.special_price_diff = 0;
if reputation != 0 {
offer.special_price_diff -= (reputation as f32 * offer.price_multiplier).floor() as i32;
}
if hero_modifier > 0.0 {
let reduction =
(hero_modifier * f64::from(offer.base_cost_a.stack.count)).floor() as i32;
offer.special_price_diff -= reduction.max(1);
}
}
}
/// An `ItemCost`: item and count (component predicates are not used by the
/// 26.3 trade data except for one exact match, kept as the stack's data).
#[derive(Clone, Debug, PartialEq)]
@@ -708,6 +725,32 @@ mod tests {
assert!(!can_level_up(5));
}
#[test]
fn reputation_and_heroes_lower_prices() {
let items = items();
let mut offers = vec![offer(10, None), offer(1, None)];
// Reputation 50 with a 0.2 multiplier: 10 off, floored per offer.
update_special_prices(&mut offers, 50, None);
assert_eq!(offers[0].special_price_diff, -10);
assert_eq!(offers[0].cost_a_count(&items), 1);
assert_eq!(offers[1].special_price_diff, -10);
// Bad reputation raises the price (-30 * 0.2 = -6 floors to -6).
update_special_prices(&mut offers, -30, None);
assert_eq!(offers[0].special_price_diff, 6);
assert_eq!(offers[0].cost_a_count(&items), 16);
// Hero of the Village I: 0.3 * 10 = 3 off, at least 1.
update_special_prices(&mut offers, 0, Some(0));
assert_eq!(offers[0].special_price_diff, -3);
assert_eq!(offers[1].special_price_diff, -1);
// Level III: 0.3 + 0.125 = 0.425 -> 4 off a ten emerald price.
update_special_prices(&mut offers, 0, Some(2));
assert_eq!(offers[0].special_price_diff, -4);
// Both stack, from scratch each time.
update_special_prices(&mut offers, 25, Some(0));
assert_eq!(offers[0].special_price_diff, -5 - 3);
update_special_prices(&mut offers, 0, None);
assert_eq!(offers[0].special_price_diff, 0);
}
#[test]
fn offers_follow_the_trade_data() {
let items = items();
+65
View File
@@ -11,6 +11,7 @@ pub mod anim;
pub mod aquatic;
pub mod camel;
pub mod control;
pub mod creaking;
pub mod cube;
pub mod data;
pub mod enderman;
@@ -28,6 +29,7 @@ pub mod nether;
pub mod path;
pub mod phantom;
pub mod piglin;
pub mod raider;
pub mod ravager;
pub mod render;
pub mod shulker;
@@ -433,6 +435,8 @@ pub struct Extra {
/// Dye colour id (sheep wool, collars).
pub color: u8,
pub sheared: bool,
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
@@ -475,6 +479,10 @@ pub struct Extra {
pub meeting: Option<[i32; 3]>,
/// Villager and wandering trader offers and experience.
pub trade: Option<Box<crate::merchant::Trader>>,
/// A raider's patrol and raid state.
pub raider: Option<Box<raider::State>>,
/// A villager's raid activity and gossip.
pub villager: Option<Box<villager::Ext>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -659,11 +667,60 @@ pub enum MobEvent {
kind: DamageKind,
amount: f32,
},
/// Two villagers are close: swap gossip and share food and wares.
VillagerMeet {
mob: u32,
other: u32,
},
/// Two villagers make a baby.
VillagerBirth {
parent: u32,
partner: u32,
},
/// A villager asks whether enough neighbours want an iron golem.
GolemCheck {
mob: u32,
needed: usize,
},
/// A villager launches a firework rocket (celebrating a won raid).
Firework {
at: [f64; 3],
color: usize,
flight: u8,
},
/// A villager throws a hero's gift (a loot table) toward the player.
ThrowGift {
table: String,
from: [f64; 3],
to: [f64; 3],
},
/// A patrol leader hands its patrol target to a companion.
PatrolTarget {
mob: u32,
target: [i32; 3],
},
/// A raider is told to attack (`HoldGroundAttackGoal` shouting).
RaiderTarget {
mob: u32,
target: Who,
aggressive: bool,
},
/// Drop the loot of a gift table (chicken eggs, armadillo scutes).
GiftLoot {
table: &'static str,
at: [f64; 3],
},
/// A creaking bound to the heart at `home` was hurt (`creakingHurt` when a player did it).
CreakingHurt {
home: [i32; 3],
by_player: bool,
id: u32,
},
/// `Creaking.tearDown`: crumbling particles around the creaking.
CreakingTearDown {
center: [f64; 3],
spread: [f64; 3],
},
}
/// How a spawned-by-kind mob should be set up.
#[derive(Clone, Debug, Default)]
@@ -703,6 +760,10 @@ pub struct Seen {
/// A villager's claimed job site and bed.
pub job: Option<[i32; 3]>,
pub bed: Option<[i32; 3]>,
/// A raider in an active raid.
pub active_raid: bool,
/// A villager's reputation of the player (`getPlayerReputation`).
pub player_rep: i32,
}
/// The player as mobs see it.
#[derive(Clone, Debug)]
@@ -725,6 +786,10 @@ pub struct PlayerView {
pub hurt_by: Option<(Who, i64)>,
/// `getLastHurtMob` and when.
pub last_hurt: Option<(Who, i64)>,
/// The Hero of the Village effect.
pub hero: bool,
/// The player's UUID (villagers' gossip is keyed by it).
pub uuid: [i32; 4],
}
pub struct MobWorld<'a> {
pub world: &'a World,
+26 -1
View File
@@ -87,6 +87,7 @@ pub enum Family {
Wither,
Allay,
Villager,
Creaking,
}
pub fn family(s: Species) -> Family {
use Species as S;
@@ -121,6 +122,7 @@ pub fn family(s: Species) -> Family {
S::Ravager => Family::Ravager,
S::Wither => Family::Wither,
S::Allay => Family::Allay,
S::Creaking => Family::Creaking,
S::Villager => Family::Villager,
S::Piglin | S::PiglinBrute | S::Hoglin | S::Zoglin => Family::Piglin,
S::Horse | S::Donkey | S::Mule | S::SkeletonHorse | S::ZombieHorse | S::Camel => {
@@ -169,7 +171,9 @@ pub fn register(m: &mut Mob) {
Family::Wither => super::wither::register(m),
Family::Allay => super::allay::register(m),
Family::Villager => super::villager::register(m),
Family::Creaking => super::creaking::register(m),
}
super::raider::register(m);
}
/// Mob.tick additions that run before the entity tick (creeper fuse, puffing).
fn pre_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
@@ -251,7 +255,11 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
return false;
}
base_tick(m, w, events);
if m.death_time >= 20 {
if m.death_time >= super::creaking::death_limit(m) {
// Creaking.tickDeath: a heart's creaking crumbles away.
if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) {
super::creaking::tear_down(m, events);
}
return false;
}
ai_step(m, w, events);
@@ -391,6 +399,8 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
Species::Axolotl if !m.fluids.in_water => "entity.axolotl.idle_air",
Species::Bat if m.extra.flag && m.random.next_int_bound(4).unwrap_or(1) != 0 => return,
Species::Allay if m.extra.main_hand.is_some() => "entity.allay.ambient_with_item",
// Creaking.getAmbientSound: silent while awake.
Species::Creaking if m.extra.flag => return,
// Shulker.playAmbientSound: silent while closed.
Species::Shulker if m.extra.counter == 0 => return,
Species::ZombifiedPiglin if m.ai.target.is_some() => "entity.zombified_piglin.angry",
@@ -405,6 +415,9 @@ fn play_ambient(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
/// LivingEntity.aiStep (and Mob/AgeableMob/Animal additions).
fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if super::creaking::is_creaking(m) {
super::creaking::update(m, w, events);
}
if m.ai.no_jump_delay > 0 {
m.ai.no_jump_delay -= 1;
}
@@ -486,6 +499,10 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool {
/// Mob.serverAiStep
fn server_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.ai.no_action_time += 1;
// A creaking looked at stands still.
if super::creaking::is_creaking(m) && !super::creaking::can_move(m) {
return;
}
// A saddled mount follows its rider instead of its goals.
if super::equine::controlled(m) {
super::equine::ridden_step(m);
@@ -587,6 +604,10 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
}
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) {
return true;
}
let despawn = if m.kind.category == "water_ambient" {
64.0
} else {
@@ -664,6 +685,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
match m.species() {
// Allay.hurtServer: its liked player cannot hurt it.
Species::Allay if m.extra.tame && source.attacker == Some(Who::Player) => false,
Species::Creaking => super::creaking::accepts_damage(m, source),
Species::Wither => super::wither::accepts(m, source.kind, source.attacker, false),
Species::Shulker => super::shulker::accepts(m, source),
Species::Enderman => super::enderman::on_damage(m, source),
@@ -707,6 +729,9 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if m.species() == Species::Ravager {
super::ravager::on_attack(m, cx.events);
}
if super::creaking::is_creaking(m) {
super::creaking::on_attack(m, cx.events);
}
let mut amount = m.attrs.attack_damage;
let from = [m.position.x, m.position.y, m.position.z];
let source = Damage::mob(m.id, from);
+2
View File
@@ -9,6 +9,7 @@ use std::f32::consts::PI;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Anim {
Allay,
Creaking,
Camel,
Wither,
Vex,
@@ -346,6 +347,7 @@ pub fn setup(
match m.kind.anim {
Anim::Camel => super::camel::anim(m, s, p, w_anims),
Anim::Allay => super::allay::anim(m, s, p),
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
Anim::Squid | Anim::Fish | Anim::Pufferfish | Anim::Dolphin => {
super::aquatic::anim(m, s, p)
}
+365
View File
@@ -0,0 +1,365 @@
//! Creakings (`Creaking`, `CreakingAi`): they freeze while any player looks at
//! them, wake up when one looks from within 12 blocks, then hunt the nearest
//! visible player and hit every 40 ticks. One bound to a creaking heart takes
//! no damage (it only sways and hurts the heart's resin spreader), dies when
//! the heart no longer protects it and falls apart with the heart.
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{Cx, Float, Goal, LookAtPlayer, MeleeAttack, Stroll, TARGET, goal_clone},
keyframes::Animation,
path::PathType,
};
use crate::containers::BlockEntity;
use horizon_core::{geometry::Vec3, random::RandomSource};
use std::collections::HashMap;
/// `Extra.ints` slots.
const INVULNERABLE: usize = 0;
const ATTACKING: usize = 1;
const STUCK: usize = 2;
const TEARING_DOWN: usize = 3;
const EYES: usize = 4;
const NEXT_FLICKER: usize = 5;
/// `Extra.counter` bits: hurt while protected, and by a player.
const HURT: i32 = 1;
const HURT_BY_PLAYER: i32 = 2;
/// `Creaking.ACTIVATION_RANGE_SQ`.
const ACTIVATION_RANGE_SQ: f64 = 144.0;
/// `Creaking.INVULNERABILITY_ANIMATION_DURATION` and the attack animation.
const INVULNERABILITY_TICKS: i32 = 8;
const ATTACK_TICKS: i32 = 15;
/// `Creaking.TWITCH_DEATH_DURATION`.
const TWITCH_TICKS: i32 = 45;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(2, MeleeAttack::new(1.0, false).interval(40));
g.add(5, Stroll::avoiding_water(0.3));
g.add(6, LookAtPlayer::new(8.0));
m.ai.targets.add(1, HuntPlayer);
}
/// Bound to a heart (`getHomePos() != null`).
pub fn heart_bound(m: &Mob) -> bool {
is_creaking(m) && m.extra.home.is_some()
}
pub fn tearing_down(m: &Mob) -> bool {
is_creaking(m) && m.extra.ints[TEARING_DOWN] != 0
}
/// `Creaking.canMove`: false while a player looks at it.
pub fn can_move(m: &Mob) -> bool {
!m.extra.flag2
}
/// `Creaking.isActive`.
pub fn is_active(m: &Mob) -> bool {
m.extra.flag
}
/// `Creaking.setTransient`: bind to the heart at `pos` and avoid damage.
pub fn set_transient(m: &mut Mob, pos: [i32; 3]) {
m.extra.home = Some(pos);
m.set_malus(PathType::Damaging, 8.0);
m.set_malus(PathType::PowderSnow, 8.0);
m.set_malus(PathType::Lava, 8.0);
m.set_malus(PathType::Fire, 0.0);
m.set_malus(PathType::FireInNeighbor, 0.0);
}
/// `Creaking.setTearingDown`: the heart was broken by someone.
pub fn set_tearing_down(m: &mut Mob) {
m.extra.ints[TEARING_DOWN] = 1;
}
/// `Creaking.hasGlowingEyes` / `isActive`: the eyes layer shows.
pub fn eyes_glowing(m: &Mob) -> bool {
if tearing_down(m) {
m.extra.ints[EYES] != 0
} else {
is_active(m)
}
}
/// Ticks of death animation before the mob is removed (`tickDeath`).
pub fn death_limit(m: &Mob) -> i32 {
if heart_bound(m) && tearing_down(m) {
TWITCH_TICKS + 1
} else {
20
}
}
/// `Creaking.tearDown`: crumbles away.
pub fn tear_down(m: &mut Mob, events: &mut Vec<MobEvent>) {
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
events.push(MobEvent::CreakingTearDown {
center: [
(lo.x + hi.x) / 2.0,
(lo.y + hi.y) / 2.0,
(lo.z + hi.z) / 2.0,
],
spread: [
(hi.x - lo.x) * 0.3,
(hi.y - lo.y) * 0.3,
(hi.z - lo.z) * 0.3,
],
});
m.voice("entity.creaking.death", events);
m.removed = true;
}
/// `Creaking.hurtServer` for a heart-bound creaking: no damage, only the
/// invulnerability animation and the heart's reaction. Returns whether the
/// normal damage path should run.
pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
if !heart_bound(m) || source.kind == DamageKind::Generic {
return true;
}
if source.is_fire() || !m.alive() || m.extra.ints[INVULNERABLE] > 0 {
return false;
}
let by_player = source.attacker == Some(Who::Player);
// The direct entity must be living or a projectile (or a player must be to blame).
let direct = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
| DamageKind::Fireball
| DamageKind::Thorns
);
if !direct && !by_player {
return false;
}
m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS;
m.extra.counter |= HURT | if by_player { HURT_BY_PLAYER } else { 0 };
false
}
/// `Creaking.doHurtTarget` extras: the attack animation and sound.
pub fn on_attack(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.extra.ints[ATTACKING] = ATTACK_TICKS;
m.voice("entity.creaking.attack", events);
}
/// The heart this creaking is bound to protects it (`isProtector`); a link
/// read from a save is trusted until the heart resolves it.
fn protected(m: &Mob, w: &MobWorld) -> bool {
let Some(home) = m.extra.home else {
return true;
};
match w.world.block_entities.get(&(home[0], home[1], home[2])) {
Some(BlockEntity::CreakingHeart(h)) => match h.creaking {
Some((Some(id), _)) => id == m.id,
Some((None, _)) => true,
None => false,
},
_ => false,
}
}
/// `Creaking.tick` and the start of `aiStep`: protection, timers, freezing.
pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
// Creaking.tick: without its heart's protection it dies.
if heart_bound(m) && m.alive() && !protected(m, w) {
m.health = 0.0;
}
for slot in [INVULNERABLE, ATTACKING] {
if m.extra.ints[slot] > 0 {
m.extra.ints[slot] -= 1;
}
}
let age = m.age as f32;
m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age);
m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age);
m.anim.states[2].animate_when(tearing_down(m), age);
if m.extra.counter & HURT != 0 {
// hurtServer: sway, and the heart reacts to a player's hit.
if protected(m, w) {
let by_player = m.extra.counter & HURT_BY_PLAYER != 0;
if let Some(home) = m.extra.home {
events.push(MobEvent::CreakingHurt {
home,
by_player,
id: m.id,
});
}
m.voice("entity.creaking.sway", events);
}
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
}
// checkEyeBlink: the eyes of a creaking falling apart flicker.
if m.death_time > m.extra.ints[NEXT_FLICKER] {
let glowing = m.extra.ints[EYES] != 0;
let (lo, hi) = if glowing {
(2, 8)
} else {
(m.death_time / 4, m.death_time / 2)
};
let span = (hi - lo + 1).max(1);
m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0);
m.extra.ints[EYES] = i32::from(!glowing);
}
if !m.alive() {
return;
}
let now = check_can_move(m, w, events);
if now != can_move(m) {
if now {
m.voice("entity.creaking.unfreeze", events);
} else {
stop_in_place(m);
m.voice("entity.creaking.freeze", events);
}
m.extra.flag2 = !now;
}
}
/// `Mob.stopInPlace`.
pub fn stop_in_place(m: &mut Mob) {
m.nav_stop();
m.ai.xxa = 0.0;
m.ai.yya = 0.0;
m.ai.zza = 0.0;
m.ai.speed = 0.0;
}
fn activate(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.ai.target = Some(Who::Player);
m.voice("entity.creaking.activate", events);
m.extra.flag = true;
}
fn deactivate(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.ai.target = None;
m.voice("entity.creaking.deactivate", events);
m.extra.flag = false;
}
/// `LivingEntity.isLookingAtMe(player, 0.5, false, true, eyeY, y + 0.5, mid)`.
fn looked_at_by(m: &Mob, w: &MobWorld) -> bool {
let Some(p) = &w.player else { return false };
let look = p.look;
let eye = m.eye_y();
[eye, m.position.y + 0.5, (eye + m.position.y) / 2.0]
.into_iter()
.any(|y| {
let d = [
m.position.x - p.position.x,
y - p.eye[1],
m.position.z - p.position.z,
];
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if len < 1.0e-6 {
return true;
}
let dot = (look[0] * d[0] + look[1] * d[1] + look[2] * d[2]) / len;
dot > 0.5
&& w.line_of_sight(
Vec3::new(p.eye[0], p.eye[1], p.eye[2]),
Vec3::new(m.position.x, y, m.position.z),
)
})
}
/// `Creaking.checkCanMove`: false while looked at; also wakes and calms it.
fn check_can_move(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) -> bool {
let active = is_active(m);
// NEAREST_PLAYERS: players within the follow range.
let near = w.player.as_ref().filter(|p| {
let d = Vec3::new(p.position.x, p.position.y, p.position.z);
m.distance_sqr(d) < 32.0 * 32.0
});
let Some(p) = near else {
if active {
deactivate(m, events);
}
return true;
};
// canAttack: alive and not creative or spectator.
let attackable = p.alive && !p.creative;
if attackable {
// GAZE_DISGUISE_EQUIPMENT hides the player once the creaking is awake.
let disguised = p.head.as_deref() == Some("minecraft:carved_pumpkin");
if (!active || !disguised) && looked_at_by(m, w) {
if active {
return false;
}
if m.distance_sqr(p.position) < ACTIVATION_RANGE_SQ {
activate(m, events);
return false;
}
}
} else if active {
deactivate(m, events);
}
true
}
/// `Creaking.playerIsStuckInYou`: the player's eyes inside it for more than 4 ticks.
pub fn player_is_stuck(m: &mut Mob, eye: Option<[f64; 3]>) -> bool {
let Some(eye) = eye else {
m.extra.ints[STUCK] = 0;
return false;
};
let b = m.bounds();
let (lo, hi) = (b.min_position(), b.max_position());
let inside = eye[0] >= lo.x
&& eye[0] <= hi.x
&& eye[1] >= lo.y
&& eye[1] <= hi.y
&& eye[2] >= lo.z
&& eye[2] <= hi.z;
if inside {
m.extra.ints[STUCK] += 1;
m.extra.ints[STUCK] > 4
} else {
m.extra.ints[STUCK] = 0;
false
}
}
/// The nearest attackable player the creaking can see.
fn sees_attackable_player(m: &mut Mob, cx: &mut Cx) -> bool {
let Some(p) = &cx.w.player else {
return false;
};
let near = m.distance_sqr(p.position) < m.attrs.follow_range.powi(2);
p.alive && !p.creative && near && m.sees(cx.w, Who::Player)
}
/// `StartAttacking` / `StopAttackingIfTargetInvalid`: while awake, hunt the
/// nearest visible player.
#[derive(Clone, Debug)]
struct HuntPlayer;
impl Goal for HuntPlayer {
goal_clone!();
fn flags(&self) -> u8 {
TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !is_active(m) || !sees_attackable_player(m, cx) {
return false;
}
m.ai.target = Some(Who::Player);
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
is_active(m) && m.ai.target == Some(Who::Player) && sees_attackable_player(m, cx)
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
if m.ai.target == Some(Who::Player) {
m.ai.target = None;
}
}
}
/// `CreakingModel.setupAnim`.
pub fn anim(m: &Mob, s: &State, p: &mut Poses, animations: &HashMap<String, Animation>) {
p.xrot("head", s.x_rot.to_radians());
p.yrot("head", s.y_rot.to_radians());
let get = |n: &str| animations.get(&format!("CreakingAnimation.CREAKING_{n}"));
if can_move(m)
&& let Some(walk) = get("WALK")
{
walk.apply_walk(s.pos, s.speed, 1.0, 1.0, p);
}
for (state, name) in [
(&m.anim.states[0], "ATTACK"),
(&m.anim.states[1], "INVULNERABLE"),
(&m.anim.states[2], "DEATH"),
] {
if let (Some(ms), Some(a)) = (state.millis(s.age), get(name)) {
a.apply(ms, 1.0, p);
}
}
}
/// The creaking species exists in the species table.
pub fn is_creaking(m: &Mob) -> bool {
m.species() == Species::Creaking
}
+8 -1
View File
@@ -731,6 +731,8 @@ pub struct MeleeAttack {
pub until_attack: i32,
last_check: i64,
raise_arm: i32,
/// Ticks between attacks (20 unless set).
pub interval: i32,
}
impl MeleeAttack {
pub fn new(speed: f64, follow_unseen: bool) -> Self {
@@ -743,12 +745,17 @@ impl MeleeAttack {
until_attack: 0,
last_check: i64::MIN / 2,
raise_arm: 0,
interval: 20,
}
}
pub fn zombie(mut self) -> Self {
self.zombie = true;
self
}
pub fn interval(mut self, ticks: i32) -> Self {
self.interval = ticks;
self
}
}
impl Goal for MeleeAttack {
goal_clone!();
@@ -834,7 +841,7 @@ impl Goal for MeleeAttack {
}
self.until_attack = (self.until_attack - 1).max(0);
if self.until_attack <= 0 && m.within_melee_range(&t) && m.sees(cx.w, who) {
self.until_attack = adjusted(true, 20);
self.until_attack = adjusted(true, self.interval);
m.swing();
super::ai::do_hurt_target(m, who, cx);
}
+43
View File
@@ -36,6 +36,7 @@ pub fn register_iron(m: &mut Mob) {
);
g.add(7, LookAtPlayer::new(6.0));
g.add(8, RandomLookAround::default());
m.ai.targets.add(1, DefendVillage);
m.ai.targets.add(2, HurtByTarget::new());
m.ai.targets.add(
3,
@@ -48,6 +49,48 @@ pub fn register_iron(m: &mut Mob) {
NearestTarget::new(Prey::Filter(golem_prey), false).interval(5),
);
}
/// `DefendVillageTargetGoal`: a player that a villager nearby has no
/// good word for (reputation of -100 or worse) is attacked on sight.
#[derive(Clone, Debug)]
struct DefendVillage;
impl Goal for DefendVillage {
goal_clone!();
fn flags(&self) -> u8 {
super::goals::TARGET
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(p) = &cx.w.player else { return false };
if !p.alive || p.creative || p.spectator {
return false;
}
// The box around the golem: 10 across, 8 up and down.
let b = m.bounds().inflate(Vec3::new(10.0, 8.0, 10.0));
if !b.intersects(p.bounds) || m.position.distance_squared(p.position) > 64.0 * 64.0 {
return false;
}
let bad = cx.w.others.iter().any(|s| {
s.species == Species::Villager
&& s.alive
&& s.player_rep <= -100
&& b.contains(s.position)
&& s.position.distance_squared(m.position) <= 64.0 * 64.0
});
bad && m.sees(cx.w, Who::Player)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.target_info(cx.w).is_some_and(|t| {
t.alive
&& !(t.is_player && t.creative)
&& m.position.distance_squared(t.position) <= 64.0 * 64.0
})
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = Some(Who::Player);
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.ai.target = None;
}
}
/// `MoveTowardsTargetGoal`: close in on a target within range.
#[derive(Clone, Debug)]
struct MoveTowardsTarget {
+27 -5
View File
@@ -384,8 +384,10 @@ impl CrossbowAttack {
pub fn crossbow_goal(speed: f64, radius: f64) -> impl Goal {
CrossbowAttack::new(speed, radius)
}
/// `CrossbowItem.getChargeDuration` without Quick Charge.
const CHARGE: i32 = 25;
/// `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))
}
fn holding_crossbow(m: &Mob) -> bool {
m.extra.main_hand.as_deref() == Some("minecraft:crossbow")
}
@@ -469,7 +471,7 @@ impl Goal for CrossbowAttack {
}
Crossbow::Charging => {
m.extra.using_item += 1;
if m.extra.using_item >= CHARGE {
if m.extra.using_item >= charge_ticks(m) {
m.extra.using_item = 0;
m.extra.flag = false;
self.state = Crossbow::Charged;
@@ -534,6 +536,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
enum ArmPose {
Spellcasting,
Crossed,
Celebrating,
Neutral,
Attacking,
CrossbowHold,
@@ -554,16 +557,22 @@ fn arm_pose(m: &Mob) -> ArmPose {
}
}
Species::Evoker if m.extra.variant2 != 0 => ArmPose::Spellcasting,
Species::Evoker if celebrating(m) => ArmPose::Celebrating,
Species::Evoker => ArmPose::Crossed,
_ => {
if m.ai.aggressive {
ArmPose::Attacking
} else if celebrating(m) {
ArmPose::Celebrating
} else {
ArmPose::Crossed
}
}
}
}
fn celebrating(m: &Mob) -> bool {
super::raider::state(m).is_some_and(|s| s.celebrating)
}
/// Whether the held item shows (vindicators only draw their axe when angry).
pub fn shows_item(m: &Mob) -> bool {
m.species() != Species::Vindicator || m.ai.aggressive
@@ -637,8 +646,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
ArmPose::CrossbowCharge => {
p.yrot("right_arm", -0.8);
p.xrot("right_arm", -0.970_796_35);
let a =
(m.extra.using_item as f32 + s.partial).clamp(0.0, CHARGE as f32) / CHARGE as f32;
let charge = charge_ticks(m) as f32;
let a = (m.extra.using_item as f32 + s.partial).clamp(0.0, charge) / charge;
p.yrot("left_arm", 0.4 + (0.85 - 0.4) * a);
p.xrot("left_arm", -0.970_796_35 + (-PI / 2.0 + 0.970_796_35) * a);
}
@@ -655,6 +664,19 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
v[5] = z_rot;
}
}
ArmPose::Celebrating => {
for (arm, x, z_rot) in [
("right_arm", -5.0, 2.670_354),
("left_arm", 5.0, -PI * 0.75),
] {
let v = p.get(arm);
v[2] = 0.0;
v[0] = x;
v[3] = (s.age * 0.6662).cos() * 0.05;
v[4] = 0.0;
v[5] = z_rot;
}
}
ArmPose::Crossed | ArmPose::Neutral => {}
}
if pose == ArmPose::Crossed {
+6 -1
View File
@@ -437,7 +437,12 @@ impl Mob {
let distance = (dx * dx + dy * dy + dz * dz).sqrt() as f32;
self.previous_limb_speed = self.limb_speed;
if self.alive() {
let target = (distance * 4.0).min(1.0);
// Creaking.updateWalkAnimation walks the model faster.
let target = if self.species() == super::Species::Creaking {
(distance * 25.0).min(3.0)
} else {
(distance * 4.0).min(1.0)
};
self.limb_speed += (target - self.limb_speed) * 0.4;
self.limb_position += self.limb_speed * if self.is_baby() { 3.0 } else { 1.0 };
} else {
+678
View File
@@ -0,0 +1,678 @@
//! Raiders (`PatrollingMonster` and `Raider`): the patrol state every
//! pillager, vindicator, evoker, witch and ravager carries, the long
//! distance patrol and hold-ground goals, the ominous banner a patrol leader
//! wears, and the saved fields.
use super::{
Mob, MobEvent, MobWorld, Species, Who,
goals::{Cx, Goal, LOOK, MOVE, goal_clone},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
use horizon_world::nbt::Tag;
/// The ominous banner is a white banner with the raid patterns; raiders wear
/// it as their head item.
pub const BANNER: &str = "minecraft:white_banner";
/// `PatrollingMonster` and `Raider` state (saved as `patrol_target`,
/// `PatrolLeader`, `Patrolling`, `Wave`, `CanJoinRaid`, `RaidId`).
#[derive(Clone, Debug, Default)]
pub struct State {
pub patrol_leader: bool,
pub patrolling: bool,
pub patrol_target: Option<[i32; 3]>,
/// Goal cooldown after a failed long distance path (game time).
pub patrol_cooldown_until: i64,
pub wave: i32,
pub can_join_raid: bool,
/// The raid this raider belongs to.
pub raid_id: Option<i32>,
pub ticks_outside_raid: i32,
pub celebrating: bool,
/// The raid is active (`hasActiveRaid`); set by the game every tick.
pub active_raid: bool,
/// The raid is won or lost (`Raid.isOver`), lost (`isLoss`).
pub raid_over: bool,
pub raid_loss: bool,
pub raid_center: [i32; 3],
/// Standing in or beside a village (`ServerLevel.isVillage`).
pub in_village: bool,
/// A dropped ominous banner this raider may fetch.
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>,
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`).
pub fn has_rider(&self) -> bool {
self.rider
}
}
/// The raider species (`EntityTypeTags.RAIDERS`).
pub fn is_raider(s: Species) -> bool {
matches!(
s,
Species::Pillager
| Species::Vindicator
| Species::Evoker
| Species::Witch
| Species::Ravager
)
}
/// `canBeLeader`: witches and ravagers never lead.
pub fn can_be_leader(s: Species) -> bool {
is_raider(s) && !matches!(s, Species::Witch | Species::Ravager)
}
pub fn state(m: &Mob) -> Option<&State> {
m.extra.raider.as_deref()
}
pub fn state_mut(m: &mut Mob) -> &mut State {
m.extra.raider.get_or_insert_with(Box::default)
}
pub fn has_active_raid(m: &Mob) -> bool {
state(m).is_some_and(|s| s.active_raid)
}
/// `Raider.isCaptain`: the banner on the head of a patrol leader.
pub fn is_captain(m: &Mob) -> bool {
m.extra.head.as_deref() == Some(BANNER) && state(m).is_some_and(|s| s.patrol_leader)
}
pub fn register(m: &mut Mob) {
if !is_raider(m.species()) {
return;
}
m.extra.raider = Some(Box::default());
let species = m.species();
m.ai.goals.add(1, ObtainBanner);
m.ai.goals.add(3, PathfindToRaid);
m.ai.goals.add(4, MoveThroughVillage::new(1.05, 1.0));
m.ai.goals.add(5, Celebration);
m.ai.goals.add(4, LongDistancePatrol::new(0.7, 0.595));
// The illagers hold their ground in a patrol (Witch and Ravager do not).
if matches!(species, Species::Pillager | Species::Vindicator) {
m.ai.goals.add(
if species == Species::Pillager { 2 } else { 4 },
HoldGroundAttack::new(10.0),
);
}
}
/// `Raid.getOminousBannerInstance`.
pub fn ominous_banner() -> crate::items::ItemStack {
let mut stack = crate::items::ItemStack::new(BANNER, 1);
stack.data_mut().ominous_banner = true;
stack
}
/// `PatrollingMonster.setPatrolLeader`.
pub fn set_patrol_leader(m: &mut Mob, leader: bool) {
let s = state_mut(m);
s.patrol_leader = leader;
s.patrolling = true;
}
/// `PatrollingMonster.setPatrolTarget`.
pub fn set_patrol_target(m: &mut Mob, target: [i32; 3]) {
let s = state_mut(m);
s.patrol_target = Some(target);
s.patrolling = true;
}
/// `PatrollingMonster.findPatrolTarget`: somewhere within 500 blocks.
pub fn find_patrol_target(m: &mut Mob) {
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
find_patrol_target_from(m, at);
}
/// `findPatrolTarget` from a given block position.
pub fn find_patrol_target_from(m: &mut Mob, [x, y, z]: [i32; 3]) {
let dx = -500 + m.random.next_int_bound(1000).unwrap_or(0);
let dz = -500 + m.random.next_int_bound(1000).unwrap_or(0);
let s = state_mut(m);
s.patrol_target = Some([x + dx, y, z + dz]);
s.patrolling = true;
}
/// The leader's ominous banner and its drop chance of 2.0 (always dropped).
pub fn wear_banner(m: &mut Mob) {
m.extra.head = Some(BANNER.into());
}
/// Why a mob was spawned (`EntitySpawnReason`), as far as raiders care.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
/// Natural spawning: one leader in 17, and witches stay out of raids.
Natural,
/// Commands, eggs and other spawns: one leader in 17.
Other,
Patrol,
Event,
}
/// `PatrollingMonster.finalizeSpawn` and `Raider.finalizeSpawn`: a spawn
/// other than a patrol, raid or structure leads one time in 17, a patrol
/// leader wears the ominous banner, and every raider but a naturally spawned
/// witch can join a raid.
pub fn finalize(m: &mut Mob, reason: Reason) {
if !is_raider(m.species()) {
return;
}
let roll = matches!(reason, Reason::Natural | Reason::Other);
if roll && m.random.next_float() < 0.06 && can_be_leader(m.species()) {
state_mut(m).patrol_leader = true;
}
if state_mut(m).patrol_leader {
wear_banner(m);
}
let witch = m.species() == Species::Witch;
let s = state_mut(m);
if reason == Reason::Patrol {
s.patrolling = true;
}
s.can_join_raid = !witch || reason != Reason::Natural;
}
/// `PatrollingMonster.removeWhenFarAway`: patrollers and raiders in a raid
/// are only despawned beyond 128 blocks (never inside a raid).
pub fn keeps_alive(m: &Mob, distance_squared: f64) -> bool {
match state(m) {
Some(s) => s.raid_id.is_some() || s.patrolling && distance_squared <= 16384.0,
None => false,
}
}
/// `Heightmap.Types.MOTION_BLOCKING_NO_LEAVES` position above (x, z).
pub fn heightmap_pos(w: &MobWorld, x: i32, z: i32) -> [i32; 3] {
let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT;
let y = (crate::chunk::MIN_Y..top)
.rev()
.find(|&y| {
let f = w.facts.get(w.world.block(x, y, z));
(f.full_collision || f.fluid != crate::blocks::Fluid::None)
&& !f.name.ends_with("leaves")
})
.map_or(crate::chunk::MIN_Y, |y| y + 1);
[x, y, z]
}
/// `Vec3.yRot` (the angle is in radians, and the patrol goal passes 90).
fn y_rot(v: Vec3, angle: f32) -> Vec3 {
let (cos, sin) = (f64::from(angle.cos()), f64::from(angle.sin()));
Vec3::new(v.x * cos + v.z * sin, v.y, v.z * cos - v.x * sin)
}
/// `PatrollingMonster.LongDistancePatrolGoal`: walk toward the patrol target
/// in 10 block hops (curving around it), the leader dragging its companions.
#[derive(Clone, Debug)]
pub struct LongDistancePatrol {
speed: f64,
leader_speed: f64,
}
impl LongDistancePatrol {
pub fn new(speed: f64, leader_speed: f64) -> Self {
Self {
speed,
leader_speed,
}
}
}
/// Patrol companions within 16 blocks that are not in a raid.
fn companions(m: &Mob, w: &MobWorld) -> Vec<u32> {
w.others
.iter()
.filter(|s| {
s.id != m.id
&& s.alive
&& is_raider(s.species)
&& !s.active_raid
&& (s.position.x - m.position.x).abs() <= 16.0 + f64::from(m.width())
&& (s.position.y - m.position.y).abs() <= 16.0 + f64::from(m.height())
&& (s.position.z - m.position.z).abs() <= 16.0 + f64::from(m.width())
})
.map(|s| s.id)
.collect()
}
impl Goal for LongDistancePatrol {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(s) = state(m) else { return false };
cx.w.game_time >= s.patrol_cooldown_until
&& s.patrolling
&& m.ai.target.is_none()
&& s.patrol_target.is_some()
&& !s.has_rider()
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if !m.ai.nav.is_done() {
return;
}
let leader = state(m).is_some_and(|s| s.patrol_leader);
let friends = companions(m, cx.w);
let Some(target) = state(m).and_then(|s| s.patrol_target) else {
return;
};
if state(m).is_some_and(|s| s.patrolling) && friends.is_empty() {
state_mut(m).patrolling = false;
} else if leader && close_to_center(target, m.position, 10.0) {
find_patrol_target(m);
} else {
let to = Vec3::new(
f64::from(target[0]) + 0.5,
f64::from(target[1]),
f64::from(target[2]) + 0.5,
);
let own = m.position;
let distance = own.subtract(to);
let to = y_rot(distance, 90.0).scale(0.4).add_vector(to);
let hop = to.subtract(own).normalize().scale(10.0).add_vector(own);
let at = heightmap_pos(cx.w, hop.x.floor() as i32, hop.z.floor() as i32);
let speed = if leader {
self.leader_speed
} else {
self.speed
};
let to = [f64::from(at[0]), f64::from(at[1]), f64::from(at[2])];
if !m.nav_move_to(cx.w, to, speed) {
self.move_randomly(m, cx);
state_mut(m).patrol_cooldown_until = cx.w.game_time + 200;
} else if leader {
for id in friends {
cx.events.push(MobEvent::PatrolTarget {
mob: id,
target: at,
});
}
}
}
}
}
impl LongDistancePatrol {
fn move_randomly(&self, m: &mut Mob, cx: &mut Cx) -> bool {
let (x, z) = (
m.position.x.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
m.position.z.floor() as i32 - 8 + m.random.next_int_bound(16).unwrap_or(0),
);
let at = heightmap_pos(cx.w, x, z);
m.nav_move_to(
cx.w,
[f64::from(at[0]), f64::from(at[1]), f64::from(at[2])],
self.speed,
)
}
}
/// `Vec3i.closerToCenterThan`.
fn close_to_center(p: [i32; 3], at: Vec3, distance: f64) -> bool {
Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
)
.distance_squared(at)
< distance * distance
}
/// `Raider.ObtainRaidLeaderBannerGoal`: walk to a fallen ominous banner when
/// the wave has no living leader (the game finds the banner and picks it up).
#[derive(Clone, Debug)]
pub struct ObtainBanner;
impl Goal for ObtainBanner {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
state(m).is_some_and(|s| s.banner_at.is_some())
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!m.ai.nav.is_done() && state(m).is_some_and(|s| s.banner_at.is_some())
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(at) = state(m).and_then(|s| s.banner_at) {
m.nav_move_to(cx.w, at, 1.15);
}
}
}
/// `PathfindToRaidGoal`: outside the village, head for the raid's centre in
/// hops of up to 15 blocks.
#[derive(Clone, Debug)]
pub struct PathfindToRaid;
impl PathfindToRaid {
fn valid(s: &State) -> bool {
s.active_raid && !s.raid_over && !s.in_village
}
}
impl Goal for PathfindToRaid {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
m.ai.target.is_none() && state(m).is_some_and(|s| !s.has_rider() && Self::valid(s))
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
state(m).is_some_and(Self::valid)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(c) = state(m).map(|s| s.raid_center) else {
return;
};
if m.ai.nav.is_done() {
let to = [
f64::from(c[0]) + 0.5,
f64::from(c[1]),
f64::from(c[2]) + 0.5,
];
if let Some(at) =
m.default_random_pos_towards(cx.w, 15, 4, to, std::f64::consts::FRAC_PI_2)
{
m.nav_move_to(cx.w, at, 1.0);
}
}
}
}
/// `Raider.RaiderMoveThroughVillageGoal`: walk to a bed of the village not
/// visited lately, then onwards to the next one.
#[derive(Clone, Debug)]
pub struct MoveThroughVillage {
speed: f64,
distance: f64,
poi: Option<[i32; 3]>,
visited: Vec<[i32; 3]>,
stuck: bool,
}
impl MoveThroughVillage {
pub fn new(speed: f64, distance: f64) -> Self {
Self {
speed,
distance,
poi: None,
visited: Vec::new(),
stuck: false,
}
}
}
impl Goal for MoveThroughVillage {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if self.visited.len() > 2 {
self.visited.remove(0);
}
let Some(s) = state(m) else { return false };
if !(s.active_raid && !s.raid_over) || m.ai.target.is_some() {
return false;
}
let Some(homes) = s.homes.clone() else {
return false;
};
let near: Vec<[i32; 3]> = homes
.iter()
.copied()
.filter(|p| !self.visited.contains(p) && close_to_center(*p, m.position, 48.0))
.collect();
if near.is_empty() {
return false;
}
self.poi = Some(near[m.random.next_int_bound(near.len() as i32).unwrap_or(0) as usize]);
true
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
let Some(p) = self.poi else { return false };
!m.ai.nav.is_done()
&& m.ai.target.is_none()
&& !close_to_center(p, m.position, f64::from(m.width()) + self.distance)
&& !self.stuck
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.no_action_time = 0;
if let Some(p) = self.poi {
m.nav_move_to(
cx.w,
[f64::from(p[0]), f64::from(p[1]), f64::from(p[2])],
self.speed,
);
}
self.stuck = false;
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
if let Some(p) = self.poi
&& close_to_center(p, m.position, self.distance)
{
self.visited.push(p);
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = self.poi else { return };
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(p[0]) + 0.5,
f64::from(p[1]),
f64::from(p[2]) + 0.5,
];
let next = m
.default_random_pos_towards(cx.w, 16, 7, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
match next {
Some(at) => {
m.nav_move_to(cx.w, at, self.speed);
}
None => self.stuck = true,
}
}
}
/// `Raider.RaiderCelebration`: after a lost village, cheer and jump.
#[derive(Clone, Debug)]
pub struct Celebration;
impl Goal for Celebration {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
m.alive()
&& m.ai.target.is_none()
&& state(m).is_some_and(|s| s.raid_loss && s.raid_id.is_some())
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
state_mut(m).celebrating = true;
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
state_mut(m).celebrating = false;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if m.random
.next_int_bound(super::goals::reduced(100))
.unwrap_or(1)
== 0
{
let sound = match m.species() {
Species::Pillager => "entity.pillager.celebrate",
Species::Vindicator => "entity.vindicator.celebrate",
Species::Evoker => "entity.evoker.celebrate",
Species::Ravager => "entity.ravager.celebrate",
_ => "entity.witch.celebrate",
};
m.voice(sound, cx.events);
}
if m.random
.next_int_bound(super::goals::reduced(50))
.unwrap_or(1)
== 0
{
m.ai.jumping = true;
}
}
}
/// `Raider.HoldGroundAttackGoal`: while patrolling, stand still and let the
/// patrol shout when something shows up; attack once it comes close.
#[derive(Clone, Debug)]
pub struct HoldGroundAttack {
hostile_radius_sqr: f64,
}
impl HoldGroundAttack {
pub fn new(radius: f64) -> Self {
Self {
hostile_radius_sqr: radius * radius,
}
}
}
/// Raiders within 8 blocks, nearest first (`shoutTargeting`).
fn shout_range(m: &Mob, w: &MobWorld) -> Vec<u32> {
w.others
.iter()
.filter(|s| {
s.id != m.id
&& s.alive
&& is_raider(s.species)
&& (s.position.x - m.position.x).abs() <= 8.0 + f64::from(m.width())
&& (s.position.y - m.position.y).abs() <= 8.0 + f64::from(m.height())
&& (s.position.z - m.position.z).abs() <= 8.0 + f64::from(m.width())
&& s.position.distance_squared(m.position) <= 64.0
})
.map(|s| s.id)
.collect()
}
impl Goal for HoldGroundAttack {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
let Some(s) = state(m) else { return false };
s.raid_id.is_none()
&& s.patrolling
&& m.ai.target.is_some()
&& !m.ai.aggressive
&& m.ai.last_hurt_by != Some(Who::Player)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.nav.stop();
if let Some(target) = m.ai.target {
for id in shout_range(m, cx.w) {
cx.events.push(MobEvent::RaiderTarget {
mob: id,
target,
aggressive: false,
});
}
}
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(target) = m.ai.target {
for id in shout_range(m, cx.w) {
cx.events.push(MobEvent::RaiderTarget {
mob: id,
target,
aggressive: true,
});
}
m.ai.aggressive = true;
}
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(t) = m.target_info(cx.w) else { return };
if m.distance_sqr(t.position) > self.hostile_radius_sqr {
m.look_at([t.position.x, t.eye_y, t.position.z]);
if m.random.next_int_bound(50).unwrap_or(1) == 0 {
let sound = m.kind.sounds[0];
if !sound.is_empty() {
m.voice(sound, cx.events);
}
}
} else {
m.ai.aggressive = true;
}
}
}
/// The saved fields (`PatrollingMonster` and `Raider.addAdditionalSaveData`).
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
let Some(s) = state(m) else { return };
match s.patrol_target {
Some(p) => {
map.insert("patrol_target".into(), Tag::IntArray(p.to_vec()));
}
None => {
map.remove(&"patrol_target".into());
}
}
map.insert("PatrolLeader".into(), Tag::Byte(i8::from(s.patrol_leader)));
map.insert("Patrolling".into(), Tag::Byte(i8::from(s.patrolling)));
map.insert("Wave".into(), Tag::Int(s.wave));
map.insert("CanJoinRaid".into(), Tag::Byte(i8::from(s.can_join_raid)));
match s.raid_id {
Some(id) => {
map.insert("RaidId".into(), Tag::Int(id));
}
None => {
map.remove(&"RaidId".into());
}
}
}
pub fn read_nbt(m: &mut Mob, tag: &Tag) {
if !is_raider(m.species()) {
return;
}
let int = |t: Option<&Tag>| match t {
Some(Tag::Int(v)) => Some(*v),
Some(Tag::Byte(v)) => Some(i32::from(*v)),
Some(Tag::Short(v)) => Some(i32::from(*v)),
_ => None,
};
let flag = |t: Option<&Tag>| int(t).unwrap_or(0) != 0;
let s = state_mut(m);
s.patrol_target = match tag.get("patrol_target") {
Some(Tag::IntArray(v)) if v.len() == 3 => Some([v[0], v[1], v[2]]),
_ => None,
};
s.patrol_leader = flag(tag.get("PatrolLeader"));
s.patrolling = flag(tag.get("Patrolling"));
s.wave = int(tag.get("Wave")).unwrap_or(0);
s.can_join_raid = flag(tag.get("CanJoinRaid"));
s.raid_id = int(tag.get("RaidId"));
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn raiders_and_leaders() {
assert!(is_raider(Species::Ravager) && is_raider(Species::Witch));
assert!(!is_raider(Species::Zombie));
assert!(can_be_leader(Species::Pillager) && can_be_leader(Species::Evoker));
assert!(!can_be_leader(Species::Witch) && !can_be_leader(Species::Ravager));
}
#[test]
fn long_distance_patrol_turns_by_ninety_radians() {
// PatrollingMonster passes 90.0F to Vec3.yRot (radians).
let v = y_rot(Vec3::new(10.0, 3.0, 0.0), 90.0);
let (c, s) = (90f64.cos(), 90f64.sin());
assert!((v.x - 10.0 * c).abs() < 1e-4 && (v.z + 10.0 * s).abs() < 1e-4);
assert_eq!(v.y, 3.0);
}
#[test]
fn closer_to_center_uses_block_centres() {
let at = Vec3::new(10.5, 64.5, 10.5);
assert!(close_to_center([10, 64, 10], at, 1.0));
assert!(!close_to_center([30, 64, 10], at, 10.0));
}
}
+12 -3
View File
@@ -403,6 +403,13 @@ pub fn layers(m: &Mob) -> Vec<Layer> {
);
}
}
S::Creaking if super::creaking::eyes_glowing(m) => push(
&mut v,
"creaking#eyes",
"entity/creaking/creaking_eyes",
white,
true,
),
S::Spider | S::CaveSpider => push(
&mut v,
&m.kind.model_key(),
@@ -622,7 +629,7 @@ pub fn base_transform(m: &Mob, alpha: f32, camera: glam::DVec3) -> glam::Mat4 {
.unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())),
};
let mut base = glam::Mat4::from_translation(p.as_vec3()) * rotation;
if m.death_time > 0 {
if m.death_time > 0 && !super::creaking::tearing_down(m) {
let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6)
.sqrt()
.min(1.0);
@@ -740,7 +747,8 @@ pub fn render_with(
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let s = anim::state(m, alpha);
let (model_key, texture) = body(m);
let model = m
@@ -793,7 +801,8 @@ pub fn render_single(
out: &mut Vec<Vertex>,
) {
let base = base_transform(m, alpha, camera);
let overlay = u32::from(m.hurt_time > 0 || m.death_time > 0);
let overlay =
u32::from(m.hurt_time > 0 || (m.death_time > 0 && !super::creaking::tearing_down(m)));
let s = anim::state(m, alpha);
let model = m.kind.model.clone();
let mut poses = Poses::new(&model);
+18 -4
View File
@@ -299,7 +299,9 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
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: 5% babies (normal difficulty).
// 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;
}
@@ -348,8 +350,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
}
// 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::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)
}
@@ -358,6 +366,7 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
// 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 {
@@ -379,11 +388,16 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
.into(),
);
}
S::PiglinBrute => m.extra.main_hand = Some("minecraft:golden_axe".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),
_ => {}
+15
View File
@@ -83,6 +83,7 @@ pub enum Species {
Wither,
Camel,
Allay,
Creaking,
}
/// Baby bounding boxes (each class's BABY_DIMENSIONS).
#[derive(Clone, Copy, Debug)]
@@ -914,6 +915,20 @@ pub const ALL: &[Def] = &[
None,
Baby::None
),
def!(
Creaking,
"creaking",
"creaking#main",
"entity/creaking/creaking",
A::Creaking,
[
"entity.creaking.ambient",
"entity.generic.hurt",
"entity.creaking.death"
],
Some("entity.creaking.step"),
Baby::None
),
def!(
Camel,
"camel",
+782 -3
View File
@@ -5,13 +5,14 @@
//! (work and restock at the job site, meet at the bell, sleep in the bed),
//! fleeing hostiles (`VillagerPanicTrigger`) and the unhappy head shake.
use super::{
Mob, MobEvent, MobWorld, Species,
Mob, MobEvent, MobWorld, Species, Who,
anim::{Poses, State},
goals::{
Avoid, AvoidEntity, Cx, Float, Goal, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll,
goal_clone,
Avoid, AvoidEntity, Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround,
Stroll, goal_clone,
},
};
use crate::items::ItemStack;
use horizon_core::random::RandomSource;
use std::{collections::HashMap, f32::consts::PI};
@@ -74,6 +75,10 @@ pub fn register(m: &mut Mob) {
AvoidEntity::new(Avoid::Species(raiders), 12.0, 0.75, 0.75),
);
g.add(1, Panic::new(0.75));
g.add(2, RaidBehavior::default());
g.add(3, Social::default());
g.add(0, GolemCall);
g.add(3, GiftToHero::default());
g.add(3, JobSite::default());
g.add(3, AcquireHome::default());
g.add(4, Schedule::default());
@@ -456,6 +461,7 @@ fn start_sleeping(m: &mut Mob, p: [i32; 3], w: &MobWorld) {
_ => 4,
};
m.nav_stop();
ext_mut(m).last_slept = Some(w.game_time);
m.velocity = horizon_core::geometry::Vec3::ZERO;
m.position = horizon_core::geometry::Vec3::new(
f64::from(p[0]) + 0.5,
@@ -516,6 +522,23 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
if m.extra.ints[0] > 0 {
m.extra.ints[0] -= 1;
}
if m.species() == Species::Villager {
let now = w.game_time;
let seen_golem = (i64::from(m.age) + i64::from(m.id)) % 200 == 0
&& w.others.iter().any(|s| {
s.species == Species::IronGolem
&& s.alive
&& (s.position.x - m.position.x).abs() <= 16.0
&& (s.position.y - m.position.y).abs() <= 16.0
&& (s.position.z - m.position.z).abs() <= 16.0
});
let e = ext_mut(m);
// Villager.maybeDecayGossip and the GolemSensor (every 200 ticks).
e.maybe_decay(now);
if seen_golem {
e.golem_until = now + 599;
}
}
// WakeUp / LivingEntity.hurt: morning, a hit or a missing bed.
if sleeping(m) {
let bed_gone = m
@@ -594,3 +617,759 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
p.yrot("right_leg", 0.0);
p.yrot("left_leg", 0.0);
}
// ---- Raids: the raid activities and the gift for a hero.
pub const RAID_NONE: u8 = 0;
/// A raid is near but no wave is on (`Activity.PRE_RAID`).
pub const PRE_RAID: u8 = 1;
/// A wave is on (`Activity.RAID`).
pub const RAID: u8 = 2;
/// The raid was won: the villagers celebrate.
pub const RAID_VICTORY: u8 = 3;
/// Villager state beyond `Extra`'s scratch fields.
#[derive(Clone, Debug, Default)]
pub struct Ext {
/// Which raid package the villager follows.
pub raid: u8,
/// What the villager remembers of players (`gossips`).
pub gossips: crate::gossip::Gossips,
pub last_gossip_time: i64,
pub last_gossip_decay: i64,
/// `foodLevel`: eaten but not yet digested, in food points.
pub food_level: i32,
/// The eight-slot inventory (`InventoryCarrier`).
pub inventory: Vec<ItemStack>,
/// `LAST_SLEPT` memory.
pub last_slept: Option<i64>,
/// `GOLEM_DETECTED_RECENTLY` expires at this game time.
pub golem_until: i64,
/// The `last_hurt_by_time` of the player's hit already counted.
pub hurt_seen: i32,
}
pub fn ext(m: &Mob) -> Option<&Ext> {
m.extra.villager.as_deref()
}
pub fn ext_mut(m: &mut Mob) -> &mut Ext {
m.extra.villager.get_or_insert_with(Box::default)
}
fn raid_status(m: &Mob) -> u8 {
ext(m).map_or(RAID_NONE, |e| e.raid)
}
/// The raid packages of `VillagerGoalPackages`: in a raid villagers hide at
/// home (`LocateHidingPlace`), before one they gather at the bell and ring it
/// (`RingBell`), and after a victory they look for the sky to celebrate
/// (`MoveToSkySeeingSpot`, `CelebrateVillagersSurvivedRaid`).
#[derive(Clone, Debug, Default)]
struct RaidBehavior {
next_move: i32,
}
impl Goal for RaidBehavior {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
raid_status(m) != RAID_NONE && !sleeping(m)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.next_move = 0;
m.nav_stop();
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.next_move -= 1;
let p = m.position;
match raid_status(m) {
RAID => {
// LocateHidingPlace(24, 0.7, 1): back to the bed.
let Some(home) = m.extra.bed else { return };
if distance(m, home) > 1.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
if distance(m, home) <= 24.0 {
m.nav_move_to(cx.w, center(home), 0.7);
}
self.next_move = 40;
}
}
PRE_RAID => {
// RingBell and SetWalkTargetFromBlockMemory(meeting, 0.75).
let Some(bell) = m.extra.meeting else { return };
if distance(m, bell) > 2.0 && (self.next_move <= 0 || m.ai.nav.is_done()) {
m.nav_move_to(cx.w, center(bell), 0.75);
self.next_move = 40;
}
if distance(m, bell) < 3.0
&& m.random.next_float() > 0.95
&& cx.w.block_name(bell[0], bell[1], bell[2]) == "minecraft:bell"
{
cx.events.push(MobEvent::SoundId(
"minecraft:block.bell.use".into(),
center(bell),
2.0,
1.0,
));
}
}
RAID_VICTORY => {
let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32);
if cx.w.can_see_sky(x, y, z) {
// CelebrateVillagersSurvivedRaid.tick.
if m.random.next_int_bound(100).unwrap_or(1) == 0 {
m.voice("entity.villager.celebrate", cx.events);
}
if m.random.next_int_bound(200).unwrap_or(1) == 0 {
let color = m.random.next_int_bound(16).unwrap_or(0) as usize;
let flight = m.random.next_int_bound(3).unwrap_or(0) as u8;
cx.events.push(MobEvent::Firework {
at: [p.x, m.eye_y(), p.z],
color,
flight,
});
}
m.nav_stop();
} else if self.next_move <= 0 || m.ai.nav.is_done() {
// MoveToSkySeeingSpot: a random spot with a view of the sky.
for _ in 0..5 {
if let Some(at) = m.land_random_pos(cx.w, 15, 7)
&& cx.w.can_see_sky(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
)
{
m.nav_move_to(cx.w, at, 0.5);
break;
}
}
self.next_move = 40;
}
}
_ => {}
}
}
}
/// `GiveGiftToHero`: a villager that sees a hero of the village walks up and
/// throws a gift of its profession, every so often.
#[derive(Clone, Debug)]
struct GiftToHero {
until_next: i32,
started: i64,
given: bool,
}
impl Default for GiftToHero {
fn default() -> Self {
Self {
until_next: 600,
started: 0,
given: false,
}
}
}
/// The gift loot table of a villager (`GiveGiftToHero.getLootTableToThrow`).
fn gift_table(m: &Mob) -> String {
if m.is_baby() {
return "minecraft:gameplay/hero_of_the_village/baby_gift".into();
}
let profession = super::render::PROFESSIONS[m.extra.variant2 as usize % 15];
let name = match profession {
"none" | "nitwit" => "unemployed",
other => other,
};
format!("minecraft:gameplay/hero_of_the_village/{name}_gift")
}
fn hero_in_view(m: &mut Mob, cx: &Cx) -> bool {
let Some(p) = &cx.w.player else { return false };
p.hero
&& p.alive
&& !p.spectator
&& m.position.distance_squared(p.position) <= 16.0 * 16.0
&& m.sees(cx.w, Who::Player)
}
impl Goal for GiftToHero {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !hero_in_view(m, cx) || sleeping(m) {
return false;
}
if self.until_next > 0 {
self.until_next -= 1;
return false;
}
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
hero_in_view(m, cx) && !self.given
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.given = false;
self.started = cx.w.game_time;
if let Some(p) = &cx.w.player {
m.look_at(p.eye);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
self.until_next = 600 + m.random.next_int_bound(6001).unwrap_or(0);
m.nav_stop();
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = cx.w.player.clone() else { return };
m.look_at(p.eye);
let near = m.position.distance_squared(p.position) < 25.0;
if near {
if cx.w.game_time - self.started > 20 {
cx.events.push(MobEvent::ThrowGift {
table: gift_table(m),
from: [m.position.x, m.eye_y() - 0.3, m.position.z],
to: [p.position.x, p.position.y, p.position.z],
});
self.given = true;
}
m.nav_stop();
} else if m.ai.nav.is_done() {
m.nav_move_to(cx.w, [p.position.x, p.position.y, p.position.z], 0.5);
}
}
}
// ---- Gossip, food, breeding and golems.
/// `VillagerFood` nutrition (`DataComponents.VILLAGER_FOOD`).
pub fn food_points(item: &str) -> i32 {
match item {
"minecraft:bread" => 4,
"minecraft:potato" | "minecraft:carrot" | "minecraft:beetroot" => 1,
_ => 0,
}
}
/// The farmer's `requestedItems`.
pub fn farmer_items() -> &'static [&'static str] {
&[
"minecraft:bread",
"minecraft:potato",
"minecraft:carrot",
"minecraft:wheat",
"minecraft:wheat_seeds",
"minecraft:beetroot",
"minecraft:beetroot_seeds",
"minecraft:torchflower_seeds",
"minecraft:pitcher_pod",
]
}
/// A villager's `requestedItems` by profession.
pub fn requested_items(m: &Mob) -> &'static [&'static str] {
if super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer" {
farmer_items()
} else {
&[]
}
}
pub fn is_farmer(m: &Mob) -> bool {
super::render::PROFESSIONS[m.extra.variant2 as usize % 15] == "farmer"
}
/// `SimpleContainer(8)`: stacks the villager carries.
const INVENTORY_SLOTS: usize = 8;
impl Ext {
/// `countFoodPointsInInventory`.
pub fn food_in_inventory(&self) -> i32 {
self.inventory
.iter()
.map(|s| food_points(&s.item) * s.count as i32)
.sum()
}
/// `hasExcessFood` and `wantsMoreFood`.
pub fn has_excess_food(&self) -> bool {
self.food_in_inventory() >= 24
}
pub fn wants_more_food(&self) -> bool {
self.food_in_inventory() < 12
}
fn hungry(&self) -> bool {
self.food_level < 12
}
/// `Villager.eatAndDigestFood`: eat until full, then digest 12 points.
pub fn eat_and_digest(&mut self) {
if self.hungry() {
let mut slot = 0;
while slot < self.inventory.len() && self.hungry() {
let points = food_points(&self.inventory[slot].item);
if points > 0 {
while self.inventory[slot].count > 0 && self.hungry() {
self.food_level += points;
self.inventory[slot].count -= 1;
}
if self.inventory[slot].count == 0 {
self.inventory.remove(slot);
continue;
}
}
slot += 1;
}
}
self.food_level -= 12;
}
/// Whether the stack fits (`SimpleContainer.canAddItem`).
pub fn can_add(&self, stack: &ItemStack, max_stack: u32) -> bool {
self.inventory.len() < INVENTORY_SLOTS
|| self
.inventory
.iter()
.any(|s| s.same_item_same_components(stack) && s.count < max_stack)
}
/// `SimpleContainer.addItem`: merge into stacks, then free slots; the
/// part that did not fit is returned.
pub fn add_item(&mut self, mut stack: ItemStack, max_stack: u32) -> Option<ItemStack> {
for s in &mut self.inventory {
if stack.count > 0 && s.same_item_same_components(&stack) && s.count < max_stack {
let n = (max_stack - s.count).min(stack.count);
s.count += n;
stack.count -= n;
}
}
while stack.count > 0 && self.inventory.len() < INVENTORY_SLOTS {
let n = stack.count.min(max_stack);
self.inventory.push(ItemStack {
count: n,
..stack.clone()
});
stack.count -= n;
}
(stack.count > 0).then_some(stack)
}
pub fn count_item(&self, item: &str) -> u32 {
self.inventory
.iter()
.filter(|s| &*s.item == item)
.map(|s| s.count)
.sum()
}
/// `TradeWithVillager.throwHalfStack`: the half of a big matching stack
/// (or whatever is over 24) leaves the inventory.
pub fn take_half_stack(
&mut self,
wanted: impl Fn(&ItemStack) -> bool,
max_stack: impl Fn(&str) -> u32,
) -> Option<ItemStack> {
for i in 0..self.inventory.len() {
let s = &self.inventory[i];
if s.count == 0 || !wanted(s) {
continue;
}
let count = if s.count > max_stack(&s.item) / 2 {
s.count / 2
} else if s.count > 24 {
s.count - 24
} else {
continue;
};
let taken = ItemStack { count, ..s.clone() };
self.inventory[i].count -= count;
if self.inventory[i].count == 0 {
self.inventory.remove(i);
}
return Some(taken);
}
None
}
/// `Villager.wantsToSpawnGolem`: slept within the last day and no golem
/// seen lately.
pub fn wants_golem(&self, now: i64) -> bool {
self.last_slept.is_some_and(|t| now - t < 24000) && now >= self.golem_until
}
/// `maybeDecayGossip`: once a day.
pub fn maybe_decay(&mut self, now: i64) {
if self.last_gossip_decay == 0 {
self.last_gossip_decay = now;
} else if now >= self.last_gossip_decay + 24000 {
self.gossips.decay();
self.last_gossip_decay = now;
}
}
/// `Villager.gossip` timing: hearing again waits 1200 ticks.
pub fn can_gossip(&self, now: i64) -> bool {
now < self.last_gossip_time || now >= self.last_gossip_time + 1200
}
}
/// `Villager.canBreed`: enough food, awake and an adult.
pub fn can_breed(m: &Mob) -> bool {
m.species() == Species::Villager
&& m.extra.age == 0
&& !sleeping(m)
&& ext(m).map_or(0, |e| e.food_level + e.food_in_inventory()) >= 12
}
/// The saved fields (`FoodLevel`, `Gossips`, `LastGossipDecay`, `Inventory`
/// and the sleep and golem memories).
pub fn write_nbt(m: &Mob, map: &mut horizon_world::nbt::Compound) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
map.insert(
"FoodLevel".into(),
Tag::Byte(e.food_level.clamp(-128, 127) as i8),
);
map.insert("Gossips".into(), e.gossips.to_nbt());
map.insert("LastGossipDecay".into(), Tag::Long(e.last_gossip_decay));
map.insert(
"Inventory".into(),
Tag::List(e.inventory.iter().map(crate::save::item_to_nbt).collect()),
);
}
/// The memories of `Brain.memories` the villager keeps besides positions.
pub fn write_memories(m: &Mob, memories: &mut Vec<(&'static str, horizon_world::nbt::Tag)>) {
use horizon_world::nbt::Tag;
let Some(e) = ext(m) else { return };
if let Some(t) = e.last_slept {
memories.push((
"minecraft:last_slept",
Tag::compound([("value", Tag::Long(t))]),
));
}
}
pub fn read_nbt(m: &mut Mob, tag: &horizon_world::nbt::Tag) {
use horizon_world::nbt::Tag;
let int = |t: Option<&Tag>| match t {
Some(Tag::Int(v)) => Some(i64::from(*v)),
Some(Tag::Byte(v)) => Some(i64::from(*v)),
Some(Tag::Short(v)) => Some(i64::from(*v)),
Some(Tag::Long(v)) => Some(*v),
_ => None,
};
let last_slept = int(tag
.get("Brain")
.and_then(|b| b.get("memories"))
.and_then(|b| b.get("minecraft:last_slept"))
.and_then(|j| j.get("value")));
let e = ext_mut(m);
e.food_level = int(tag.get("FoodLevel")).unwrap_or(0) as i32;
e.gossips = tag
.get("Gossips")
.map(crate::gossip::Gossips::from_nbt)
.unwrap_or_default();
e.last_gossip_decay = int(tag.get("LastGossipDecay")).unwrap_or(0);
e.last_slept = last_slept;
if let Some(Tag::List(items)) = tag.get("Inventory") {
e.inventory = items
.iter()
.filter_map(crate::save::item_from_nbt)
.take(INVENTORY_SLOTS)
.collect();
}
}
/// `InteractWith(VILLAGER)`, `TradeWithVillager` and `VillagerMakeLove` while
/// idle, and `SocializeAtBell` at the meeting: walk up to a villager, swap
/// gossip and food, and make a baby with a willing partner.
#[derive(Clone, Debug, Default)]
struct Social {
target: Option<u32>,
breed: bool,
ticks: i32,
cooldown: i32,
birth_at: i64,
}
impl Social {
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let breedable = can_breed(m);
let id = m.id;
let nearest =
cx.w.nearby(m.position, 8.0, move |s| {
s.species == Species::Villager && s.id != id
})
.filter(|s| m.position.distance_squared(s.position) <= 64.0)
.map(|s| (s.id, s.in_love))
.collect::<Vec<_>>();
let visible: Vec<(u32, bool)> = nearest
.into_iter()
.filter(|(i, _)| m.sees(cx.w, Who::Mob(*i)))
.collect();
let Some(&(target, partner_willing)) = visible.first() else {
return false;
};
// RunOne weights: interact 2, breed 1 (when both are willing).
let breed = breedable && partner_willing && m.random.next_int_bound(3).unwrap_or(0) == 0;
self.target = Some(target);
self.breed = breed;
true
}
}
impl Goal for Social {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.is_baby() || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.cooldown > 0 {
self.cooldown -= 1;
return false;
}
match activity(m, cx.w.day_time) {
Activity::Idle => self.pick(m, cx),
Activity::Meet => {
// SocializeAtBell: one tick in a hundred, near the bell.
let near_bell = m.extra.meeting.is_some_and(|p| distance(m, p) < 4.0);
near_bell && m.random.next_int_bound(100).unwrap_or(1) == 0 && {
let ok = self.pick(m, cx);
self.breed = false;
ok
}
}
_ => false,
}
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(t) = self.target else { return false };
let Some(s) = cx.w.seen(t) else { return false };
if !s.alive || sleeping(m) || raid_status(m) != RAID_NONE {
return false;
}
if self.breed {
self.ticks < 350 && can_breed(m) && s.in_love
} else {
self.ticks < 60
}
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 0;
self.birth_at = 0;
if let Some(s) = self.target.and_then(|t| cx.w.seen(t)) {
let at = [s.position.x, s.position.y, s.position.z];
m.nav_move_to(cx.w, at, 0.5);
}
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.nav_stop();
self.target = None;
self.cooldown = 20 + m.random.next_int_bound(40).unwrap_or(0);
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks += 1;
let Some(t) = self.target else { return };
let Some(s) = cx.w.seen(t) else { return };
let (at, eye) = ([s.position.x, s.position.y, s.position.z], s.eye_y);
m.look_at([at[0], eye, at[2]]);
if m.position.distance_squared(s.position) > 5.0 {
if m.ai.nav.is_done() && self.ticks % 10 == 1 {
m.nav_move_to(cx.w, at, 0.5);
}
return;
}
m.nav_stop();
if !self.breed {
cx.events.push(MobEvent::VillagerMeet {
mob: m.id,
other: t,
});
return;
}
let now = cx.w.game_time;
if self.birth_at == 0 {
self.birth_at = now + 275 + i64::from(m.random.next_int_bound(50).unwrap_or(0));
}
if now >= self.birth_at {
cx.events.push(MobEvent::VillagerBirth {
parent: m.id,
partner: t,
});
self.ticks = 1000;
} else if m.random.next_int_bound(35).unwrap_or(1) == 0 {
for p in [m.position, s.position] {
cx.events.push(MobEvent::Particles {
kind: "heart",
at: [p.x, p.y + 1.8, p.z],
count: 1,
});
}
}
}
}
/// `VillagerPanicTrigger.tick`: a frightened villager calls for a golem
/// every five seconds.
#[derive(Clone, Debug, Default)]
struct GolemCall;
/// `VillagerHostilesSensor`: how close each hostile must be to scare.
fn hostile_range(s: Species) -> f64 {
match s {
Species::Drowned
| Species::Husk
| Species::Vex
| Species::Zombie
| Species::ZombieVillager => 8.0,
Species::Evoker | Species::Ravager => 12.0,
Species::Pillager => 15.0,
Species::Vindicator | Species::Zoglin => 10.0,
_ => 0.0,
}
}
fn frightened(m: &Mob, cx: &Cx) -> bool {
// HURT_BY lasts 100 ticks.
let hurt = m.ai.last_hurt_by.is_some() && m.age as i32 - m.ai.last_hurt_by_time <= 100;
hurt || cx.w.others.iter().any(|s| {
s.alive && {
let r = hostile_range(s.species);
r > 0.0 && s.position.distance_squared(m.position) <= r * r
}
})
}
impl Goal for GolemCall {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
!m.is_baby() && frightened(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_use(m, cx)
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if cx.w.game_time % 100 == 0 {
cx.events.push(MobEvent::GolemCheck {
mob: m.id,
needed: 3,
});
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn stack(item: &str, count: u32) -> ItemStack {
ItemStack::new(item, count)
}
#[test]
fn eating_fills_the_food_level_then_digests() {
let mut e = Ext {
inventory: vec![stack("minecraft:bread", 3), stack("minecraft:carrot", 5)],
..Default::default()
};
assert_eq!(e.food_in_inventory(), 17);
// Hungry below 12: three breads fill it exactly, then 12 digest away.
e.eat_and_digest();
assert_eq!(e.food_level, 0);
assert_eq!(e.inventory.len(), 1);
assert_eq!(e.inventory[0].count, 5);
// Five carrots are not enough to be full again, and are all eaten.
e.eat_and_digest();
assert_eq!(e.food_level, 5 - 12);
assert!(e.inventory.is_empty());
}
#[test]
fn willingness_to_breed_needs_twelve_food_points() {
let mut e = Ext::default();
assert!(e.wants_more_food() && !e.has_excess_food());
e.inventory.push(stack("minecraft:bread", 6));
assert!(e.has_excess_food() && !e.wants_more_food());
e.food_level = -5;
assert_eq!(e.food_level + e.food_in_inventory(), 19);
}
#[test]
fn the_inventory_has_eight_stacking_slots() {
let mut e = Ext::default();
assert!(e.add_item(stack("minecraft:bread", 100), 64).is_none());
assert_eq!(e.inventory.len(), 2);
assert_eq!(e.inventory[0].count, 64);
for i in 0..6 {
assert!(
e.add_item(stack(&format!("minecraft:item_{i}"), 1), 64)
.is_none()
);
}
assert_eq!(e.inventory.len(), 8);
// Full: another kind is refused, the same kind tops up the stack.
assert!(!e.can_add(&stack("minecraft:stick", 1), 64));
let left = e.add_item(stack("minecraft:bread", 40), 64).unwrap();
assert_eq!(left.count, 40 - 28);
}
#[test]
fn half_stacks_are_thrown() {
let mut e = Ext {
inventory: vec![
stack("minecraft:bread", 10),
stack("minecraft:wheat", 50),
stack("minecraft:wheat", 20),
],
..Default::default()
};
let max = |_: &str| 64;
// Bread is under half a stack and under 24: nothing.
assert!(
e.take_half_stack(|s| &*s.item == "minecraft:bread", max)
.is_none()
);
// 50 wheat is over half a stack: 25 go.
let t = e
.take_half_stack(|s| &*s.item == "minecraft:wheat", max)
.unwrap();
assert_eq!(t.count, 25);
assert_eq!(e.count_item("minecraft:wheat"), 25 + 20);
}
#[test]
fn golems_need_sleep_and_no_golem_nearby() {
let mut e = Ext::default();
assert!(!e.wants_golem(100));
e.last_slept = Some(0);
assert!(e.wants_golem(23_999));
assert!(!e.wants_golem(24_000));
e.last_slept = Some(1000);
e.golem_until = 2000 + 599;
assert!(!e.wants_golem(2500));
assert!(e.wants_golem(2700));
}
#[test]
fn gossip_decays_once_a_day_and_heard_gossip_waits() {
let player = [1, 2, 3, 4];
let mut e = Ext::default();
e.gossips
.add(player, crate::gossip::GossipType::MajorNegative, 25);
e.maybe_decay(100);
assert_eq!(e.last_gossip_decay, 100);
e.maybe_decay(24_099);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
25
);
e.maybe_decay(24_100);
assert_eq!(
e.gossips
.get(player, crate::gossip::GossipType::MajorNegative),
15
);
e.last_gossip_time = 5000;
assert!(!e.can_gossip(5100));
assert!(e.can_gossip(6200));
assert!(e.can_gossip(4000));
}
#[test]
fn villager_food_values() {
assert_eq!(food_points("minecraft:bread"), 4);
assert_eq!(food_points("minecraft:beetroot"), 1);
assert_eq!(food_points("minecraft:apple"), 0);
}
}
+29 -1
View File
@@ -19,6 +19,18 @@ pub fn register(m: &mut Mob) {
g.add(3, LookAtPlayer::new(8.0));
g.add(3, RandomLookAround::default());
m.ai.targets.add(1, HurtByTarget::new());
// NearestHealableRaiderTargetGoal: in a raid, go and heal the other raiders.
m.ai.targets.add(
2,
NearestTarget::new(
super::goals::Prey::Filter(|s| {
super::raider::is_raider(s.species) && s.species != Species::Witch
}),
true,
)
.interval(1)
.when(|m, _| super::raider::has_active_raid(m)),
);
m.ai.targets
.add(3, NearestTarget::player(true).interval(10));
}
@@ -129,7 +141,23 @@ fn witch_attack(m: &mut Mob, who: Who, _power: f32, cx: &mut Cx) {
})
.map_or(20.0, |s| s.health)
};
let (effect, ticks, amplifier) = if dist >= 8.0 {
// A raider target is healed instead: Healing when nearly dead, else
// Regeneration, and the witch drops the target afterwards.
let heals = match who {
Who::Mob(id) => {
cx.w.seen(id)
.is_some_and(|s| super::raider::is_raider(s.species))
}
Who::Player => false,
};
let (effect, ticks, amplifier) = if heals {
m.ai.target = None;
if health <= 4.0 {
("minecraft:instant_health", 1, 0)
} else {
("minecraft:regeneration", 900, 0)
}
} else if dist >= 8.0 {
("minecraft:slowness", 1800, 0)
} else if health >= 8.0 {
("minecraft:poison", 900, 0)
+52
View File
@@ -41,6 +41,7 @@ macro_rules! particle_types {
particle_types! {
Block = "block",
BlockCrumble = "block_crumble",
Trail = "trail",
DustPillar = "dust_pillar",
FallingDust = "falling_dust",
Smoke = "smoke",
@@ -140,6 +141,8 @@ pub struct ParticleOptions {
pub color: [f32; 4],
/// `DustParticleOptions.scale`, `PowerParticleOption.power`, `SpellParticleOption.power`.
pub scale: f32,
/// `TrailParticleOption`: the point it flies to and how many ticks it takes.
pub trail: Option<([f64; 3], i32)>,
}
impl ParticleOptions {
pub fn simple(ty: ParticleType) -> Self {
@@ -148,6 +151,20 @@ impl ParticleOptions {
block: None,
color: [1.0; 4],
scale: 1.0,
trail: None,
}
}
/// `TrailParticleOption(target, color, duration)`.
pub fn trail(target: [f64; 3], rgb: u32, duration: i32) -> Self {
Self {
color: [
((rgb >> 16) & 255) as f32 / 255.0,
((rgb >> 8) & 255) as f32 / 255.0,
(rgb & 255) as f32 / 255.0,
1.0,
],
trail: Some((target, duration)),
..Self::simple(ParticleType::Trail)
}
}
pub fn block(ty: ParticleType, sprite: String, tint: u32) -> Self {
@@ -261,6 +278,10 @@ enum Behaviour {
DragonBreath {
hit_ground: bool,
},
/// `TrailParticle`: eases towards its target over its lifetime.
Trail {
target: [f64; 3],
},
}
#[derive(Clone, Copy, Debug, PartialEq)]
enum DripStage {
@@ -1662,6 +1683,24 @@ impl ParticleEngine {
q.set_power(o.scale);
q
}
T::Trail => {
let (target, duration) = o.trail?;
let mut q = Particle::at(r, ty, p);
let jitter = |r: &mut LegacyRandom| 0.875 + r.next_float() * 0.25;
let (jr, jg, jb) = (jitter(r), jitter(r), jitter(r));
q.set_color(
(o.color[0] * jr).min(1.0),
(o.color[1] * jg).min(1.0),
(o.color[2] * jb).min(1.0),
);
q.size = 0.26;
q.lifetime = duration;
q.has_physics = false;
q.free_move = true;
q.light = Light::FullBright;
q.behaviour = Behaviour::Trail { target };
q
}
};
if particle.set.is_some() {
particle.sprite = self.first(ty);
@@ -2146,6 +2185,19 @@ impl ParticleEngine {
start[2] + p.velocity[2] * f64::from(pos),
];
}
Behaviour::Trail { target } => {
p.previous = p.position;
let age = p.age;
p.age += 1;
if age >= p.lifetime {
p.removed = true;
return;
}
let alpha = 1.0 / f64::from((p.lifetime - p.age).max(1));
for i in 0..3 {
p.position[i] += (target[i] - p.position[i]) * alpha;
}
}
Behaviour::HugeExplosion => {
p.previous = p.position;
let age = p.age;
File diff suppressed because it is too large Load Diff
+148 -2
View File
@@ -422,6 +422,11 @@ fn encode_block_entity(p: (i32, i32, i32), e: &crate::containers::BlockEntity, b
entries.push(("CustomName", string(name)));
}
}
BlockEntity::CreakingHeart(h) => {
if let Some((_, uuid)) = h.creaking {
entries.push(("creaking", uuid_tag(uuid)));
}
}
}
Tag::compound(entries)
}
@@ -443,6 +448,13 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
}),
));
}
if id == "minecraft:creaking_heart" {
let heart = crate::containers::CreakingHeart {
creaking: uuid_from_tag(tag.get("creaking")).map(|uuid| (None, uuid)),
..Default::default()
};
return Some((pos, BlockEntity::CreakingHeart(Box::new(heart))));
}
if id == "minecraft:lectern" {
let lectern = crate::containers::Lectern {
book: tag.get("Book").and_then(item_from_nbt),
@@ -522,7 +534,8 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
BlockEntity::Jukebox(_)
| BlockEntity::Beacon(_)
| BlockEntity::Lectern(_)
| BlockEntity::Banner(_) => {}
| BlockEntity::Banner(_)
| BlockEntity::CreakingHeart(_) => {}
}
Some((pos, entity))
}
@@ -949,6 +962,60 @@ pub fn decode_with(
Some(chunk)
}
/// Read the stored `SkyLight`/`BlockLight` layers of a chunk saved with
/// `isLightOn` (`SerializableChunkData.read` + `ThreadedLevelLightEngine`),
/// so it needs no relighting. A missing sky layer repeats the bottom layer of
/// the section above it (15 above the highest stored one); a missing block
/// layer is dark.
pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
if tag.get("isLightOn") != Some(&Tag::Byte(1)) {
return;
}
let Some(Tag::List(sections)) = tag.get("sections") else {
return;
};
let mut layers: Vec<(Option<&[u8]>, Option<&[u8]>)> = vec![(None, None); SECTIONS];
for section in sections {
let Some(y) = number(section.get("Y")) else {
continue;
};
let si = y as i32 - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&si) {
continue;
}
let layer = |name: &str| match section.get(name) {
Some(Tag::ByteArray(a)) if a.len() == 2048 => Some(&a[..]),
_ => None,
};
layers[si as usize] = (layer("SkyLight"), layer("BlockLight"));
}
let sky_default = if sky_light { 15u8 } else { 0 };
// Sky nibbles of the section above's bottom layer, going down.
let mut above: [u8; 256] = [sky_default; 256];
for si in (0..SECTIONS).rev() {
let (sky, block) = layers[si];
let mut data = Box::new([0u8; 4096]);
let nibble = |a: &[u8], i: usize| (a[i >> 1] >> ((i & 1) * 4)) & 15;
for (i, packed) in data.iter_mut().enumerate() {
let s = match sky {
Some(a) if sky_light => nibble(a, i),
_ => above[i & 255],
};
let b = block.map_or(0, |a| nibble(a, i));
*packed = s << 4 | b;
}
for (i, a) in above.iter_mut().enumerate() {
*a = data[i] >> 4;
}
let mut section = (*chunk.sections[si]).clone();
section.light = Light::Full(data);
section.compact();
chunk.sections[si] = Arc::new(section);
}
chunk.lit = true;
chunk.light_loaded = true;
}
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
/// One dimension folder (`dimensions/minecraft/<name>`). Region files are
/// read lazily by worker threads.
@@ -999,7 +1066,9 @@ impl SaveDir {
pub fn load(&self, x: i32, z: i32, registry: &BlockRegistry, biomes: &Biomes) -> Option<Chunk> {
let root = self.read_record("region", x, z)?;
let tables = self.tables.get().map(|t| &**t);
decode_with(&root, registry, biomes, tables)
let mut chunk = decode_with(&root, registry, biomes, tables)?;
load_light(&root.tag, &mut chunk, self.sky_light);
Some(chunk)
}
/// Entities saved for a chunk (`entities/`; older chunks may still keep
/// them in the chunk's own `entities` list).
@@ -2108,6 +2177,37 @@ mod tests {
assert_eq!((r[1] >> 12) & 0xF, 4, "version 4");
}
#[test]
fn creaking_heart_keeps_its_protector_uuid() {
use crate::containers::{BlockEntity, CreakingHeart};
let heart = CreakingHeart {
creaking: Some((Some(7), [1, 2, 3, 4])),
..Default::default()
};
let tag = encode_block_entity(
(3, 70, -5),
&BlockEntity::CreakingHeart(Box::new(heart)),
"minecraft:creaking_heart",
);
assert_eq!(
tag.get("creaking"),
Some(&Tag::IntArray(vec![1, 2, 3, 4])),
"vanilla stores the protector's UUID under `creaking`"
);
let (pos, entity) = decode_block_entity(&tag).expect("heart decodes");
assert_eq!(pos, (3, 70, -5));
let BlockEntity::CreakingHeart(h) = entity else {
panic!("a creaking heart");
};
// The entity id is resolved again once the creaking is loaded.
assert_eq!(h.creaking, Some((None, [1, 2, 3, 4])));
let lonely = encode_block_entity(
(0, 0, 0),
&BlockEntity::CreakingHeart(Box::default()),
"minecraft:creaking_heart",
);
assert!(lonely.get("creaking").is_none());
}
#[test]
fn light_nibbles_use_vanilla_order() {
let mut a = Box::new([0u8; 4096]);
a[0] = 0xF3; // sky 15, block 3 at x=0
@@ -2117,6 +2217,52 @@ mod tests {
assert_eq!(nibbles(&light, true)[0], 0x5F);
}
#[test]
fn stored_light_loads_with_vanilla_defaults() {
let mut sky = vec![0u8; 2048];
sky[0] = 0x5A; // x=0 -> 10, x=1 -> 5
let section = |y: i8, entries: Vec<(&str, Tag)>| {
let mut all = vec![("Y", Tag::Byte(y))];
all.extend(entries);
Tag::compound(all)
};
let tag = Tag::compound([
("isLightOn", Tag::Byte(1)),
(
"sections",
Tag::List(vec![
section(
-4,
vec![
("SkyLight", Tag::ByteArray(sky)),
("BlockLight", Tag::ByteArray(vec![0x21; 2048])),
],
),
// No sky layer: repeats the bottom layer of the section above.
section(-3, vec![]),
]),
),
]);
let mut chunk = Chunk::empty(0, 0);
load_light(&tag, &mut chunk, true);
assert!(chunk.lit && chunk.light_loaded);
let at = |c: &Chunk, si: usize, i: usize| c.sections[si].light(i);
assert_eq!(at(&chunk, 0, 0), 0xA1, "stored sky 10, block 1");
assert_eq!(at(&chunk, 0, 1), 0x52, "stored sky 5, block 2");
// Section -3 has no layers; above it (-2..) sky defaults to 15.
assert_eq!(at(&chunk, 1, 0), 0xF0);
assert_eq!(at(&chunk, SECTIONS - 1, 5), 0xF0);
let mut dark = Chunk::empty(0, 0);
load_light(&tag, &mut dark, false);
assert_eq!(at(&dark, 1, 0), 0x00, "no skylight dimension");
let mut unlit = Chunk::empty(0, 0);
load_light(
&Tag::compound([("isLightOn", Tag::Byte(0))]),
&mut unlit,
true,
);
assert!(!unlit.lit && !unlit.light_loaded);
}
#[test]
fn level_round_trips_through_the_vanilla_files() {
let dir = std::env::temp_dir().join(format!("horizon-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
+14 -1
View File
@@ -329,10 +329,23 @@ impl Streaming {
self.decorated.insert(key);
if self.in_range(key.0, key.1, 2) {
self.generated_total += 1;
// A chunk saved with its light needs no light job; its
// unlit neighbours still light themselves from it.
let loaded = chunk.light_loaded;
world.chunks.insert(key, Arc::new(chunk));
if loaded {
self.lit.insert(key);
for sy in 0..SECTIONS as i32 {
world.dirty_sections.insert((key.0, sy, key.1));
}
}
for dz in -1..=1 {
for dx in -1..=1 {
world.dirty_light.insert((key.0 + dx, key.1 + dz));
let n = (key.0 + dx, key.1 + dz);
if !loaded || world.chunks.get(&n).is_some_and(|c| !c.light_loaded)
{
world.dirty_light.insert(n);
}
}
}
}
+12 -5
View File
@@ -59,11 +59,18 @@ pub fn block_entities(
.iter_mut()
.zip(loot.fill(&table, seed, 27, Some(biome)))
{
*slot = stack.map(|s| ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
*slot = stack.map(|s| {
let mut item = ItemStack {
item: Arc::from(s.item.as_str()),
count: s.count.max(0) as u32,
damage: s.damage.max(0) as u32,
extra: None,
};
// An ominous bottle's level (the default, 0, is no component).
if let Some(level) = s.ominous_amplifier.filter(|l| *l > 0) {
item.data_mut().ominous_amplifier = Some(level.clamp(0, 4) as u8);
}
item
});
}
}
+146
View File
@@ -0,0 +1,146 @@
//! Dispenser use of buckets: `BucketPickup.pickupBlock` for an empty bucket and
//! `DispensibleContainerItem.emptyContents` for filled ones (`BucketItem`,
//! `MobBucketItem`, `SolidBucketItem`), both without a player.
use super::{
Behaviours, Dimension, LevelAccess, Sim, Ticks,
classes::{Class, Interface},
};
use crate::{
fluid::{FluidKind, FluidState},
registry::BlockStateId,
};
use horizon_core::{position::BlockPos, random::RandomSource};
use std::sync::Arc;
/// What a filled bucket empties into the world.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BucketContent {
/// Water or lava (mob buckets hold water).
Fluid(FluidKind),
/// `SolidBucketItem`: the block placed into an empty space (powder snow).
Powder,
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `BucketPickup.pickupBlock(null, level, pos, state)`: the filled bucket
/// that results, None when the block gives nothing.
pub(crate) fn bucket_pickup(&mut self, pos: BlockPos) -> Option<&'static str> {
let b = self.b;
let state = self.state(pos);
let item = if b.instance_of(state, Class::Liquid) {
match b.fluid(state).kind() {
FluidKind::Water | FluidKind::FlowingWater => "minecraft:water_bucket",
FluidKind::Lava | FluidKind::FlowingLava => "minecraft:lava_bucket",
FluidKind::Empty => return None,
}
} else if b.implements(state, Interface::SimpleWaterlogged)
&& b.table.has(state, b.props.waterlogged)
{
"minecraft:water_bucket"
} else if b.is_block(state, b.named.powder_snow) {
"minecraft:powder_snow_bucket"
} else {
return None;
};
self.pickup_block(pos, state).then_some(item)
}
/// `BucketItem.emptyContents(null, level, pos, null)`. `sound` is the
/// bucket's empty sound (mob buckets have their own).
pub(crate) fn bucket_empty(
&mut self,
pos: BlockPos,
content: BucketContent,
sound: &str,
) -> bool {
let b = self.b;
let fluid = match content {
BucketContent::Powder => {
if self.is_in_valid_bounds(pos) && b.is_air(self.state(pos)) {
let snow = b.table.default_state(b.named.powder_snow);
self.set_block_and_update(pos, snow);
self.game_event(pos, "minecraft:fluid_place");
self.empty_sound(pos, sound);
return true;
}
return false;
}
BucketContent::Fluid(fluid) => fluid,
};
let state = self.state(pos);
// canBeReplaced(fluid): replaceable or not solid (portals refuse).
let may_replace = !b.instance_of(state, Class::EndPortal)
&& !b.instance_of(state, Class::EndGateway)
&& (b.is_replaceable(state) || !b.is_solid(state));
let liquid_container = self.is_liquid_container(state);
let container = liquid_container && self.can_place_liquid(state, fluid);
let place_liquid = may_replace || container;
if !(b.is_air(state) || place_liquid) {
return false;
}
let water = matches!(fluid, FluidKind::Water | FluidKind::FlowingWater);
if water && self.level.dimension() == Dimension::Nether {
// WATER_EVAPORATES: the water hisses away.
let pitch = 2.6 + (self.random().next_float() - self.random().next_float()) * 0.8;
self.emit(super::LevelEvent::Sound {
pos,
sound: "minecraft:block.fire.extinguish".into(),
volume: 0.5,
pitch,
});
return true;
}
if liquid_container && water {
self.place_liquid(pos, state, FluidState::new(FluidKind::Water, 8, false));
self.empty_sound(pos, sound);
return true;
}
if may_replace && !b.instance_of(state, Class::Liquid) {
self.destroy_block(pos, true, super::flags::UPDATE_LIMIT);
}
let source = FluidState::new(
if water {
FluidKind::Water
} else {
FluidKind::Lava
},
8,
false,
);
let legacy: BlockStateId = b.legacy_block(source);
if !self.set_block(pos, legacy, super::flags::UPDATE_ALL_IMMEDIATE)
&& !self.fluid_at(pos).is_source()
{
return false;
}
self.empty_sound(pos, sound);
true
}
fn empty_sound(&mut self, pos: BlockPos, sound: &str) {
let sound: Arc<str> = sound.into();
self.sound(pos, &sound, 1.0, 1.0);
self.game_event(pos, "minecraft:fluid_place");
}
}
impl Behaviours {
/// `BucketPickup.pickupBlock` by a dispenser: the filled bucket item.
pub fn bucket_pickup<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
) -> Option<&'static str> {
self.sim(level, ticks).bucket_pickup(pos)
}
/// `DispensibleContainerItem.emptyContents(null, level, pos, null)`.
pub fn bucket_empty<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
content: BucketContent,
sound: &str,
) -> bool {
self.sim(level, ticks).bucket_empty(pos, content, sound)
}
}
@@ -0,0 +1,83 @@
//! The creaking heart block (`CreakingHeartBlock`): its state follows the
//! pale oak logs on both ends of its axis and the `creaking_active`
//! environment attribute. The block entity (protector, particles, resin)
//! lives with the entities in the client.
use super::{Behaviours, Dimension, LevelAccess, Sim, Ticks, update::rel};
use crate::registry::BlockStateId;
use horizon_core::{geometry::Direction, position::BlockPos};
/// `Direction.Axis.getDirections()`.
fn axis_directions(axis: &str) -> [Direction; 2] {
match axis {
"x" => [Direction::West, Direction::East],
"z" => [Direction::North, Direction::South],
_ => [Direction::Down, Direction::Up],
}
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `EnvironmentAttributes.CREAKING_ACTIVE`: the overworld day timeline
/// turns it on from 12600 to 23400.
pub(crate) fn creaking_active(&self) -> bool {
self.level.dimension() == Dimension::Overworld
&& (12600..23401).contains(&self.level.day_time().rem_euclid(24000))
}
/// `CreakingHeartBlock.hasRequiredLogs`: pale oak logs along the axis.
pub(crate) fn heart_has_required_logs(&self, state: BlockStateId, pos: BlockPos) -> bool {
let b = self.b;
let axis = b.table.text(state, b.props.axis);
axis_directions(axis).into_iter().all(|d| {
let neighbour = self.state(rel(pos, d));
b.in_set(neighbour, &b.tags.pale_oak_logs)
&& b.table.text(neighbour, b.props.axis) == axis
})
}
/// `CreakingHeartBlock.updateState`: an uprooted heart with its logs wakes
/// (at night) or goes dormant.
pub(crate) fn heart_update_state(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId {
let b = self.b;
let uprooted = b.table.text(state, b.props.creaking_heart_state) == "uprooted";
if uprooted && self.heart_has_required_logs(state, pos) {
let next = if self.creaking_active() {
"awake"
} else {
"dormant"
};
b.table.set_text(state, b.props.creaking_heart_state, next)
} else {
state
}
}
/// `CreakingHeartBlock.tick` (scheduled by `updateShape`).
pub(crate) fn heart_tick(&mut self, state: BlockStateId, pos: BlockPos) {
let next = self.heart_update_state(state, pos);
if next != state {
self.set_block_and_update(pos, next);
}
}
/// `CreakingHeartBlock.getStateForPlacement` after the axis is set.
pub(crate) fn heart_placement(&self, state: BlockStateId, pos: BlockPos) -> BlockStateId {
self.heart_update_state(state, pos)
}
}
impl Behaviours {
/// `EnvironmentAttributes.CREAKING_ACTIVE` at the level's time.
pub fn creaking_active<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
) -> bool {
self.sim(level, ticks).creaking_active()
}
/// `CreakingHeartBlock.hasRequiredLogs`.
pub fn creaking_heart_has_logs<L: LevelAccess + ?Sized>(
&self,
level: &mut L,
ticks: &mut Ticks,
pos: BlockPos,
state: BlockStateId,
) -> bool {
self.sim(level, ticks).heart_has_required_logs(state, pos)
}
}
+2
View File
@@ -451,6 +451,7 @@ tags! {
enables_bubble_column_push_up = "enables_bubble_column_push_up",
enables_bubble_column_drag_down = "enables_bubble_column_drag_down",
shulker_boxes = "shulker_boxes",
pale_oak_logs = "pale_oak_logs",
convertible_to_mud = "convertible_to_mud",
grows_crops = "grows_crops",
candles = "candles",
@@ -553,6 +554,7 @@ props! {
honey_level = "honey_level",
bloom = "bloom",
natural = "natural",
creaking_heart_state = "creaking_heart_state",
cracked = "cracked",
has_book = "has_book",
signal_fire = "signal_fire",
+1 -1
View File
@@ -178,7 +178,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
// ---- liquid containers ----
/// `LiquidBlockContainer` membership (`canHoldAnyFluid` first clause).
fn is_liquid_container(&self, state: BlockStateId) -> bool {
pub(super) fn is_liquid_container(&self, state: BlockStateId) -> bool {
self.b.implements(state, Interface::LiquidBlockContainer)
|| self.b.implements(state, Interface::SimpleWaterlogged)
}
+3
View File
@@ -101,6 +101,8 @@ pub mod states;
pub mod ticks;
mod bonemeal;
mod buckets;
mod creaking;
mod falling;
mod feature_world;
mod fluids;
@@ -126,6 +128,7 @@ mod growth_tests;
#[cfg(test)]
mod tests;
pub use buckets::BucketContent;
pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags};
pub use falling::Landing;
pub use interact::{InteractionResult, PlayerContext, PlayerEffect};
+6 -1
View File
@@ -786,7 +786,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
);
Some(table.set_text(default, p.orientation, &orientation))
}
Class::CreakingHeart | Class::RotatedPillar | Class::InfestedRotatedPillar => {
Class::CreakingHeart => {
let state =
table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face)));
Some(self.heart_placement(state, ctx.pos))
}
Class::RotatedPillar | Class::InfestedRotatedPillar => {
Some(table.set_text(default, p.axis, super::states::axis_name(axis_of(ctx.face))))
}
Class::DecoratedPot => {
+113
View File
@@ -43,6 +43,7 @@ pub(crate) struct TestLevel {
air: BlockStateId,
random: LegacyRandom,
pub time: i64,
pub day_time: i64,
pub events: Vec<LevelEvent>,
pub block_light: HashMap<BlockPos, i32>,
}
@@ -53,6 +54,7 @@ impl TestLevel {
air: b.air(),
random: LegacyRandom::new(42),
time: 0,
day_time: 0,
events: Vec::new(),
block_light: HashMap::new(),
}
@@ -74,6 +76,9 @@ impl LevelAccess for TestLevel {
fn game_time(&self) -> i64 {
self.time
}
fn day_time(&self) -> i64 {
self.day_time
}
fn block_light(&self, pos: BlockPos) -> i32 {
self.block_light.get(&pos).copied().unwrap_or(0)
}
@@ -917,3 +922,111 @@ fn dripstone_fills_cauldrons() {
}
assert_eq!(w.name(BlockPos::new(0, 5, 0)), "water_cauldron[level=1]");
}
#[test]
fn dispenser_buckets_pick_up_and_empty() {
let mut w = world!();
let at = BlockPos::new(0, 10, 0);
let water = w.id("water", &[("level", "0")]);
w.put(at, water);
let picked = w.b().bucket_pickup(&mut w.level, &mut w.ticks, at);
assert_eq!(picked, Some("minecraft:water_bucket"));
assert_eq!(w.get(at), w.b().air());
// Flowing water gives nothing.
let flowing = w.id("water", &[("level", "3")]);
w.put(at, flowing);
assert_eq!(w.b().bucket_pickup(&mut w.level, &mut w.ticks, at), None);
// A waterlogged slab is drained and stays a slab.
let slab = w.id("oak_slab", &[("waterlogged", "true")]);
w.put(at, slab);
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:water_bucket")
);
assert_eq!(w.prop(at, "waterlogged"), "false");
// Powder snow comes up as its bucket.
let snow = w.id("powder_snow", &[]);
w.put(at, snow);
assert_eq!(
w.b().bucket_pickup(&mut w.level, &mut w.ticks, at),
Some("minecraft:powder_snow_bucket")
);
// Emptying water into air makes a source; stone refuses.
let sound = "minecraft:item.bucket.empty";
let content = BucketContent::Fluid(crate::fluid::FluidKind::Water);
assert!(
w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
assert_eq!(w.name(at), "water[level=0]");
let stone = w.id("stone", &[]);
w.put(at, stone);
assert!(
!w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
// Water fills a waterloggable slab instead of replacing it.
let dry = w.id("oak_slab", &[]);
w.put(at, dry);
assert!(
w.b()
.bucket_empty(&mut w.level, &mut w.ticks, at, content, sound)
);
assert_eq!(w.prop(at, "waterlogged"), "true");
// Powder snow only goes into empty space.
let air = w.b().air();
w.put(at, air);
assert!(w.b().bucket_empty(
&mut w.level,
&mut w.ticks,
at,
BucketContent::Powder,
"minecraft:item.bucket.empty_powder_snow"
));
assert_eq!(w.name(at), "powder_snow[]");
}
#[test]
fn creaking_heart_follows_its_logs_and_the_night() {
let mut w = world!();
let heart_at = BlockPos::new(0, 10, 0);
let log = |w: &World, axis: &str| w.id("pale_oak_log", &[("axis", axis)]);
let heart = w.id(
"creaking_heart",
&[("axis", "y"), ("creaking_heart_state", "uprooted")],
);
let (below, above) = (BlockPos::new(0, 9, 0), BlockPos::new(0, 11, 0));
w.put(heart_at, heart);
w.put(below, log(&w, "y"));
// A log along another axis does not count.
w.put(above, log(&w, "x"));
assert!(
!w.b()
.creaking_heart_has_logs(&mut w.level, &mut w.ticks, heart_at, heart)
);
// Day: a log update wakes the uprooted heart to dormant.
let up = log(&w, "y");
w.set(above, up);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "dormant");
// Night: the same trunk wakes a fresh heart up.
w.level.day_time = 14000;
w.put(heart_at, heart);
w.put(above, w.b().air());
w.set(above, up);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "awake");
// Placed without logs it stays uprooted.
w.put(above, w.b().air());
w.put(heart_at, heart);
let air = w.b().air();
w.set(above, air);
for _ in 0..3 {
w.tick();
}
assert_eq!(w.prop(heart_at, "creaking_heart_state"), "uprooted");
}
+1
View File
@@ -146,6 +146,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
Class::Observer => self.observer_tick(pos, state),
Class::Eyeblossom => self.eyeblossom_tick(state, pos, false),
Class::CreakingHeart => self.heart_tick(state, pos),
Class::DriedGhast => self.dried_ghast_tick(state, pos),
Class::RedstoneLamp => self.lamp_tick(pos, state),
Class::RedstoneTorch => self.torch_tick(pos, state),
+4 -1
View File
@@ -23,6 +23,8 @@ pub struct LootStack {
pub potion: Option<String>,
/// Set by exploration_map (the map_id component of a found map).
pub map: bool,
/// Set by set_ominous_bottle_amplifier.
pub ominous_amplifier: Option<i32>,
}
impl LootStack {
fn new(item: &str) -> Self {
@@ -33,6 +35,7 @@ impl LootStack {
enchantments: Vec::new(),
potion: None,
map: false,
ominous_amplifier: None,
}
}
pub fn is_empty(&self) -> bool {
@@ -584,7 +587,7 @@ impl Context<'_> {
}
}
"minecraft:set_ominous_bottle_amplifier" => {
self.int(&f["amplifier"]);
stack.ominous_amplifier = Some(self.int(&f["amplifier"]));
}
"minecraft:set_instrument" => {
let options = data.holder_set("instrument", &f["options"]);
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Compare Horizon's light engine with the vanilla 26.3 server.
Builds a scene of slabs, stairs, snow layers, trapdoors, lanterns, glass,
leaves, water and glowstone in a fresh vanilla world, lets the vanilla light
engine settle, stops the server so the SkyLight/BlockLight arrays are saved,
then relights every saved chunk with `examples/light_parity` and requires every
value to agree. The example also replays block edits through the incremental
`light::relight` and checks them against a full relight.
test_light_parity.py [--seed N] [--keep]
"""
import argparse
import shutil
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
LOCAL = ROOT / '.local'
RESOURCES = LOCAL / 'horizon-client' / '26.3'
SERVER = LOCAL / 'minecraft' / '26.3' / 'jars' / 'server.jar'
# Absolute coordinates well above the terrain, inside force-loaded chunks.
SCENE = [
'forceload add 0 0 63 63',
'sleep 6',
# Closed room with a bottom-slab roof and a glowstone lamp.
'fill 2 170 2 20 175 20 stone hollow',
'fill 2 176 2 20 176 20 stone_slab[type=bottom]',
'setblock 10 171 10 glowstone',
# Stairs, top and bottom; snow layers; trapdoors; lanterns; water.
'fill 4 171 4 4 171 18 oak_stairs[facing=east,half=top]',
'fill 6 171 4 6 171 18 stone_brick_stairs[facing=north,half=bottom,shape=inner_left]',
'fill 12 171 4 18 171 6 snow[layers=3]',
'fill 12 172 8 18 172 8 oak_trapdoor[half=bottom,open=false]',
'fill 12 173 12 18 173 12 oak_trapdoor[half=top,open=true,facing=north]',
'setblock 14 171 14 lantern',
'setblock 15 175 15 soul_lantern[hanging=true]',
'fill 8 171 16 9 172 17 water',
# Open-air structures: sky light through slabs, stairs and leaves.
'fill 24 170 24 46 170 46 stone',
'fill 26 171 26 44 171 26 stone_slab[type=top]',
'fill 26 171 28 44 171 28 stone_slab[type=bottom]',
'fill 26 172 30 44 172 30 oak_leaves[persistent=true]',
'fill 26 171 32 30 171 40 glass',
'fill 32 171 32 36 171 40 oak_stairs[facing=south,half=bottom]',
'fill 38 171 32 38 175 40 stone_brick_wall',
'fill 40 171 32 44 171 40 dirt_path',
'fill 40 172 34 44 172 34 daylight_detector',
'fill 24 180 50 46 180 50 stone_slab[type=double]',
'fill 24 178 52 46 178 52 oak_stairs[facing=west,half=top]',
'setblock 30 171 44 torch',
'setblock 34 171 44 campfire',
'setblock 38 171 44 sea_lantern',
'setblock 42 171 44 lava',
'sleep 10',
# Edits after the first lighting pass, so vanilla updates incrementally.
'setblock 10 171 10 air',
'setblock 10 176 10 air',
'setblock 30 171 26 air',
'fill 26 172 30 30 172 30 air',
# Vanilla saves a chunk only when its blocks changed, so light that
# reached an untouched chunk later is stale on disk: mark every compared
# chunk (0..2, 0..3) as edited so it is written at shutdown.
*[f'setblock {x * 16 + 8} 169 {z * 16 + 8} stone' for x in range(3) for z in range(4)],
'sleep 8',
]
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', default='4242')
parser.add_argument('--keep', action='store_true')
args = parser.parse_args()
run = LOCAL / 'rust-light-parity'
shutil.rmtree(run, ignore_errors=True)
run.mkdir(parents=True)
command = [sys.executable, str(ROOT / 'tools' / 'vanilla_world_check.py'), '--jar', str(SERVER),
'--dir', str(run), '--world', 'world', '--seed', args.seed, '--wait-after', '8']
for step in SCENE:
command += ['--command', step]
if subprocess.run(command).returncode:
sys.exit('vanilla server reported problems')
dimension = run / 'world' / 'dimensions' / 'minecraft' / 'overworld'
if not (dimension / 'region').is_dir():
dimension = run / 'world'
for extra in (['--chunks', '0', '0', '2', '3'], ['--incremental', '100']):
status = subprocess.run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client',
'--example', 'light_parity', '--', str(RESOURCES), str(dimension), *extra],
cwd=ROOT).returncode
if status:
sys.exit('light mismatch against vanilla')
print('light parity ok')
if not args.keep:
shutil.rmtree(run, ignore_errors=True)
if __name__ == '__main__':
main()