Merge branch 'parity/mobs-b' into parity-base
# Conflicts: # crates/horizon-client/examples/entity_anim_fixture.rs # crates/horizon-client/examples/mob_ai_probe.rs # crates/horizon-client/src/game/creatures.rs # crates/horizon-client/src/mobs.rs # crates/horizon-client/src/mobs/ai.rs # mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMobAiOracle.java # tools/test_mob_ai_parity.py
This commit is contained in:
@@ -8,7 +8,7 @@ use horizon_client::mobs::{
|
||||
anim::{self, Poses, State},
|
||||
aquatic, body_anim as b_anim, equine, guardian,
|
||||
keyframes::AnimationState,
|
||||
shulker, species, tame,
|
||||
shulker, sniffer, species, tame,
|
||||
};
|
||||
use horizon_core::geometry::Vec3;
|
||||
use serde_json::{Value, json};
|
||||
@@ -182,6 +182,30 @@ fn entity_state(mob: &mut Mob, species: Species, case: &Value) {
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::Sniffer => {
|
||||
if flag("isSearching") {
|
||||
mob.extra.variant = sniffer::SEARCHING;
|
||||
}
|
||||
// Sniffer's animation states, in `sniffer::anim`'s order.
|
||||
for (i, k) in [
|
||||
"feelingHappyAnimationState",
|
||||
"scentingAnimationState",
|
||||
"sniffingAnimationState",
|
||||
"diggingAnimationState",
|
||||
"risingAnimationState",
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
mob.anim.states[i].started = case[k].as_f64().map(|v| v as f32);
|
||||
}
|
||||
}
|
||||
Species::HappyGhast => {
|
||||
mob.extra.head = case["bodyItem"].as_str().map(Into::into);
|
||||
if flag("isRidden") {
|
||||
mob.rider = Some(Default::default());
|
||||
}
|
||||
}
|
||||
Species::Witch if flag("isHoldingItem") => {
|
||||
mob.extra.main_hand = Some("minecraft:potion".into());
|
||||
}
|
||||
@@ -225,8 +249,12 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
let base = base.replace("undead_horse#", "zombie_horse#");
|
||||
// The breeze's wind and eyes and the creaking's eyes are layers of
|
||||
// the species' own model class.
|
||||
let base = base.replace("#wind", "#main").replace("#eyes", "#main");
|
||||
// the species' own model class; LlamaDecorLayer's model animates like
|
||||
// the llama.
|
||||
let base = base
|
||||
.replace("#wind", "#main")
|
||||
.replace("#eyes", "#main")
|
||||
.replace("#decor", "#main");
|
||||
let base = base.trim_start_matches("cold_").trim_start_matches("warm_");
|
||||
let Some(def) = species::ALL.iter().find(|d| {
|
||||
d.model == layer
|
||||
|
||||
@@ -56,6 +56,7 @@ struct Scenario {
|
||||
spawning: bool,
|
||||
/// The player hits a mob for 1 at the start of a tick: (tick, mob index).
|
||||
hurts: Vec<(i32, usize)>,
|
||||
hand: Option<String>,
|
||||
mobs: Vec<MobSpec>,
|
||||
}
|
||||
|
||||
@@ -101,6 +102,8 @@ fn parse(text: &str) -> Vec<Scenario> {
|
||||
} else if let Some(t) = opt.strip_prefix("turn=") {
|
||||
let (tick, yaw) = t.split_once(',').unwrap();
|
||||
s.turn = Some((tick.parse().unwrap(), yaw.parse().unwrap()));
|
||||
} else if let Some(item) = opt.strip_prefix("hand=") {
|
||||
s.hand = Some(item.to_owned());
|
||||
} else {
|
||||
panic!("unknown player option {opt}");
|
||||
}
|
||||
@@ -262,6 +265,11 @@ fn seen(m: &Mob) -> Seen {
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
stats: [
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -465,9 +473,10 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob) {
|
||||
u8::from(m.ai.jumping)
|
||||
);
|
||||
let _ = write!(out, "\trng {:x}", m.random.state());
|
||||
if let Some((acts, mem)) = horizon_client::mobs::villager_brain::describe(m)
|
||||
let brain = horizon_client::mobs::villager_brain::describe(m)
|
||||
.or_else(|| horizon_client::mobs::monster_brain::describe(m))
|
||||
{
|
||||
.or_else(|| horizon_client::mobs::animal_brain::describe(m));
|
||||
if let Some((acts, mem)) = brain {
|
||||
let _ = write!(out, "\tact {acts}\tmem {mem}");
|
||||
}
|
||||
out.push('\n');
|
||||
@@ -590,6 +599,15 @@ fn main() -> horizon_client::Result<()> {
|
||||
match flag.as_str() {
|
||||
"persistent" => m.persistent = true,
|
||||
"noai" => m.no_ai = true,
|
||||
"inlove" => m.extra.in_love = 600,
|
||||
"tame" => m.extra.tame = true,
|
||||
x if x.starts_with("age=") => m.extra.age = x[4..].parse().unwrap(),
|
||||
x if x.starts_with("strength=") => m.extra.variant2 = x[9..].parse().unwrap(),
|
||||
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
|
||||
x if x.starts_with("leashto=") => {
|
||||
let n: u32 = x[8..].parse().unwrap();
|
||||
m.extra.leash = Some(horizon_client::mobs::leash::Holder::Mob(100_000 + n));
|
||||
}
|
||||
other => panic!("unknown mob flag {other}"),
|
||||
}
|
||||
}
|
||||
@@ -609,6 +627,10 @@ fn main() -> horizon_client::Result<()> {
|
||||
spec.seed,
|
||||
);
|
||||
}
|
||||
// The same for the sniffer's and the happy ghast's brains.
|
||||
if horizon_client::mobs::animal_brain::kind_of(&m).is_some() {
|
||||
horizon_client::mobs::animal_brain::init(&mut m, spec.seed);
|
||||
}
|
||||
mobs.push(m);
|
||||
}
|
||||
let mut player = s.player.map(|p| {
|
||||
@@ -624,7 +646,7 @@ fn main() -> horizon_client::Result<()> {
|
||||
creative: s.creative,
|
||||
sneaking: false,
|
||||
look: [0.0, 0.0, 1.0],
|
||||
main_hand: None,
|
||||
main_hand: s.hand.as_deref().map(Into::into),
|
||||
off_hand: None,
|
||||
head: None,
|
||||
armor_cover: 0.0,
|
||||
@@ -643,6 +665,35 @@ fn main() -> horizon_client::Result<()> {
|
||||
for (i, m) in mobs.iter().enumerate() {
|
||||
print(&mut out, 0, i, m);
|
||||
}
|
||||
// The MobWorld every step sees, over a snapshot of the mobs.
|
||||
macro_rules! mob_world {
|
||||
($snapshot:expr) => {
|
||||
MobWorld {
|
||||
teams: Default::default(),
|
||||
world: &world,
|
||||
registry,
|
||||
facts: &facts,
|
||||
collision: &collision,
|
||||
data: &data,
|
||||
player: player.clone(),
|
||||
others: $snapshot,
|
||||
daylight: (s.time.rem_euclid(24000)) < 12000,
|
||||
game_time: world.game_time,
|
||||
day_time: world.day_time,
|
||||
raining: s.rain,
|
||||
thundering: s.thunder,
|
||||
nether: false,
|
||||
block_tags: &items.block_tags,
|
||||
biomes: &biomes,
|
||||
mob_griefing: true,
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
}
|
||||
};
|
||||
}
|
||||
for t in 1..=s.ticks {
|
||||
world.game_time += 1;
|
||||
let mut heart_events_later: Vec<HeartEvent> = Vec::new();
|
||||
@@ -665,31 +716,8 @@ fn main() -> horizon_client::Result<()> {
|
||||
p.look = [f64::from(sin), -0.0, f64::from(cos)];
|
||||
p.yaw = yaw;
|
||||
}
|
||||
let snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = MobWorld {
|
||||
teams: Default::default(),
|
||||
world: &world,
|
||||
registry,
|
||||
facts: &facts,
|
||||
collision: &collision,
|
||||
data: &data,
|
||||
player: player.clone(),
|
||||
others: &snapshot,
|
||||
daylight: (s.time.rem_euclid(24000)) < 12000,
|
||||
game_time: world.game_time,
|
||||
day_time: world.day_time,
|
||||
raining: s.rain,
|
||||
thundering: s.thunder,
|
||||
nether: false,
|
||||
block_tags: &items.block_tags,
|
||||
biomes: &biomes,
|
||||
mob_griefing: true,
|
||||
difficulty: LocalDifficulty::new(2, world.day_time, 0, 0.0),
|
||||
end: false,
|
||||
world_seed: 0,
|
||||
// FlatLevelSource.getSeaLevel.
|
||||
sea_level: -63,
|
||||
};
|
||||
let mut snapshot: Vec<Seen> = mobs.iter().filter(|m| !m.removed).map(seen).collect();
|
||||
let w = mob_world!(&snapshot);
|
||||
let mut events = Vec::new();
|
||||
let mut heart_events = Vec::new();
|
||||
let mut added = Vec::new();
|
||||
@@ -739,10 +767,12 @@ fn main() -> horizon_client::Result<()> {
|
||||
#[allow(unused_mut)] // filled only with the rng-trace feature
|
||||
let mut traces: Vec<String> = Vec::new();
|
||||
let mut pushes = Vec::new();
|
||||
for (i, m) in mobs.iter_mut().enumerate() {
|
||||
if m.removed {
|
||||
for i in 0..mobs.len() {
|
||||
if mobs[i].removed {
|
||||
continue;
|
||||
}
|
||||
let w = mob_world!(&snapshot);
|
||||
let m = &mut mobs[i];
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
#[cfg(feature = "rng-trace")]
|
||||
@@ -756,14 +786,21 @@ fn main() -> horizon_client::Result<()> {
|
||||
}
|
||||
}
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
let _ = i;
|
||||
if !alive {
|
||||
m.removed = true;
|
||||
}
|
||||
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
||||
// ServerLevel ticks entities one after another: the ones
|
||||
// after this mob see it as it is now.
|
||||
if let Some(e) = snapshot.iter_mut().find(|e| e.id == mobs[i].id) {
|
||||
*e = seen(&mobs[i]);
|
||||
e.alive &= !mobs[i].removed;
|
||||
}
|
||||
}
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
let w = mob_world!(&snapshot);
|
||||
// ServerLevel.tickBlockEntities: the hearts (none ticks once uprooted).
|
||||
heart_events.append(&mut heart_events_later);
|
||||
for (at, h) in &mut hearts {
|
||||
|
||||
@@ -135,6 +135,11 @@ pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
|
||||
.flatten(),
|
||||
profession: m.extra.variant2,
|
||||
xp: horizon_client::mobs::villager::xp(m),
|
||||
stats: [
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
],
|
||||
}
|
||||
}
|
||||
impl Game<'_> {
|
||||
@@ -449,7 +454,7 @@ impl Game<'_> {
|
||||
}
|
||||
self.tick_raids();
|
||||
let uuid = self.level.player_uuid;
|
||||
let snapshot: Vec<Seen> = self.mobs.iter().map(|m| seen(m, uuid)).collect();
|
||||
let mut 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();
|
||||
@@ -457,24 +462,34 @@ impl Game<'_> {
|
||||
// the like draw from it, and it goes on from where they left it.
|
||||
let mut scratch = self.world.random.clone();
|
||||
{
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
let mut pushes = Vec::new();
|
||||
mobs.retain_mut(|m| {
|
||||
let mut keep = Vec::with_capacity(mobs.len());
|
||||
for i in 0..mobs.len() {
|
||||
let w = self.mob_world_base(&snapshot);
|
||||
let m = &mut mobs[i];
|
||||
if !w
|
||||
.world
|
||||
.loaded(m.position.x.floor() as i32, m.position.z.floor() as i32)
|
||||
{
|
||||
return !m.hostile() || m.persistent;
|
||||
keep.push(!m.hostile() || m.persistent);
|
||||
continue;
|
||||
}
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
let keep = m.tick(&w, &mut scratch, &mut events);
|
||||
let kept = m.tick(&w, &mut scratch, &mut events);
|
||||
horizon_client::mobs::take_mob_pushes(&mut events, from, &mut pushes);
|
||||
if !keep && !m.alive() && !m.removed {
|
||||
if !kept && !m.alive() && !m.removed {
|
||||
dead.push(m.clone());
|
||||
}
|
||||
keep
|
||||
});
|
||||
keep.push(kept);
|
||||
// ServerLevel ticks entities one after another: the ones
|
||||
// after this mob see it as it is now.
|
||||
snapshot[i] = seen(m, uuid);
|
||||
snapshot[i].alive &= kept;
|
||||
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
|
||||
}
|
||||
let mut flags = keep.into_iter();
|
||||
mobs.retain(|_| flags.next().unwrap_or(true));
|
||||
for m in &mut mobs {
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
}
|
||||
@@ -896,7 +911,21 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
},
|
||||
MobEvent::Breed { parent, partner } => self.breed(parent, partner),
|
||||
MobEvent::Breed {
|
||||
parent,
|
||||
partner,
|
||||
llama,
|
||||
} => self.breed(parent, partner, llama),
|
||||
MobEvent::LockGaze { mob, partner } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
horizon_client::mobs::animal_brain::lock_gaze(m, partner);
|
||||
}
|
||||
}
|
||||
MobEvent::BreedTarget { mob, partner } => {
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
horizon_client::mobs::animal_brain::set_breed_partner(m, partner);
|
||||
}
|
||||
}
|
||||
MobEvent::LeashBreak { mob, drop, sound } => self.break_leash(mob, drop, sound),
|
||||
MobEvent::Vibration { from, to, ticks } => {
|
||||
self.mob_vibration_particle(from, to, ticks)
|
||||
@@ -981,7 +1010,12 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
/// Animal.spawnChildFromBreeding
|
||||
fn breed(&mut self, parent: u32, partner: u32) {
|
||||
fn breed(
|
||||
&mut self,
|
||||
parent: u32,
|
||||
partner: u32,
|
||||
llama: Option<Box<horizon_client::mobs::llama::Offspring>>,
|
||||
) {
|
||||
let Some(p) = self.mobs.iter().find(|m| m.id == parent).cloned() else {
|
||||
return;
|
||||
};
|
||||
@@ -1034,6 +1068,12 @@ impl Game<'_> {
|
||||
&& let Some(child) = self.mobs.iter_mut().find(|m| m.id == id)
|
||||
{
|
||||
child.extra.age = -24000;
|
||||
// A llama's baby was drawn in the parent's tick, with the
|
||||
// experience.
|
||||
if let Some(o) = llama {
|
||||
horizon_client::mobs::llama::apply_offspring(child, &o);
|
||||
return;
|
||||
}
|
||||
if horizon_client::mobs::equine::is_equine(p.species()) {
|
||||
let other = q.clone().unwrap_or_else(|| p.clone());
|
||||
let mut r = self.world.random.clone();
|
||||
|
||||
@@ -1943,7 +1943,7 @@ impl Game<'_> {
|
||||
}
|
||||
// Leashable.dropLeash: a lead item at the leashed entity's feet.
|
||||
let drop = |game: &mut Self, j: usize| {
|
||||
if game.mobs[j].extra.leash.take().is_some() {
|
||||
if horizon_client::mobs::leash::remove(&mut game.mobs[j]).is_some() {
|
||||
let at = game.mobs[j].position;
|
||||
game.spawn_at_location(at, 0.0, ItemStack::new("minecraft:lead", 1));
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ impl Game<'_> {
|
||||
let id = self.mobs[index].id;
|
||||
self.break_leash(id, true, false);
|
||||
let was_empty = self.mobs[index].rider.is_none();
|
||||
// addPassenger: the rider is not standing on top, so no still
|
||||
// timeout.
|
||||
self.mobs[index].extra.counter = 0;
|
||||
self.yaw = self.mobs[index].yaw;
|
||||
self.riding = Some(id);
|
||||
self.mount.reset_jump();
|
||||
@@ -62,6 +65,12 @@ impl Game<'_> {
|
||||
}
|
||||
/// Getting off lands on top of it.
|
||||
pub(super) fn dismount_happy_ghast(&mut self, id: u32) {
|
||||
// removePassenger: held still for half a second, and with no one
|
||||
// aboard the ghast forgets its home.
|
||||
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
|
||||
m.extra.counter = 10;
|
||||
m.ai.home = None;
|
||||
}
|
||||
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -76,7 +76,7 @@ impl Game<'_> {
|
||||
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
|
||||
return;
|
||||
};
|
||||
if m.extra.leash.take().is_none() {
|
||||
if horizon_client::mobs::leash::remove(m).is_none() {
|
||||
return;
|
||||
}
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
|
||||
@@ -10,20 +10,19 @@ use horizon_client::{
|
||||
use horizon_core::random::RandomSource;
|
||||
|
||||
impl Game<'_> {
|
||||
/// An egg item at the parent, a plop and some experience.
|
||||
/// The egg item at the parent (`Sniffer.spawnChildFromBreeding`; the
|
||||
/// brain already played the plop and dropped the experience).
|
||||
pub(super) fn lay_sniffer_egg(&mut self, parent: &Mob) {
|
||||
let at = [parent.position.x, parent.position.y, parent.position.z];
|
||||
// new ItemEntity(level, x, y, z, stack): a little random push.
|
||||
let vx = self.world.random.next_double() * 0.2 - 0.1;
|
||||
let vz = self.world.random.next_double() * 0.2 - 0.1;
|
||||
self.spawn_item(
|
||||
ItemStack::new("minecraft:sniffer_egg", 1),
|
||||
at,
|
||||
[0.0, 0.2, 0.0],
|
||||
[vx, 0.2, vz],
|
||||
10,
|
||||
);
|
||||
let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 0.5;
|
||||
self.audio
|
||||
.play("minecraft:block.sniffer_egg.plop", Some(at), 1.0, pitch);
|
||||
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
|
||||
self.spawn_orbs(at, xp);
|
||||
}
|
||||
/// A snifflet where the egg was.
|
||||
pub(super) fn hatch_sniffer(&mut self, pos: [i32; 3]) {
|
||||
@@ -42,8 +41,10 @@ impl Game<'_> {
|
||||
m.head_yaw = yaw;
|
||||
}
|
||||
}
|
||||
/// `Sniffer.emitDiggingParticles`: block dust and the digging sound
|
||||
/// between the 1.7th and the 6th second of the digging animation.
|
||||
/// The sniffer's client-side effects: `SnifferSoundInstance` when it
|
||||
/// starts digging, `Sniffer.emitDiggingParticles` (block dust and the
|
||||
/// block's hit sound between the 1.7th and the 6th second of the
|
||||
/// digging animation) and `playSearchingSound`.
|
||||
pub(super) fn tick_sniffer_effects(&mut self) {
|
||||
let Some(camera) = self.player.as_ref().map(|p| p.position) else {
|
||||
return;
|
||||
@@ -52,14 +53,27 @@ impl Game<'_> {
|
||||
let m = &self.mobs[i];
|
||||
if m.species() != Species::Sniffer
|
||||
|| !m.alive()
|
||||
|| !sniffer::digging(m)
|
||||
|| m.silent
|
||||
|| m.position.distance_squared(camera) > 32.0 * 32.0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let at = [m.position.x, m.position.y, m.position.z];
|
||||
if sniffer::state(m) == sniffer::SEARCHING && m.age.is_multiple_of(20) {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.searching", Some(at), 1.0, 1.0);
|
||||
continue;
|
||||
}
|
||||
if !sniffer::digging(m) {
|
||||
continue;
|
||||
}
|
||||
let Some(ms) = m.anim.states[3].millis(m.age as f32) else {
|
||||
continue;
|
||||
};
|
||||
if ms == 0 {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.digging", Some(at), 1.0, 1.0);
|
||||
}
|
||||
if ms <= 1700 || ms >= 6000 {
|
||||
continue;
|
||||
}
|
||||
@@ -68,19 +82,19 @@ impl Game<'_> {
|
||||
let Some((sprite, tint)) = self.particle_sprite(below) else {
|
||||
continue;
|
||||
};
|
||||
let at = [
|
||||
let dust = [
|
||||
f64::from(head[0]) + 0.5,
|
||||
f64::from(head[1]) + 0.5 - f64::from(0.65_f32),
|
||||
f64::from(head[2]) + 0.5,
|
||||
];
|
||||
for _ in 0..30 {
|
||||
let particle =
|
||||
Particle::terrain(&mut self.world.random, at, [0.0; 3], sprite.clone(), tint);
|
||||
Particle::terrain(&mut self.world.random, dust, [0.0; 3], sprite.clone(), tint);
|
||||
self.particles.push(particle);
|
||||
}
|
||||
if self.mobs[i].age.is_multiple_of(10) {
|
||||
self.audio
|
||||
.play("minecraft:entity.sniffer.digging", Some(at), 0.5, 0.5);
|
||||
let hit = self.res.facts.get(below).sounds.hit.clone();
|
||||
self.audio.play(&hit, Some(at), 0.5, 0.5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
pub mod ai;
|
||||
pub mod allay;
|
||||
pub mod anim;
|
||||
pub mod animal_brain;
|
||||
pub mod aquatic;
|
||||
pub mod body_anim;
|
||||
pub mod brain;
|
||||
@@ -545,6 +546,8 @@ pub struct Extra {
|
||||
pub raider: Option<Box<raider::State>>,
|
||||
/// A villager's raid activity and gossip.
|
||||
pub villager: Option<Box<villager::Ext>>,
|
||||
/// The sniffer's and the ghastling's brain.
|
||||
pub animal_brain: Option<Box<animal_brain::Brain>>,
|
||||
/// The mob this one rides, and the mob riding it (`getVehicle`, `getFirstPassenger`).
|
||||
pub mount: Option<u32>,
|
||||
pub rider: Option<u32>,
|
||||
@@ -639,6 +642,18 @@ pub enum MobEvent {
|
||||
target: u32,
|
||||
item: &'static str,
|
||||
},
|
||||
/// `AnimalMakeLove`: the partner remembers this mob as its breed target
|
||||
/// and walks to it and looks at it.
|
||||
BreedTarget {
|
||||
mob: u32,
|
||||
partner: u32,
|
||||
},
|
||||
/// `BehaviorUtils.lockGazeAndWalkToEachOther`'s other half: the partner
|
||||
/// looks at this mob and walks to it.
|
||||
LockGaze {
|
||||
mob: u32,
|
||||
partner: u32,
|
||||
},
|
||||
/// A sound event id that is not a static string (variant sounds).
|
||||
SoundId(String, [f64; 3], f32, f32),
|
||||
/// `Level.playLocalSound`: a sound the client plays for itself, never
|
||||
@@ -740,6 +755,9 @@ pub enum MobEvent {
|
||||
Breed {
|
||||
parent: u32,
|
||||
partner: u32,
|
||||
/// A llama's baby, drawn from the parent's random as
|
||||
/// `Llama.getBreedOffspring` does.
|
||||
llama: Option<Box<super::mobs::llama::Offspring>>,
|
||||
},
|
||||
/// Replace a block by name (sheep turning grass to dirt), optionally with
|
||||
/// the destroy effect.
|
||||
@@ -914,9 +932,13 @@ pub struct Seen {
|
||||
/// A villager's `POTENTIAL_JOB_SITE` and `MEETING_POINT`.
|
||||
pub potential_job: Option<[i32; 3]>,
|
||||
pub meeting: Option<[i32; 3]>,
|
||||
/// A villager's profession (index into `render::PROFESSIONS`) and experience.
|
||||
/// `variant2`: a villager's profession (index into
|
||||
/// `render::PROFESSIONS`), a llama's strength. And a villager's experience.
|
||||
pub profession: u8,
|
||||
pub xp: i32,
|
||||
/// `MAX_HEALTH`, `JUMP_STRENGTH` and `MOVEMENT_SPEED` base values (a
|
||||
/// horse's breeding stock).
|
||||
pub stats: [f64; 3],
|
||||
}
|
||||
impl Mob {
|
||||
/// `EntityType.getCategory`'s name.
|
||||
@@ -962,6 +984,41 @@ pub fn apply_mob_pushes(m: &mut Mob, pending: &mut Vec<(u32, Vec3)>) {
|
||||
false
|
||||
});
|
||||
}
|
||||
/// Applies the brain memories a mob's tick set on other mobs (from event
|
||||
/// index `from` on), at once: vanilla sets them on the other entity during
|
||||
/// the tick, before the mobs after it tick.
|
||||
pub fn apply_brain_events(mobs: &mut [Mob], events: &mut Vec<MobEvent>, from: usize) {
|
||||
let mut i = from;
|
||||
while i < events.len() {
|
||||
match events[i] {
|
||||
MobEvent::BreedTarget { mob, partner } => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) {
|
||||
animal_brain::set_breed_partner(m, partner);
|
||||
}
|
||||
events.remove(i);
|
||||
}
|
||||
MobEvent::LockGaze { mob, partner } => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == mob) {
|
||||
animal_brain::lock_gaze(m, partner);
|
||||
}
|
||||
events.remove(i);
|
||||
}
|
||||
// Animal.finalizeSpawnChildFromBreeding: the partner rests and
|
||||
// forgets it at once (the game still makes the baby).
|
||||
MobEvent::Breed {
|
||||
parent, partner, ..
|
||||
} => {
|
||||
if let Some(m) = mobs.iter_mut().find(|m| m.id == partner) {
|
||||
m.extra.age = 6000;
|
||||
m.extra.in_love = 0;
|
||||
animal_brain::forget_breed_target(m, parent);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The player as mobs see it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PlayerView {
|
||||
|
||||
@@ -19,6 +19,9 @@ use horizon_core::{
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Ai {
|
||||
/// `Mob.homePosition` and `homeRadius`: where a restricted mob stays
|
||||
/// (a lead's holder, a happy ghast's float area).
|
||||
pub home: Option<([i32; 3], i32)>,
|
||||
pub goals: GoalSelector,
|
||||
pub targets: GoalSelector,
|
||||
pub nav: Navigation,
|
||||
@@ -563,6 +566,10 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
.is_some_and(|t| t.position.distance_squared(m.position) > 121.0);
|
||||
super::witch::ai_step(m, events, far);
|
||||
}
|
||||
// AbstractHorse.aiStep: the tail swishes now and then (moveTail).
|
||||
if super::equine::is_equine(m.species()) {
|
||||
let _ = m.random.next_int_bound(200);
|
||||
}
|
||||
// Monster.aiStep: updateNoActionTime (Raider: always +2).
|
||||
if is_monster(m.species())
|
||||
&& (super::raider::is_raider(m.species()) || super::hostile::mob_brightness(m, w) > 0.5)
|
||||
@@ -608,7 +615,12 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
// AgeableMob.aiStep
|
||||
if m.alive() {
|
||||
if m.extra.age < 0 {
|
||||
let (bw, bh, _) = m.dims();
|
||||
m.extra.age += 1;
|
||||
// setAge at the age boundary: refreshDimensions.
|
||||
if m.extra.age >= 0 {
|
||||
m.fudge_position_after_size_change(w, bw, bh);
|
||||
}
|
||||
} else if m.extra.age > 0 {
|
||||
m.extra.age -= 1;
|
||||
}
|
||||
@@ -619,13 +631,18 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
|
||||
if m.extra.in_love > 0 {
|
||||
m.extra.in_love -= 1;
|
||||
if m.extra.in_love % 10 == 0 {
|
||||
// The heart's speed and getRandomX/Y/Z, drawn even on the server.
|
||||
let (w, h) = (f64::from(m.width()), f64::from(m.height()));
|
||||
let r = &mut m.random;
|
||||
for _ in 0..3 {
|
||||
let _ = r.next_gaussian();
|
||||
}
|
||||
let x = m.position.x + w * (2.0 * r.next_double() - 1.0);
|
||||
let y = m.position.y + h * r.next_double() + 0.5;
|
||||
let z = m.position.z + w * (2.0 * r.next_double() - 1.0);
|
||||
events.push(MobEvent::Particles {
|
||||
kind: "heart",
|
||||
at: [
|
||||
m.position.x,
|
||||
m.position.y + f64::from(m.height()) + 0.5,
|
||||
m.position.z,
|
||||
],
|
||||
at: [x, y, z],
|
||||
count: 1,
|
||||
});
|
||||
}
|
||||
@@ -737,6 +754,10 @@ fn server_ai_step(
|
||||
events: &mut Vec<MobEvent>,
|
||||
) {
|
||||
m.ai.no_action_time += 1;
|
||||
// A happy ghast set up for its age (ageBoundaryReached runs at once).
|
||||
if m.species() == Species::HappyGhast {
|
||||
super::happy_ghast::ensure_setup(m);
|
||||
}
|
||||
// A saddled mount follows its rider instead of its goals.
|
||||
if super::equine::controlled(m) {
|
||||
super::equine::ridden_step(m);
|
||||
@@ -774,6 +795,11 @@ fn server_ai_step(
|
||||
super::villager_brain::tick(m, w, level_random, events);
|
||||
let _ = m.random.next_int_bound(100);
|
||||
}
|
||||
// Sniffer and HappyGhast.customServerAiStep: the brain (a happy ghast's
|
||||
// only while it is a ghastling), then updateActivity.
|
||||
if m.species() == Species::Sniffer || m.species() == Species::HappyGhast && m.is_baby() {
|
||||
super::animal_brain::tick(m, w, level_random, events);
|
||||
}
|
||||
{
|
||||
let mut cx = Cx { w, events };
|
||||
custom_server_ai_step(m, &mut cx);
|
||||
@@ -951,6 +977,17 @@ pub fn walk_target_value(m: &Mob, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
if family(m.species()) == Family::Guardian && w.fluid(p[0], p[1], p[2]) == Fluid::Water {
|
||||
return 10.0 + light();
|
||||
}
|
||||
// HappyGhast.getWalkTargetValue: open air, best just above the ground.
|
||||
if m.species() == Species::HappyGhast {
|
||||
let air = |y: i32| w.facts.is_air(w.world.block(p[0], y, p[2]));
|
||||
return if !air(p[1]) {
|
||||
0.0
|
||||
} else if air(p[1] - 1) && !air(p[1] - 2) {
|
||||
10.0
|
||||
} else {
|
||||
5.0
|
||||
};
|
||||
}
|
||||
// AbstractNautilus and Creaking.getWalkTargetValue: everywhere alike.
|
||||
if matches!(
|
||||
m.species(),
|
||||
|
||||
@@ -466,7 +466,8 @@ pub fn setup(
|
||||
Anim::CopperGolem => super::copper_golem::anim(m, s, p, w_anims),
|
||||
Anim::HappyGhast => super::happy_ghast::anim(m, s, p),
|
||||
Anim::Nautilus => super::nautilus::anim(m, s, p, w_anims),
|
||||
Anim::Llama => super::llama::anim(m, s, p),
|
||||
// body_anim::llama runs first.
|
||||
Anim::Llama => quadruped(p, s),
|
||||
Anim::Warden => super::warden::anim(m, s, p, w_anims),
|
||||
Anim::Allay => super::allay::anim(m, s, p),
|
||||
Anim::Creaking => super::creaking::anim(m, s, p, w_anims),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -55,20 +55,21 @@ fn first_is_leashed(cx: &Cx, caravan: u32, leashed: bool, counter: i32) -> bool
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FollowCaravan {
|
||||
speed: f64,
|
||||
base_speed: f64,
|
||||
dist_check: i32,
|
||||
}
|
||||
impl FollowCaravan {
|
||||
pub fn new(speed: f64) -> Self {
|
||||
Self {
|
||||
speed,
|
||||
base_speed: speed,
|
||||
dist_check: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Goal for FollowCaravan {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"LlamaFollowCaravanGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
super::goals::MOVE
|
||||
}
|
||||
@@ -158,7 +159,8 @@ impl Goal for FollowCaravan {
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
m.extra.ints[1] = 0;
|
||||
self.speed = self.base_speed;
|
||||
// A double 2.1 here, while the llama built it with 2.1F.
|
||||
self.speed = 2.1;
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let caravan = head_of(m);
|
||||
@@ -265,7 +267,7 @@ pub fn trader_llama_tick(m: &mut Mob, w: &MobWorld) {
|
||||
}
|
||||
m.extra.ints[0] = trader.unwrap_or(m.extra.ints[0]) - 1;
|
||||
if m.extra.ints[0] <= 0 {
|
||||
m.extra.leash = None;
|
||||
super::leash::remove(m);
|
||||
m.removed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,8 @@ pub enum LookKind {
|
||||
SmoothSwimming(f32),
|
||||
/// Look controls that never reset pitch (e.g. ghasts keep their own).
|
||||
Fixed,
|
||||
/// `HappyGhast.HappyGhastLookControl`.
|
||||
HappyGhast,
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LookControl {
|
||||
@@ -307,8 +309,12 @@ impl Mob {
|
||||
/// LookControl.tick (and SmoothSwimmingLookControl).
|
||||
pub fn look_control_tick(&mut self) {
|
||||
let look = self.ai.look.clone();
|
||||
if look.kind == LookKind::HappyGhast {
|
||||
return super::happy_ghast::look_control(self);
|
||||
}
|
||||
let (x_d, y_d) = self.look_angles(look.wanted);
|
||||
match look.kind {
|
||||
LookKind::HappyGhast => {}
|
||||
LookKind::SmoothSwimming(max) => {
|
||||
if look.cooldown > 0 {
|
||||
self.ai.look.cooldown -= 1;
|
||||
|
||||
@@ -174,6 +174,13 @@ impl GoalSelector {
|
||||
|
||||
// --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) -------
|
||||
|
||||
/// `Mob.isWithinHome(BlockPos)`.
|
||||
pub fn within_home(c: [i32; 3], r: i32, p: [i32; 3]) -> bool {
|
||||
let d = |i: usize| i64::from(c[i] - p[i]);
|
||||
let r = i64::from(r);
|
||||
d(0) * d(0) + d(1) * d(1) + d(2) * d(2) < r * r
|
||||
}
|
||||
|
||||
impl Mob {
|
||||
/// PathfinderMob.getWalkTargetValue.
|
||||
pub fn walk_target_value(&self, w: &MobWorld, p: [i32; 3]) -> f32 {
|
||||
@@ -209,17 +216,52 @@ impl Mob {
|
||||
let yt = self.random.next_int_bound(2 * v + 1).unwrap_or(0) - v + fly_height;
|
||||
Some([xt.floor() as i32, yt, zt.floor() as i32])
|
||||
}
|
||||
/// RandomPos.generateRandomPosTowardDirection (no home restriction).
|
||||
fn toward(&mut self, _h: f64, d: [i32; 3]) -> [i32; 3] {
|
||||
/// RandomPos.generateRandomPosTowardDirection: a mob with a home leans
|
||||
/// half the distance back toward it.
|
||||
fn toward(&mut self, h: f64, d: [i32; 3]) -> [i32; 3] {
|
||||
let (mut xt, mut zt) = (f64::from(d[0]), f64::from(d[2]));
|
||||
if let Some((c, _)) = self.ai.home
|
||||
&& h > 1.0
|
||||
{
|
||||
if self.position.x > f64::from(c[0]) {
|
||||
xt -= self.random.next_double() * h / 2.0;
|
||||
} else {
|
||||
xt += self.random.next_double() * h / 2.0;
|
||||
}
|
||||
if self.position.z > f64::from(c[2]) {
|
||||
zt -= self.random.next_double() * h / 2.0;
|
||||
} else {
|
||||
zt += self.random.next_double() * h / 2.0;
|
||||
}
|
||||
}
|
||||
[
|
||||
(f64::from(d[0]) + self.position.x).floor() as i32,
|
||||
(xt + self.position.x).floor() as i32,
|
||||
(f64::from(d[1]) + self.position.y).floor() as i32,
|
||||
(f64::from(d[2]) + self.position.z).floor() as i32,
|
||||
(zt + self.position.z).floor() as i32,
|
||||
]
|
||||
}
|
||||
fn default_check(&self, w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
/// `GoalUtils.isRestricted(mobRestricted(mob, h), mob, pos)`: a mob
|
||||
/// near its home keeps the positions it picks within it.
|
||||
pub fn restricted(&self, h: f64, p: [i32; 3]) -> bool {
|
||||
let Some((c, r)) = self.ai.home else {
|
||||
return false;
|
||||
};
|
||||
let near = {
|
||||
let d = |i: usize, v: f64| f64::from(c[i]) + 0.5 - v;
|
||||
let (x, y, z) = (
|
||||
d(0, self.position.x),
|
||||
d(1, self.position.y),
|
||||
d(2, self.position.z),
|
||||
);
|
||||
let reach = f64::from(r) + h + 1.0;
|
||||
x * x + y * y + z * z < reach * reach
|
||||
};
|
||||
near && !within_home(c, r, p)
|
||||
}
|
||||
fn default_check(&self, w: &MobWorld, h: f64, p: [i32; 3]) -> bool {
|
||||
p[1] >= crate::chunk::MIN_Y
|
||||
&& p[1] < 320
|
||||
&& !self.restricted(h, p)
|
||||
&& self.stable_destination(w, p)
|
||||
&& self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0
|
||||
}
|
||||
@@ -252,7 +294,7 @@ impl Mob {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction(h, v);
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
/// DefaultRandomPos.getPosAway
|
||||
@@ -275,7 +317,7 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
/// DefaultRandomPos.getPosTowards
|
||||
@@ -291,7 +333,7 @@ impl Mob {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction_within(0.0, f64::from(h), v, 0, xd, zd, max_rad)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
m.default_check(w, p).then_some(p)
|
||||
m.default_check(w, f64::from(h), p).then_some(p)
|
||||
})
|
||||
}
|
||||
fn land_up_out_of_solid(&self, w: &MobWorld, mut p: [i32; 3]) -> Option<[i32; 3]> {
|
||||
@@ -304,12 +346,64 @@ impl Mob {
|
||||
let water = w.fluid(p[0], p[1], p[2]) == crate::blocks::Fluid::Water;
|
||||
(!water && self.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
|
||||
}
|
||||
/// `Entity.getViewVector(0)`: `calculateViewVector(xRotO, yRotO)`.
|
||||
pub fn view_vector(&self) -> [f64; 3] {
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
let to_rad = std::f32::consts::PI / 180.0;
|
||||
let x = self.previous_head_pitch * to_rad;
|
||||
let y = -self.previous_yaw * to_rad;
|
||||
let (y_cos, y_sin, x_cos, x_sin) = (y.mcos(), y.msin(), x.mcos(), x.msin());
|
||||
[
|
||||
f64::from(y_sin * x_cos),
|
||||
f64::from(-x_sin),
|
||||
f64::from(y_cos * x_cos),
|
||||
]
|
||||
}
|
||||
/// AirAndWaterRandomPos.getPos: within the radians of a direction, kept
|
||||
/// near home, moved up out of solid blocks and free of path maluses.
|
||||
pub fn air_and_water_random_pos(
|
||||
&mut self,
|
||||
w: &MobWorld,
|
||||
h: i32,
|
||||
v: i32,
|
||||
fly_height: i32,
|
||||
xd: f64,
|
||||
zd: f64,
|
||||
) -> Option<[f64; 3]> {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction_within(
|
||||
0.0,
|
||||
f64::from(h),
|
||||
v,
|
||||
fly_height,
|
||||
xd,
|
||||
zd,
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let mut p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || m.restricted(f64::from(h), p) {
|
||||
return None;
|
||||
}
|
||||
// RandomPos.moveUpOutOfSolid
|
||||
if w.solid(p[0], p[1], p[2]) {
|
||||
p[1] += 1;
|
||||
while p[1] <= 319 && w.solid(p[0], p[1], p[2]) {
|
||||
p[1] += 1;
|
||||
}
|
||||
}
|
||||
(m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0).then_some(p)
|
||||
})
|
||||
}
|
||||
/// LandRandomPos.getPos
|
||||
pub fn land_random_pos(&mut self, w: &MobWorld, h: i32, v: i32) -> Option<[f64; 3]> {
|
||||
self.pick_best(w, |m| {
|
||||
let d = m.random_direction(h, v);
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -371,7 +465,11 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -397,7 +495,11 @@ impl Mob {
|
||||
std::f64::consts::FRAC_PI_2,
|
||||
)?;
|
||||
let p = m.toward(f64::from(h), d);
|
||||
if p[1] < crate::chunk::MIN_Y || p[1] >= 320 || !m.stable_destination(w, p) {
|
||||
if p[1] < crate::chunk::MIN_Y
|
||||
|| p[1] >= 320
|
||||
|| m.restricted(f64::from(h), p)
|
||||
|| !m.stable_destination(w, p)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
m.land_up_out_of_solid(w, p)
|
||||
@@ -1338,6 +1440,8 @@ pub struct AvoidEntity {
|
||||
/// Extra condition on the avoider (e.g. untamed cats only).
|
||||
pub when: Option<fn(&Mob) -> bool>,
|
||||
from: Vec3,
|
||||
/// The mob being avoided (`toAvoid`), when it is one.
|
||||
pub found: Option<u32>,
|
||||
}
|
||||
impl AvoidEntity {
|
||||
pub fn new(what: Avoid, max_dist: f32, walk: f64, sprint: f64) -> Self {
|
||||
@@ -1348,6 +1452,7 @@ impl AvoidEntity {
|
||||
sprint,
|
||||
when: None,
|
||||
from: Vec3::ZERO,
|
||||
found: None,
|
||||
}
|
||||
}
|
||||
pub fn when(mut self, f: fn(&Mob) -> bool) -> Self {
|
||||
@@ -1382,11 +1487,16 @@ impl Goal for AvoidEntity {
|
||||
Avoid::Species(list) => {
|
||||
let id = m.id;
|
||||
let y = m.position.y;
|
||||
cx.w.nearby(m.position, max, move |s| {
|
||||
s.id != id && list.contains(&s.species) && (s.position.y - y).abs() <= 3.0 + max
|
||||
})
|
||||
.map(|s| s.position)
|
||||
.next()
|
||||
let hit =
|
||||
cx.w.nearby(m.position, max, move |s| {
|
||||
s.id != id
|
||||
&& list.contains(&s.species)
|
||||
&& (s.position.y - y).abs() <= 3.0 + max
|
||||
})
|
||||
.map(|s| (s.id, s.position))
|
||||
.next();
|
||||
self.found = hit.map(|h| h.0);
|
||||
hit.map(|h| h.1)
|
||||
}
|
||||
};
|
||||
let Some(from) = found else { return false };
|
||||
@@ -1623,11 +1733,23 @@ impl Goal for Breed {
|
||||
);
|
||||
self.love_time += 1;
|
||||
if self.love_time >= reduced(60) && m.distance_sqr(p.position) < 9.0 {
|
||||
// Llama.getBreedOffspring and finalizeSpawnChildFromBreeding's
|
||||
// experience, from the parent's random.
|
||||
let llama = super::llama::is_llama(m.species()).then(|| {
|
||||
let o = super::llama::breed_offspring(m, &p);
|
||||
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0);
|
||||
cx.events.push(MobEvent::Experience {
|
||||
at: [m.position.x, m.position.y, m.position.z],
|
||||
amount: xp as u32,
|
||||
});
|
||||
Box::new(o)
|
||||
});
|
||||
m.extra.in_love = 0;
|
||||
m.extra.age = 6000;
|
||||
cx.events.push(MobEvent::Breed {
|
||||
parent: m.id,
|
||||
partner: p.id,
|
||||
llama,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
//! ghastling follows players and adults, a harnessed adult can be ridden and
|
||||
//! flown, healing is slow (fast in the rain) and `HappyGhastModel`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Species,
|
||||
Mob, MobEvent, MobWorld,
|
||||
anim::{Poses, State},
|
||||
control::{MoveKind, Operation},
|
||||
goals::{Cx, Float, Goal, LOOK, MOVE, Panic, Stroll, Tempt, goal_clone},
|
||||
control::{LookKind, MoveKind, Operation},
|
||||
goals::{Cx, Float, Goal, LOOK, MOVE, goal_clone},
|
||||
nav::NavKind,
|
||||
};
|
||||
use horizon_core::{
|
||||
@@ -15,7 +15,7 @@ use horizon_core::{
|
||||
};
|
||||
|
||||
// Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a
|
||||
// baby and 2 as an adult, `home` and `ints[4]` the restriction, `counter`
|
||||
// baby and 2 as an adult, `ai.home` the restriction, `counter`
|
||||
// the end tick of the follow-an-adult range pick.
|
||||
pub const BABY_SCALE: f64 = 0.2375;
|
||||
/// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`).
|
||||
@@ -25,35 +25,41 @@ pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0;
|
||||
pub fn register(m: &mut Mob) {
|
||||
setup(m, m.is_baby());
|
||||
}
|
||||
/// `adultGhastSetup` and `babyGhastSetup`.
|
||||
/// `adultGhastSetup` and `babyGhastSetup`: the ghastling flies with a
|
||||
/// `FlyingMoveControl` and has no goals (its brain drives it); the adult
|
||||
/// floats with `GhastMoveControl` and three goals, its brain stopped.
|
||||
fn setup(m: &mut Mob, baby: bool) {
|
||||
let was = m.extra.scratch[0];
|
||||
m.extra.scratch[0] = if baby { 1 } else { 2 };
|
||||
m.ai.goals.clear();
|
||||
m.ai.nav.stop();
|
||||
// A new move and look control (nothing wanted) and navigation.
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
m.ai.mov.wanted = [0.0; 3];
|
||||
m.ai.mov.speed_modifier = 0.0;
|
||||
m.ai.look.wanted = [0.0; 3];
|
||||
m.ai.look.cooldown = 0;
|
||||
m.extra.counter2 = 0;
|
||||
if baby {
|
||||
m.ai.look.kind = LookKind::Default;
|
||||
m.ai.mov.kind = MoveKind::Flying {
|
||||
max_turn: 180.0,
|
||||
hovers: true,
|
||||
};
|
||||
// BabyFlyingPathNavigation.
|
||||
m.ai.nav.kind = NavKind::Flying;
|
||||
m.ai.nav.can_float = true;
|
||||
m.ai.nav.required_path_length = 48.0;
|
||||
let tempt = m.kind.food.clone();
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(0, Panic::new(2.0));
|
||||
let mut t = Tempt::new(1.25, tempt, false);
|
||||
t.stop_distance = 3.0;
|
||||
g.add(1, t);
|
||||
g.add(2, FollowAdult::default());
|
||||
g.add(4, Stroll::flying(1.0));
|
||||
return;
|
||||
}
|
||||
if was == 1 {
|
||||
super::animal_brain::grown_up(m);
|
||||
}
|
||||
m.ai.mov.kind = MoveKind::Custom;
|
||||
m.ai.nav.kind = NavKind::Ground;
|
||||
m.ai.look.kind = LookKind::HappyGhast;
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(3, Float);
|
||||
g.add(3, HappyGhastFloat);
|
||||
g.add(4, GhastTempt::default());
|
||||
g.add(5, FloatAround { blocks: 16 });
|
||||
}
|
||||
@@ -74,8 +80,10 @@ fn restriction_radius(m: &Mob) -> i32 {
|
||||
}
|
||||
/// `Mob.isWithinHome` for the ghast's restriction.
|
||||
fn within_home(m: &Mob, p: Vec3) -> bool {
|
||||
let Some(h) = m.extra.home else { return true };
|
||||
let r = f64::from(m.extra.ints[4]);
|
||||
let Some((h, r)) = m.ai.home else {
|
||||
return true;
|
||||
};
|
||||
let r = f64::from(r);
|
||||
let (dx, dy, dz) = (
|
||||
f64::from(h[0]) + 0.5 - p.x,
|
||||
f64::from(h[1]) + 0.5 - p.y,
|
||||
@@ -83,58 +91,233 @@ fn within_home(m: &Mob, p: Vec3) -> bool {
|
||||
);
|
||||
dx * dx + dy * dy + dz * dz < r * r
|
||||
}
|
||||
/// `Ghast.GhastMoveControl` with the careful block checks: a push toward
|
||||
/// the wanted point every few ticks while the way is clear.
|
||||
/// `isOnStillTimeout`: a player standing on it (or just off it) holds it
|
||||
/// still (`serverStillTimeout`, kept in `counter`).
|
||||
pub fn on_still_timeout(m: &Mob) -> bool {
|
||||
!m.is_baby() && m.extra.counter > 0
|
||||
}
|
||||
/// `Mob.stopInPlace`.
|
||||
fn stop_in_place(m: &mut Mob) {
|
||||
m.ai.nav.stop();
|
||||
m.ai.xxa = 0.0;
|
||||
m.ai.yya = 0.0;
|
||||
m.ai.zza = 0.0;
|
||||
m.ai.speed = 0.0;
|
||||
m.velocity = Vec3::ZERO;
|
||||
}
|
||||
/// `Ghast.GhastMoveControl(careful)`: held still on a still timeout, else
|
||||
/// a push toward the wanted point every 2 to 6 ticks while the way there
|
||||
/// is clear.
|
||||
pub fn move_control(m: &mut Mob, w: &MobWorld) {
|
||||
if on_still_timeout(m) {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
stop_in_place(m);
|
||||
}
|
||||
if m.ai.mov.operation != Operation::MoveTo {
|
||||
return;
|
||||
}
|
||||
// floatDuration-- <= 0
|
||||
let duration = m.extra.counter2;
|
||||
m.extra.counter2 -= 1;
|
||||
if m.extra.counter2 > 0 {
|
||||
if duration > 0 {
|
||||
return;
|
||||
}
|
||||
m.extra.counter2 += m.random.next_int_bound(5).unwrap_or(0) + 2;
|
||||
let [wx, wy, wz] = m.ai.mov.wanted;
|
||||
let travel = Vec3::new(wx - m.position.x, wy - m.position.y, wz - m.position.z);
|
||||
let len = travel.length();
|
||||
if len < 1.0e-6 {
|
||||
return;
|
||||
}
|
||||
let b = m.bounds();
|
||||
let steps = len.ceil() as i32;
|
||||
let clear = (1..=steps).all(|i| {
|
||||
let f = f64::from(i) / f64::from(steps);
|
||||
let d = Vec3::new(travel.x * f, travel.y * f, travel.z * f);
|
||||
let at = Aabb::new(
|
||||
b.min_position().add_vector(d),
|
||||
b.max_position().add_vector(d),
|
||||
);
|
||||
w.no_collision(at) && !touches_fluid(w, at)
|
||||
});
|
||||
if clear {
|
||||
let speed = AIR_SPEED;
|
||||
m.velocity = m.velocity.add_vector(Vec3::new(
|
||||
travel.x / len * f64::from(speed),
|
||||
travel.y / len * f64::from(speed),
|
||||
travel.z / len * f64::from(speed),
|
||||
));
|
||||
if can_reach(m, w, travel) {
|
||||
// travel.normalize().scale(FLYING_SPEED * 5 / 3)
|
||||
let len = (travel.x * travel.x + travel.y * travel.y + travel.z * travel.z).sqrt();
|
||||
let unit = if len < f64::from(1.0e-5_f32) {
|
||||
Vec3::ZERO
|
||||
} else {
|
||||
Vec3::new(travel.x / len, travel.y / len, travel.z / len)
|
||||
};
|
||||
let speed = FLYING_SPEED * 5.0 / 3.0;
|
||||
m.velocity =
|
||||
m.velocity
|
||||
.add_vector(Vec3::new(unit.x * speed, unit.y * speed, unit.z * speed));
|
||||
} else {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
}
|
||||
/// A careful ghast does not float into water or lava.
|
||||
fn touches_fluid(w: &MobWorld, b: Aabb) -> bool {
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
/// `EntityDimensions.makeBoundingBox` at another position.
|
||||
fn bounds_at(m: &Mob, p: Vec3) -> Aabb {
|
||||
let half = f64::from(m.width()) / 2.0;
|
||||
let h = f64::from(m.height());
|
||||
Aabb::new(
|
||||
Vec3::new(p.x - half, p.y, p.z - half),
|
||||
Vec3::new(p.x + half, p.y + h, p.z + half),
|
||||
)
|
||||
}
|
||||
/// `GhastMoveControl.canReach`: every block around the destination box can
|
||||
/// be crossed, and so can every block the box sweeps through on the way.
|
||||
fn can_reach(m: &Mob, w: &MobWorld, travel: Vec3) -> bool {
|
||||
let aabb = m.bounds();
|
||||
let dest = aabb.move_by(travel);
|
||||
let around = dest.inflate(Vec3::new(1.0, 1.0, 1.0));
|
||||
let (lo, hi) = (around.min_position(), around.max_position());
|
||||
for x in lo.x.floor() as i32..=hi.x.floor() as i32 {
|
||||
for y in lo.y.floor() as i32..=hi.y.floor() as i32 {
|
||||
for z in lo.z.floor() as i32..=hi.z.floor() as i32 {
|
||||
if w.fluid(x, y, z) != crate::blocks::Fluid::None {
|
||||
return true;
|
||||
if !traversal_possible(m, w, None, [x, y, z], false, false) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
let (water, lava) = (m.fluids.in_water, m.fluids.in_lava);
|
||||
let start = m.position;
|
||||
let end = start.add_vector(travel);
|
||||
horizon_core::geometry::sweep_intersected_blocks(start, end, dest, 1 << 22, |p, _| {
|
||||
let at = [p.x, p.y, p.z];
|
||||
let unit = Aabb::new(
|
||||
Vec3::new(f64::from(at[0]), f64::from(at[1]), f64::from(at[2])),
|
||||
Vec3::new(
|
||||
f64::from(at[0]) + 1.0,
|
||||
f64::from(at[1]) + 1.0,
|
||||
f64::from(at[2]) + 1.0,
|
||||
),
|
||||
);
|
||||
aabb.intersects(unit) || traversal_possible(m, w, Some((start, end)), at, water, lava)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
/// `GhastMoveControl.blockTraversalPossible` for a careful ghast: air, or no
|
||||
/// collision (along the way when `along` is given), never a
|
||||
/// `#happy_ghast_avoids` block, and a fluid only where the ghast already is.
|
||||
fn traversal_possible(
|
||||
m: &Mob,
|
||||
w: &MobWorld,
|
||||
along: Option<(Vec3, Vec3)>,
|
||||
p: [i32; 3],
|
||||
through_water: bool,
|
||||
through_lava: bool,
|
||||
) -> bool {
|
||||
let state = w.world.block(p[0], p[1], p[2]);
|
||||
if w.facts.is_air(state) {
|
||||
return true;
|
||||
}
|
||||
let boxes = w.block_collision_boxes(p[0], p[1], p[2]);
|
||||
let no_collisions = match along {
|
||||
Some((from, to)) => !bounds_at(m, from).collided_along_vector(to.subtract(from), &boxes),
|
||||
None => boxes.is_empty(),
|
||||
};
|
||||
if w.has_tag(
|
||||
"minecraft:happy_ghast_avoids",
|
||||
w.block_name(p[0], p[1], p[2]),
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
let (fluid, height) = w.fluid_height(p[0], p[1], p[2]);
|
||||
if fluid != crate::blocks::Fluid::None {
|
||||
let collided = match along {
|
||||
None => true,
|
||||
// collidedWithFluid: the fluid's own height.
|
||||
Some((from, to)) => {
|
||||
let fluid_box = Aabb::new(
|
||||
Vec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2])),
|
||||
Vec3::new(
|
||||
f64::from(p[0]) + 1.0,
|
||||
f64::from(p[1]) + height,
|
||||
f64::from(p[2]) + 1.0,
|
||||
),
|
||||
);
|
||||
bounds_at(m, from).collided_along_vector(to.subtract(from), &[fluid_box])
|
||||
}
|
||||
};
|
||||
if collided {
|
||||
return match fluid {
|
||||
crate::blocks::Fluid::Water => through_water,
|
||||
_ => through_lava,
|
||||
};
|
||||
}
|
||||
}
|
||||
no_collisions
|
||||
}
|
||||
/// `HappyGhast.HappyGhastLookControl`: square to the world on a still
|
||||
/// timeout, face what it looks at, else face its motion
|
||||
/// (`Ghast.faceMovementDirection`).
|
||||
pub fn look_control(m: &mut Mob) {
|
||||
use horizon_core::geometry::trig;
|
||||
let to_deg = 180.0_f32 / std::f32::consts::PI;
|
||||
if on_still_timeout(m) {
|
||||
// Mth.wrapDegrees90
|
||||
let mut close = m.yaw % 90.0;
|
||||
if close >= 45.0 {
|
||||
close -= 90.0;
|
||||
}
|
||||
if close < -45.0 {
|
||||
close += 90.0;
|
||||
}
|
||||
m.yaw -= close;
|
||||
m.head_yaw = m.yaw;
|
||||
} else if m.ai.look.cooldown > 0 {
|
||||
m.ai.look.cooldown -= 1;
|
||||
let [wx, _, wz] = m.ai.look.wanted;
|
||||
m.yaw = -(trig::atan2(wx - m.position.x, wz - m.position.z) as f32) * to_deg;
|
||||
m.body_yaw = m.yaw;
|
||||
m.head_yaw = m.body_yaw;
|
||||
} else if m.ai.target.is_none() {
|
||||
let v = m.velocity;
|
||||
m.yaw = -(trig::atan2(v.x, v.z) as f32) * to_deg;
|
||||
m.body_yaw = m.yaw;
|
||||
}
|
||||
}
|
||||
/// `HappyGhast.tick`'s still timeout: it runs out (after the first three
|
||||
/// seconds) unless a player stands on top (`scanPlayerAboveGhast`).
|
||||
pub fn still_tick(m: &mut Mob, w: &MobWorld) {
|
||||
if m.is_baby() {
|
||||
m.extra.counter = 0;
|
||||
return;
|
||||
}
|
||||
if m.extra.counter > 0 && m.age > 60 {
|
||||
m.extra.counter -= 1;
|
||||
}
|
||||
if player_above(m, w) {
|
||||
m.extra.counter = 10;
|
||||
}
|
||||
}
|
||||
/// `scanPlayerAboveGhast`: a player (not one riding a happy ghast) within
|
||||
/// a block around the top, up to half the ghast's height above it.
|
||||
pub fn player_above(m: &Mob, w: &MobWorld) -> bool {
|
||||
let Some(p) = w.player.as_ref().filter(|p| !p.spectator) else {
|
||||
return false;
|
||||
};
|
||||
if m.rider.is_some() {
|
||||
return false;
|
||||
}
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let area = Aabb::new(
|
||||
Vec3::new(lo.x - 1.0, hi.y - f64::from(1.0e-5_f32), lo.z - 1.0),
|
||||
Vec3::new(hi.x + 1.0, hi.y + (hi.y - lo.y) / 2.0, hi.z + 1.0),
|
||||
);
|
||||
area.contains(p.position)
|
||||
}
|
||||
/// `HappyGhastFloatGoal`: a `FloatGoal` off a still timeout.
|
||||
#[derive(Clone, Debug)]
|
||||
struct HappyGhastFloat;
|
||||
impl Goal for HappyGhastFloat {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"HappyGhastFloatGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
Float.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
!on_still_timeout(m) && Float.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
Float.can_use(m, cx)
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
Float.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// `TemptGoal.ForNonPathfinders`: drift toward a player holding food, or
|
||||
/// food and harnesses for a bare adult.
|
||||
@@ -151,6 +334,9 @@ impl GhastTempt {
|
||||
}
|
||||
impl Goal for GhastTempt {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"ForNonPathfinders"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE | LOOK
|
||||
}
|
||||
@@ -160,22 +346,24 @@ impl Goal for GhastTempt {
|
||||
return false;
|
||||
}
|
||||
let Some(p) = &cx.w.player else { return false };
|
||||
// Attributes.TEMPT_RANGE 16.
|
||||
// getNearestPlayer(TargetingConditions.forNonCombat()
|
||||
// .ignoreLineOfSight().range(TEMPT_RANGE 16)): creative players too.
|
||||
let visibility = if p.sneaking { 0.8 } else { 1.0 };
|
||||
let range = (16.0_f64 * visibility).max(2.0);
|
||||
p.alive
|
||||
&& !p.creative
|
||||
&& !p.spectator
|
||||
&& (Self::wants(m, &p.main_hand) || Self::wants(m, &p.off_hand))
|
||||
&& m.distance_sqr(p.position) <= 256.0
|
||||
&& m.distance_sqr(p.position) <= range * range
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
// stopNavigation: setWait; calmDown = reducedTickDelay(100).
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
self.calm_down = 50;
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
self.calm_down = super::goals::reduced(100);
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let Some(p) = cx.w.player.clone() else { return };
|
||||
m.look_at(p.eye);
|
||||
// stopDistance 7.
|
||||
if m.distance_sqr(p.position) < 49.0 {
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
} else {
|
||||
@@ -227,6 +415,9 @@ impl FloatAround {
|
||||
}
|
||||
impl Goal for FloatAround {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"RandomFloatAroundGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
@@ -242,85 +433,39 @@ impl Goal for FloatAround {
|
||||
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
false
|
||||
}
|
||||
/// `getSuitableFlyToPosition`: the first of 64 random points within 16
|
||||
/// blocks (and home) that is good; failing that, the last point, kept
|
||||
/// below the motion-blocking surface.
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let c = m.position;
|
||||
let mut result: Option<Vec3> = None;
|
||||
for _ in 0..64 {
|
||||
let r = &mut m.random;
|
||||
let t = Vec3::new(
|
||||
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
);
|
||||
result = Some(t);
|
||||
if within_home(m, t) && self.good(cx.w, t) {
|
||||
break;
|
||||
}
|
||||
result = None;
|
||||
}
|
||||
let mut t = result.unwrap_or_else(|| {
|
||||
let choose = |m: &mut Mob| {
|
||||
let r = &mut m.random;
|
||||
Vec3::new(
|
||||
c.x + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.y + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.z + f64::from(r.next_float() * 2.0 - 1.0) * 16.0,
|
||||
c.x + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
c.y + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
c.z + f64::from((r.next_float() * 2.0 - 1.0) * 16.0),
|
||||
)
|
||||
});
|
||||
};
|
||||
let mut result: Option<Vec3> = None;
|
||||
for _ in 0..64 {
|
||||
let t = choose(m);
|
||||
result = within_home(m, t).then_some(t);
|
||||
if let Some(t) = result
|
||||
&& self.good(cx.w, t)
|
||||
{
|
||||
m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let mut t = result.unwrap_or_else(|| choose(m));
|
||||
let top =
|
||||
cx.w.motion_blocking_height(t.x.floor() as i32, t.z.floor() as i32);
|
||||
if top < t.y.floor() as i32 && top > crate::chunk::MIN_Y {
|
||||
t.y = c.y - (c.y - t.y).abs();
|
||||
t.y = m.position.y - (m.position.y - t.y).abs();
|
||||
}
|
||||
m.ai.mov.set_wanted(t.x, t.y, t.z, 1.0);
|
||||
}
|
||||
}
|
||||
/// `BabyFollowAdult`: a ghastling drifts toward the nearest player or adult
|
||||
/// until it is a few blocks away.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct FollowAdult {
|
||||
close: f64,
|
||||
}
|
||||
impl FollowAdult {
|
||||
fn target(m: &Mob, cx: &Cx) -> Option<Vec3> {
|
||||
let player =
|
||||
cx.w.player
|
||||
.as_ref()
|
||||
.filter(|p| p.alive && !p.spectator && m.distance_sqr(p.position) <= 32.0 * 32.0)
|
||||
.map(|p| p.position);
|
||||
player.or_else(|| {
|
||||
cx.w.nearby(m.position, 32.0, |s| {
|
||||
s.species == Species::HappyGhast && !s.baby
|
||||
})
|
||||
.next()
|
||||
.map(|s| s.position)
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Goal for FollowAdult {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
m.is_baby()
|
||||
&& Self::target(m, cx).is_some_and(|t| {
|
||||
let close = if self.close > 0.0 { self.close } else { 16.0 };
|
||||
m.position.distance_squared(t) > close * close
|
||||
})
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
Self::target(m, cx).is_some_and(|t| m.position.distance_squared(t) > 9.0)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
|
||||
// UniformInt.of(3, 16).
|
||||
self.close = f64::from(3 + m.random.next_int_bound(14).unwrap_or(0));
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
if let Some(t) = Self::target(m, cx) {
|
||||
m.nav_move_to(cx.w, [t.x, t.y, t.z], 1.1);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// What a rider asks (`getRiddenInput`, `tickRidden`).
|
||||
pub fn ridden(m: &mut Mob) {
|
||||
let Some(r) = m.rider else { return };
|
||||
@@ -351,13 +496,17 @@ pub fn ridden(m: &mut Mob) {
|
||||
m.ai.zza = forward * scale;
|
||||
m.ai.mov.operation = Operation::Wait;
|
||||
}
|
||||
/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby
|
||||
/// setup at the age boundary, the home, face-the-motion and slow healing.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
/// The adult or ghastling setup for its age (`ageBoundaryReached`).
|
||||
pub fn ensure_setup(m: &mut Mob) {
|
||||
let baby = m.is_baby();
|
||||
if m.extra.scratch[0] != if baby { 1 } else { 2 } {
|
||||
setup(m, baby);
|
||||
}
|
||||
}
|
||||
/// `HappyGhast.aiStep`, `tick` and `checkRestriction`: the adult/baby
|
||||
/// setup at the age boundary, the home, face-the-motion and slow healing.
|
||||
pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
ensure_setup(m);
|
||||
// checkRestriction.
|
||||
if m.extra.leash.is_none() && m.rider.is_none() {
|
||||
let radius = restriction_radius(m);
|
||||
@@ -366,26 +515,17 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
m.position.y.floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
];
|
||||
let stale = match m.extra.home {
|
||||
Some(h) => {
|
||||
// !hasHome || !home.closerThan(blockPosition, radius + 16) || radius changed
|
||||
let stale = match m.ai.home {
|
||||
Some((h, r)) => {
|
||||
(h[0] - here[0]).pow(2) + (h[1] - here[1]).pow(2) + (h[2] - here[2]).pow(2)
|
||||
>= (radius + 16).pow(2)
|
||||
|| radius != m.extra.ints[4]
|
||||
|| radius != r
|
||||
}
|
||||
None => true,
|
||||
};
|
||||
if stale {
|
||||
m.extra.home = Some(here);
|
||||
m.extra.ints[4] = radius;
|
||||
}
|
||||
}
|
||||
// LookControl: face where it is going.
|
||||
if !baby && m.rider.is_none() {
|
||||
let v = m.velocity;
|
||||
if m.ai.target.is_none() && v.x * v.x + v.z * v.z > 1.0e-6 {
|
||||
m.yaw = -(v.x.atan2(v.z) as f32).to_degrees();
|
||||
m.body_yaw = m.yaw;
|
||||
m.head_yaw = m.yaw;
|
||||
m.ai.home = Some((here, radius));
|
||||
}
|
||||
}
|
||||
// continuousHeal: a point every 30 seconds, every second in rain.
|
||||
@@ -401,6 +541,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) {
|
||||
m.health = (m.health + 1.0).min(m.attrs.max_health);
|
||||
}
|
||||
}
|
||||
still_tick(m, w);
|
||||
}
|
||||
/// Sounds: the ghastling has its own.
|
||||
pub fn sounds(m: &Mob) -> [&'static str; 3] {
|
||||
|
||||
@@ -209,6 +209,21 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
}
|
||||
return;
|
||||
};
|
||||
// PathfinderMob.whenLeashedTo: home is the holder's block, within the
|
||||
// elastic distance less one.
|
||||
let elastic = if m.species() == super::Species::HappyGhast {
|
||||
10.0
|
||||
} else {
|
||||
ELASTIC
|
||||
};
|
||||
m.ai.home = Some((
|
||||
[
|
||||
state.position.x.floor() as i32,
|
||||
state.position.y.floor() as i32,
|
||||
state.position.z.floor() as i32,
|
||||
],
|
||||
elastic as i32 - 1,
|
||||
));
|
||||
let b = m.bounds();
|
||||
let (lo, hi) = (b.min_position(), b.max_position());
|
||||
let center = Vec3::new(
|
||||
@@ -265,6 +280,14 @@ pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
};
|
||||
m.extra.leash_spin *= friction;
|
||||
}
|
||||
/// The lead comes off (`Mob.onLeashRemoved`): no more home.
|
||||
pub fn remove(m: &mut Mob) -> Option<Holder> {
|
||||
let was = m.extra.leash.take();
|
||||
if was.is_some() {
|
||||
m.ai.home = None;
|
||||
}
|
||||
was
|
||||
}
|
||||
/// `PathfinderMob.closeRangeLeashBehaviour`: walk to within two blocks of
|
||||
/// the holder unless panicking.
|
||||
fn close_range(m: &mut Mob, w: &MobWorld, holder: &HolderState) {
|
||||
|
||||
@@ -116,6 +116,22 @@ impl MobWorld<'_> {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `BlockState.getCollisionShape(level, pos)` (the empty collision
|
||||
/// context) as boxes in the world.
|
||||
pub fn block_collision_boxes(&self, x: i32, y: i32, z: i32) -> Vec<Aabb> {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let state = self.world.block(x, y, z);
|
||||
let at = horizon_core::position::BlockPos::new(x, y, z);
|
||||
let context = horizon_world::collision_context::CollisionContext::empty(false);
|
||||
let offset = Vec3::new(f64::from(x), f64::from(y), f64::from(z));
|
||||
self.collision
|
||||
.collision_shape_with_context(&mut scene, state, at, &context)
|
||||
.map(|shape| shape.boxes().iter().map(|b| b.move_by(offset)).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub fn no_collision(&self, b: Aabb) -> bool {
|
||||
let mut scene = SceneCollisions {
|
||||
world: self.world,
|
||||
@@ -125,6 +141,38 @@ impl MobWorld<'_> {
|
||||
}
|
||||
}
|
||||
impl Mob {
|
||||
/// `Entity.refreshDimensions` after growing from `old_w` by `old_h`:
|
||||
/// `fudgePositionAfterSizeChange` moves the mob to the free spot nearest
|
||||
/// its old centre where the bigger box fits (`findFreePosition`), or
|
||||
/// failing that, one that fits at the old height.
|
||||
pub fn fudge_position_after_size_change(&mut self, w: &MobWorld, old_w: f64, old_h: f64) {
|
||||
let (new_w, new_h, _) = self.dims();
|
||||
let small = new_w <= 4.0 && new_h <= 4.0;
|
||||
if self.age == 0 || self.no_physics() || !small || !(new_w > old_w || new_h > old_h) {
|
||||
return;
|
||||
}
|
||||
let center = Vec3::new(
|
||||
self.position.x,
|
||||
self.position.y + old_h / 2.0,
|
||||
self.position.z,
|
||||
);
|
||||
let dw = (new_w - old_w).max(0.0) + 1.0e-6;
|
||||
let dh = (new_h - old_h).max(0.0) + 1.0e-6;
|
||||
let at = |allowed: Aabb, size_y: f64| free_position(w, allowed, center, new_w, size_y);
|
||||
if let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, dh, dw)), new_h) {
|
||||
self.position = Vec3::new(p.x, p.y - new_h / 2.0, p.z);
|
||||
return;
|
||||
}
|
||||
if new_w > old_w
|
||||
&& new_h > old_h
|
||||
&& let Some(p) = at(Aabb::of_size(center, Vec3::new(dw, 1.0e-6, dw)), old_h)
|
||||
{
|
||||
self.position = Vec3::new(p.x, p.y - old_h / 2.0 + 1.0e-6, p.z);
|
||||
}
|
||||
}
|
||||
fn no_physics(&self) -> bool {
|
||||
false
|
||||
}
|
||||
pub fn eye_y(&self) -> f64 {
|
||||
self.position.y + self.eye_height()
|
||||
}
|
||||
@@ -417,14 +465,21 @@ impl Mob {
|
||||
self.travel_in_air(w, input, events);
|
||||
}
|
||||
}
|
||||
/// LivingEntity.travelFlying (ghast 0.02, phantom 0.2): no gravity, 0.91 drag.
|
||||
/// LivingEntity.travelFlying: no gravity, `0.91F` drag in the air,
|
||||
/// `0.8F` in water and 0.5 in lava. A happy ghast swims as fast as it
|
||||
/// flies (`HappyGhast.travel`); the others at 0.02.
|
||||
fn travel_flying(&mut self, w: &MobWorld, input: Vec3, events: &mut Vec<MobEvent>) {
|
||||
let (speed, drag) = if self.fluids.in_water {
|
||||
(0.02, 0.8)
|
||||
} else if self.fluids.in_lava {
|
||||
(0.02, 0.5)
|
||||
let fluid_speed = if self.species() == super::Species::HappyGhast {
|
||||
self.kind.air_speed
|
||||
} else {
|
||||
(self.kind.air_speed, 0.91)
|
||||
0.02
|
||||
};
|
||||
let (speed, drag) = if self.fluids.in_water {
|
||||
(fluid_speed, f64::from(0.8_f32))
|
||||
} else if self.fluids.in_lava {
|
||||
(fluid_speed, 0.5)
|
||||
} else {
|
||||
(self.kind.air_speed, f64::from(0.91_f32))
|
||||
};
|
||||
self.move_relative(speed, input);
|
||||
self.do_move(w, events);
|
||||
@@ -638,3 +693,44 @@ fn fluid_falling(gravity: f64, falling: bool, m: Vec3) -> Vec3 {
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// `CollisionGetter.findFreePosition`: within `allowed`, the point nearest
|
||||
/// `preferred` at which a box of the size, centred there, meets no block.
|
||||
fn free_position(
|
||||
w: &MobWorld,
|
||||
allowed: Aabb,
|
||||
preferred: Vec3,
|
||||
size_x: f64,
|
||||
size_y: f64,
|
||||
) -> Option<Vec3> {
|
||||
use horizon_core::geometry::{ShapeOp, VoxelShape};
|
||||
let allowed_shape = VoxelShape::from_box(allowed).ok()?;
|
||||
if allowed_shape.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let half = Vec3::new(size_x / 2.0, size_y / 2.0, size_x / 2.0);
|
||||
let area = allowed.inflate(half);
|
||||
let (lo, hi) = (area.min_position(), area.max_position());
|
||||
let mut collisions = VoxelShape::empty();
|
||||
// getBlockCollisions: the block shapes that reach into the area.
|
||||
for x in (lo.x - 1.0e-7).floor() as i32 - 1..=(hi.x + 1.0e-7).floor() as i32 + 1 {
|
||||
for y in (lo.y - 1.0e-7).floor() as i32 - 1..=(hi.y + 1.0e-7).floor() as i32 + 1 {
|
||||
for z in (lo.z - 1.0e-7).floor() as i32 - 1..=(hi.z + 1.0e-7).floor() as i32 + 1 {
|
||||
let boxes = w.block_collision_boxes(x, y, z);
|
||||
let touches = boxes.iter().any(|b| {
|
||||
let (a, c) = (b.min_position(), b.max_position());
|
||||
a.x < hi.x && c.x > lo.x && a.y < hi.y && c.y > lo.y && a.z < hi.z && c.z > lo.z
|
||||
});
|
||||
if !touches {
|
||||
continue;
|
||||
}
|
||||
for b in boxes {
|
||||
let grown = VoxelShape::from_box(b.inflate(half)).ok()?;
|
||||
collisions = collisions.join(&grown, ShapeOp::OR).ok()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?;
|
||||
free.closest_point(preferred)
|
||||
}
|
||||
|
||||
@@ -3,9 +3,7 @@
|
||||
//! spit ranged attack, hunting wolves (and, for traders, zombies and
|
||||
//! illagers) and `LlamaModel`.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld, Seen, Species, Who,
|
||||
anim::{Poses, State},
|
||||
equine,
|
||||
Mob, MobEvent, MobWorld, Seen, Species, Who, equine,
|
||||
goals::{
|
||||
Breed, Cx, Float, FollowParent, Goal, HurtByTarget, LookAtPlayer, NearestTarget, Panic,
|
||||
Prey, RandomLookAround, Stroll, Tempt, goal_clone,
|
||||
@@ -14,7 +12,6 @@ use super::{
|
||||
};
|
||||
use crate::projectiles::{Projectile, ProjectileKind};
|
||||
use horizon_core::{geometry::Vec3, random::RandomSource};
|
||||
use std::f32::consts::PI;
|
||||
|
||||
pub const VARIANTS: [&str; 4] = ["creamy", "white", "brown", "gray"];
|
||||
/// `Llama.getMaxTemper`.
|
||||
@@ -29,9 +26,10 @@ pub fn is_llama(s: Species) -> bool {
|
||||
pub fn is_trader(m: &Mob) -> bool {
|
||||
m.species() == Species::TraderLlama
|
||||
}
|
||||
/// `Llama.getStrength`.
|
||||
/// `Llama.getStrength`: the stored strength (0 for a llama that was never
|
||||
/// given one; `setStrength` keeps it within 1 to 5).
|
||||
pub fn strength(m: &Mob) -> i32 {
|
||||
i32::from(m.extra.variant2).clamp(1, 5)
|
||||
i32::from(m.extra.variant2)
|
||||
}
|
||||
/// `getInventoryColumns`: a chest holds three rows of `strength` columns.
|
||||
pub fn inventory_columns(m: &Mob) -> i32 {
|
||||
@@ -64,7 +62,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(1, Panic::new(2.0));
|
||||
}
|
||||
g.add(1, equine::RunAroundLikeCrazy);
|
||||
g.add(2, super::caravan::FollowCaravan::new(2.1));
|
||||
g.add(2, super::caravan::FollowCaravan::new(f64::from(2.1_f32)));
|
||||
g.add(3, RangedAttack::new(1.25, 40, 40, 20.0, spit));
|
||||
g.add(3, Panic::new(1.2));
|
||||
g.add(4, Breed::new(1.0));
|
||||
@@ -129,6 +127,59 @@ pub fn offspring(child: &mut Mob, a: &Mob, b: &Mob, r: &mut impl RandomSource) {
|
||||
child.persistent = true;
|
||||
}
|
||||
}
|
||||
/// A llama's baby as `Llama.getBreedOffspring` makes it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Offspring {
|
||||
pub max_health: f32,
|
||||
pub jump: f64,
|
||||
pub speed: f64,
|
||||
pub strength: u8,
|
||||
pub variant: u8,
|
||||
}
|
||||
/// `Llama.getBreedOffspring` with `AbstractHorse.setOffspringAttributes`,
|
||||
/// drawn from the parent's random with the partner's stock.
|
||||
pub fn breed_offspring(m: &mut Mob, partner: &Seen) -> Offspring {
|
||||
// Seen.profession is the partner's strength.
|
||||
let top = strength(m).max(i32::from(partner.profession));
|
||||
let (health, jump, speed, own) = (
|
||||
f64::from(m.attrs.max_health),
|
||||
m.extra.vector[0],
|
||||
m.attrs.speed,
|
||||
m.extra.variant,
|
||||
);
|
||||
let r = &mut m.random;
|
||||
let max_health = equine::offspring(health, partner.stats[0], 15.0, 30.0, r) as f32;
|
||||
let jump = equine::offspring(jump, partner.stats[1], 0.4, 1.0, r);
|
||||
let speed = equine::offspring(speed, partner.stats[2], 0.1125, 0.3375, r);
|
||||
let mut s = r.next_int_bound(top).unwrap_or(0) + 1;
|
||||
if r.next_float() < 0.03 {
|
||||
s += 1;
|
||||
}
|
||||
let variant = if r.next_boolean() {
|
||||
own
|
||||
} else {
|
||||
partner.variant
|
||||
};
|
||||
Offspring {
|
||||
max_health,
|
||||
jump,
|
||||
speed,
|
||||
strength: s.clamp(1, 5) as u8,
|
||||
variant,
|
||||
}
|
||||
}
|
||||
/// The game makes the baby drawn by `breed_offspring`.
|
||||
pub fn apply_offspring(child: &mut Mob, o: &Offspring) {
|
||||
child.attrs.max_health = o.max_health;
|
||||
child.health = o.max_health;
|
||||
child.extra.vector[0] = o.jump;
|
||||
child.attrs.speed = o.speed;
|
||||
child.extra.variant2 = o.strength;
|
||||
child.extra.variant = o.variant;
|
||||
if is_trader(child) {
|
||||
child.persistent = true;
|
||||
}
|
||||
}
|
||||
/// `LlamaHurtByTargetGoal`: stops hunting right after a spit.
|
||||
#[derive(Clone, Debug)]
|
||||
struct LlamaHurtBy(HurtByTarget);
|
||||
@@ -255,17 +306,6 @@ pub fn decor(m: &Mob) -> Option<(String, String)> {
|
||||
(model.into(), format!("entity/equipment/llama_body/{name}"))
|
||||
})
|
||||
}
|
||||
/// `LlamaModel.setupAnim`.
|
||||
pub fn anim(m: &Mob, s: &State, p: &mut Poses) {
|
||||
super::anim::quadruped(p, s);
|
||||
let chest = m.extra.chested && !s.baby;
|
||||
for part in ["right_chest", "left_chest"] {
|
||||
if !chest {
|
||||
p.visible(part, false);
|
||||
}
|
||||
}
|
||||
let _ = PI;
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -3,13 +3,10 @@
|
||||
//! digging up a seed, the explored positions, laying eggs when bred, and
|
||||
//! `SnifferModel`'s keyframe animations.
|
||||
use super::{
|
||||
Mob, MobEvent, MobWorld,
|
||||
Mob, MobEvent,
|
||||
anim::{Poses, State},
|
||||
brain::{Sink, Ttl, WalkTarget, duration},
|
||||
goals::{Breed, Cx, Float, Goal, Panic, Tempt, goal_clone},
|
||||
keyframes::Animation,
|
||||
};
|
||||
use horizon_core::random::RandomSource;
|
||||
use std::collections::HashMap;
|
||||
|
||||
// Sniffer state: `variant` the state (below), `scratch[0]` the state the
|
||||
@@ -24,15 +21,14 @@ pub const SEARCHING: u8 = 4;
|
||||
pub const DIGGING: u8 = 5;
|
||||
pub const RISING: u8 = 6;
|
||||
|
||||
const SNIFF_COOLDOWN: i32 = 9600;
|
||||
/// `Sniffer.getBabyStartAge`.
|
||||
pub const BABY_START_AGE: i32 = -48000;
|
||||
|
||||
pub fn state(m: &Mob) -> u8 {
|
||||
m.extra.variant
|
||||
}
|
||||
fn set_state(m: &mut Mob, s: u8) {
|
||||
m.extra.variant = s;
|
||||
fn now(m: &Mob) -> i32 {
|
||||
m.age as i32
|
||||
}
|
||||
/// `Sniffer.getDefaultDimensions`: lower while digging.
|
||||
pub fn digging(m: &Mob) -> bool {
|
||||
@@ -44,468 +40,36 @@ pub fn register(m: &mut Mob) {
|
||||
m.set_malus(PathType::Water, -1.0);
|
||||
m.set_malus(PathType::OnTopOfPowderSnow, -1.0);
|
||||
m.set_malus(PathType::DamageCautious, -1.0);
|
||||
let tempt = m.kind.tempt.clone();
|
||||
let g = &mut m.ai.goals;
|
||||
g.add(0, Float);
|
||||
g.add(0, SnifferPanic(Panic::new(2.0)));
|
||||
g.add(
|
||||
0,
|
||||
Brain {
|
||||
walk: None,
|
||||
sink: Sink::new(500, 700),
|
||||
look: None,
|
||||
look_until: 0,
|
||||
digging: false,
|
||||
happy: false,
|
||||
cooldown: Ttl::default(),
|
||||
sniff_target: None,
|
||||
run: Run::None,
|
||||
until: 0,
|
||||
breed: Breed::new(1.0),
|
||||
tempt: Tempt::new(1.25, tempt, false),
|
||||
love_on: false,
|
||||
tempt_on: false,
|
||||
},
|
||||
);
|
||||
}
|
||||
/// The core's `AnimalPanic`, forgetting any sniffing when it starts.
|
||||
#[derive(Clone, Debug)]
|
||||
struct SnifferPanic(Panic);
|
||||
impl Goal for SnifferPanic {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_use(m, cx)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
set_state(m, IDLING);
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Run {
|
||||
None,
|
||||
Digging,
|
||||
FinishedDigging,
|
||||
Searching,
|
||||
Happy,
|
||||
Scenting,
|
||||
Sniffing,
|
||||
DoNothing,
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
struct Brain {
|
||||
walk: Option<WalkTarget>,
|
||||
sink: Sink,
|
||||
/// `LOOK_TARGET` and the end of `LookAtTargetSink`'s run (0 when not running).
|
||||
look: Option<[f64; 3]>,
|
||||
look_until: i32,
|
||||
/// `SNIFFER_DIGGING`, `SNIFFER_HAPPY`, `SNIFF_COOLDOWN`, `SNIFFER_SNIFFING_TARGET`.
|
||||
digging: bool,
|
||||
happy: bool,
|
||||
cooldown: Ttl,
|
||||
sniff_target: Option<[i32; 3]>,
|
||||
/// The timed behaviour running and when it times out.
|
||||
run: Run,
|
||||
until: i32,
|
||||
breed: Breed,
|
||||
tempt: Tempt,
|
||||
love_on: bool,
|
||||
tempt_on: bool,
|
||||
}
|
||||
impl Goal for Brain {
|
||||
goal_clone!();
|
||||
fn flags(&self) -> u8 {
|
||||
0
|
||||
}
|
||||
fn can_use(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
|
||||
true
|
||||
}
|
||||
fn every_tick(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.brain(m, cx);
|
||||
}
|
||||
}
|
||||
fn now(m: &Mob) -> i32 {
|
||||
m.age as i32
|
||||
}
|
||||
fn sound(m: &Mob, cx: &mut Cx, name: &'static str, pitch: f32) {
|
||||
cx.events
|
||||
.push(MobEvent::Sound(name, m.center(), 1.0, pitch));
|
||||
/// `Sniffer.setState`.
|
||||
pub fn set_state(m: &mut Mob, s: u8) {
|
||||
m.extra.variant = s;
|
||||
}
|
||||
/// `Sniffer.getOnPos`: the block under its feet.
|
||||
fn on_pos(m: &Mob) -> [i32; 3] {
|
||||
pub fn on_pos(m: &Mob) -> [i32; 3] {
|
||||
[
|
||||
m.position.x.floor() as i32,
|
||||
(m.position.y - 0.2).floor() as i32,
|
||||
(m.position.y - f64::from(0.2_f32)).floor() as i32,
|
||||
m.position.z.floor() as i32,
|
||||
]
|
||||
}
|
||||
/// `Sniffer.getHeadBlock`: 2.25 blocks ahead of it, a little above its feet.
|
||||
/// `Sniffer.getHeadBlock`: 2.25 blocks along `getForward()`, at its feet
|
||||
/// plus 0.2.
|
||||
pub fn head_block(m: &Mob) -> [i32; 3] {
|
||||
let (yaw, pitch) = (m.yaw.to_radians(), m.head_pitch.to_radians());
|
||||
let forward = [
|
||||
f64::from(-yaw.sin() * pitch.cos()),
|
||||
f64::from(-pitch.sin()),
|
||||
f64::from(yaw.cos() * pitch.cos()),
|
||||
];
|
||||
use horizon_core::geometry::trig::Mth;
|
||||
// Vec3.directionFromRotation(xRot, yRot).
|
||||
let to_rad = std::f32::consts::PI / 180.0;
|
||||
let y = -m.yaw * to_rad - std::f32::consts::PI;
|
||||
let x = -m.head_pitch * to_rad;
|
||||
let (y_cos, y_sin) = (y.mcos(), y.msin());
|
||||
let x_cos = -x.mcos();
|
||||
let forward = [f64::from(y_sin * x_cos), f64::from(y_cos * x_cos)];
|
||||
[
|
||||
(m.position.x + forward[0] * 2.25).floor() as i32,
|
||||
(m.position.y + f64::from(0.2_f32)).floor() as i32,
|
||||
(m.position.z + forward[2] * 2.25).floor() as i32,
|
||||
(m.position.z + forward[1] * 2.25).floor() as i32,
|
||||
]
|
||||
}
|
||||
impl Brain {
|
||||
fn tempted(&self) -> bool {
|
||||
self.tempt_on
|
||||
}
|
||||
/// `Sniffer.canSniff`.
|
||||
fn can_sniff(&self, m: &Mob) -> bool {
|
||||
!self.tempted()
|
||||
&& !m.ai.panicking
|
||||
&& !m.fluids.in_water
|
||||
&& m.extra.in_love <= 0
|
||||
&& m.on_ground
|
||||
&& m.rider.is_none()
|
||||
&& m.extra.leash.is_none()
|
||||
}
|
||||
/// `Sniffer.canDig(BlockPos)`: diggable, unexplored and reachable.
|
||||
fn can_dig_at(&self, m: &mut Mob, w: &MobWorld, p: [i32; 3]) -> bool {
|
||||
w.has_tag(
|
||||
"minecraft:sniffer_diggable_block",
|
||||
w.block_name(p[0], p[1], p[2]),
|
||||
) && !m.extra.positions.contains(&p)
|
||||
&& m.create_path_to(w, p, 1).is_some_and(|path| path.reached)
|
||||
}
|
||||
/// `Sniffer.canDig`.
|
||||
fn can_dig(&self, m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if m.ai.panicking
|
||||
|| self.tempted()
|
||||
|| m.is_baby()
|
||||
|| m.fluids.in_water
|
||||
|| !m.on_ground
|
||||
|| m.rider.is_some()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let head = head_block(m);
|
||||
self.can_dig_at(m, w, [head[0], head[1] - 1, head[2]])
|
||||
}
|
||||
/// `Sniffer.calculateDigPosition`.
|
||||
fn dig_position(&self, m: &mut Mob, w: &MobWorld) -> Option<[i32; 3]> {
|
||||
for idx in 0..5 {
|
||||
let Some(p) = m.land_random_pos(w, 10 + 2 * idx, 3) else {
|
||||
continue;
|
||||
};
|
||||
let below = [
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32 - 1,
|
||||
p[2].floor() as i32,
|
||||
];
|
||||
if self.can_dig_at(m, w, below) {
|
||||
return Some(below);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn transition(&mut self, m: &mut Mob, cx: &mut Cx, to: u8) {
|
||||
match to {
|
||||
FEELING_HAPPY => sound(m, cx, "entity.sniffer.happy", 1.0),
|
||||
SCENTING => {
|
||||
let pitch = if m.is_baby() { 1.3 } else { 1.0 };
|
||||
sound(m, cx, "entity.sniffer.scenting", pitch)
|
||||
}
|
||||
SNIFFING => sound(m, cx, "entity.sniffer.sniffing", 1.0),
|
||||
DIGGING => m.extra.ints[3] = now(m) + 120,
|
||||
RISING => sound(m, cx, "entity.sniffer.digging_stop", 1.0),
|
||||
_ => {}
|
||||
}
|
||||
set_state(m, to);
|
||||
}
|
||||
/// `SnifferAi.resetSniffing`.
|
||||
fn reset_sniffing(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.digging = false;
|
||||
self.sniff_target = None;
|
||||
self.transition(m, cx, IDLING);
|
||||
}
|
||||
fn brain(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.cooldown.tick();
|
||||
// Tempted: the tempting player memory while the goal runs.
|
||||
if m.ai.panicking {
|
||||
self.walk = None;
|
||||
self.sink.stop(m, &mut self.walk);
|
||||
self.love_on = false;
|
||||
self.tempt_on = false;
|
||||
} else {
|
||||
self.start_behaviours(m, cx);
|
||||
}
|
||||
self.sink.tick(m, cx, &mut self.walk);
|
||||
self.tick_running(m, cx);
|
||||
}
|
||||
/// `Brain.startEachNonRunningBehavior` for the first valid activity.
|
||||
fn start_behaviours(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
// DIG, SNIFF, IDLE.
|
||||
let dig = self.digging && self.walk.is_none();
|
||||
let sniff = self.sniff_target.is_some() && self.walk.is_some();
|
||||
if dig {
|
||||
if self.run == Run::None && !self.cooldown.present() && self.can_sniff(m) {
|
||||
self.run = Run::Digging;
|
||||
self.until = n + duration(m, 160, 180);
|
||||
self.transition(m, cx, DIGGING);
|
||||
}
|
||||
if self.run == Run::None && self.cooldown.present() {
|
||||
self.run = Run::FinishedDigging;
|
||||
self.until = n + 40;
|
||||
self.transition(m, cx, RISING);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if sniff {
|
||||
if self.run == Run::None && self.can_sniff(m) {
|
||||
self.run = Run::Searching;
|
||||
self.until = n + 600;
|
||||
self.transition(m, cx, SEARCHING);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.digging {
|
||||
return;
|
||||
}
|
||||
// IDLE: love, tempt, look at the target, feeling happy, one of the rest.
|
||||
if !self.love_on && !self.tempt_on && self.breed.can_use(m, cx) {
|
||||
self.reset_sniffing(m, cx);
|
||||
self.breed.start(m, cx);
|
||||
self.love_on = true;
|
||||
}
|
||||
if !self.love_on && !self.tempt_on && self.tempt.can_use(m, cx) {
|
||||
self.reset_sniffing(m, cx);
|
||||
self.tempt.start(m, cx);
|
||||
self.tempt_on = true;
|
||||
}
|
||||
if self.look.is_some() && self.look_until == 0 {
|
||||
self.look_until = n + duration(m, 45, 90);
|
||||
}
|
||||
if self.run == Run::None && self.happy {
|
||||
self.run = Run::Happy;
|
||||
self.until = n + duration(m, 40, 100);
|
||||
self.transition(m, cx, FEELING_HAPPY);
|
||||
}
|
||||
if self.run == Run::None {
|
||||
self.run_one(m, cx);
|
||||
}
|
||||
}
|
||||
/// The idle `RunOne`: a weighted random pick among what can start.
|
||||
fn run_one(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
// (weight, option)
|
||||
let mut options: Vec<(i32, u8)> = Vec::new();
|
||||
if self.look.is_some() && self.walk.is_none() {
|
||||
options.push((2, 0));
|
||||
}
|
||||
if !self.happy && !self.love_on && !self.tempted() && self.sniff_target.is_none() {
|
||||
options.push((1, 1));
|
||||
}
|
||||
if self.walk.is_none()
|
||||
&& self.sniff_target.is_none()
|
||||
&& !self.cooldown.present()
|
||||
&& !m.is_baby()
|
||||
&& self.can_sniff(m)
|
||||
{
|
||||
options.push((1, 2));
|
||||
}
|
||||
if cx.w.player.as_ref().is_some_and(|p| {
|
||||
p.alive && !p.creative && m.distance_sqr(p.position) <= 36.0 && !p.spectator
|
||||
}) {
|
||||
options.push((1, 3));
|
||||
}
|
||||
if self.walk.is_none() {
|
||||
options.push((1, 4));
|
||||
}
|
||||
options.push((2, 5));
|
||||
let total: i32 = options.iter().map(|o| o.0).sum();
|
||||
// A weighted pick from the high bits (`WeightedList.getRandom`).
|
||||
let mut roll = ((m.random.next_float() * total as f32) as i32).min(total - 1);
|
||||
let mut pick = options[0].1;
|
||||
for (w, o) in &options {
|
||||
if roll < *w {
|
||||
pick = *o;
|
||||
break;
|
||||
}
|
||||
roll -= w;
|
||||
}
|
||||
match pick {
|
||||
// SetWalkTargetFromLookTarget(1.0, 3).
|
||||
0 => {
|
||||
if let Some(l) = self.look {
|
||||
self.walk = Some(WalkTarget::new(
|
||||
[
|
||||
l[0].floor() as i32,
|
||||
l[1].floor() as i32,
|
||||
l[2].floor() as i32,
|
||||
],
|
||||
1.0,
|
||||
3,
|
||||
));
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
self.run = Run::Scenting;
|
||||
self.until = n + duration(m, 40, 80);
|
||||
self.transition(m, cx, SCENTING);
|
||||
}
|
||||
2 => {
|
||||
self.run = Run::Sniffing;
|
||||
self.until = n + duration(m, 40, 80);
|
||||
self.transition(m, cx, SNIFFING);
|
||||
}
|
||||
// SetEntityLookTarget(PLAYER, 6).
|
||||
3 => {
|
||||
if let Some(p) = &cx.w.player {
|
||||
self.look = Some(p.eye);
|
||||
self.look_until = 0;
|
||||
}
|
||||
}
|
||||
// RandomStroll.stroll(1.0).
|
||||
4 => {
|
||||
if let Some(p) = m.land_random_pos(cx.w, 10, 7) {
|
||||
self.walk = Some(WalkTarget::new(
|
||||
[
|
||||
p[0].floor() as i32,
|
||||
p[1].floor() as i32,
|
||||
p[2].floor() as i32,
|
||||
],
|
||||
1.0,
|
||||
0,
|
||||
));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.run = Run::DoNothing;
|
||||
self.until = n + duration(m, 5, 20);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Brain.tickRunningBehaviors`.
|
||||
fn tick_running(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
let n = now(m);
|
||||
let timed_out = n > self.until;
|
||||
// The delegated idle behaviours.
|
||||
if self.love_on {
|
||||
if self.breed.can_continue(m, cx) {
|
||||
self.breed.tick(m, cx);
|
||||
} else {
|
||||
self.breed.stop(m, cx);
|
||||
self.love_on = false;
|
||||
}
|
||||
}
|
||||
if self.tempt_on {
|
||||
self.tempt.stop_distance = if m.is_baby() { 2.5 } else { 3.5 };
|
||||
if self.tempt.can_continue(m, cx) {
|
||||
self.tempt.tick(m, cx);
|
||||
} else {
|
||||
self.tempt.stop(m, cx);
|
||||
self.tempt_on = false;
|
||||
}
|
||||
}
|
||||
// LookAtTargetSink.
|
||||
if self.look_until != 0 {
|
||||
if let Some(l) = self.look
|
||||
&& n <= self.look_until
|
||||
{
|
||||
m.look_at(l);
|
||||
} else {
|
||||
self.look = None;
|
||||
self.look_until = 0;
|
||||
}
|
||||
}
|
||||
match self.run {
|
||||
Run::None => {}
|
||||
Run::Digging => {
|
||||
let ok = self.digging && self.can_dig(m, cx.w) && m.extra.in_love <= 0;
|
||||
if timed_out || !ok {
|
||||
if timed_out {
|
||||
self.cooldown.set(SNIFF_COOLDOWN);
|
||||
} else {
|
||||
self.reset_sniffing(m, cx);
|
||||
}
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::FinishedDigging => {
|
||||
if timed_out || !self.digging {
|
||||
self.transition(m, cx, IDLING);
|
||||
// onDiggingComplete: remember the spot when it finished.
|
||||
if timed_out {
|
||||
let p = on_pos(m);
|
||||
m.extra.positions.insert(0, p);
|
||||
m.extra.positions.truncate(21);
|
||||
}
|
||||
self.digging = false;
|
||||
self.happy = true;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Searching => {
|
||||
let still = if !self.can_sniff(m) {
|
||||
self.transition(m, cx, IDLING);
|
||||
false
|
||||
} else {
|
||||
match (self.walk, self.sniff_target) {
|
||||
(Some(w), Some(t)) => w.pos == t,
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
if timed_out || !still {
|
||||
if self.can_dig(m, cx.w) && self.can_sniff(m) {
|
||||
self.digging = true;
|
||||
}
|
||||
self.sink.stop(m, &mut self.walk);
|
||||
self.sniff_target = None;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Happy => {
|
||||
if timed_out {
|
||||
self.transition(m, cx, IDLING);
|
||||
self.happy = false;
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Scenting => {
|
||||
if timed_out {
|
||||
self.transition(m, cx, IDLING);
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::Sniffing => {
|
||||
if timed_out || !self.can_sniff(m) {
|
||||
self.transition(m, cx, IDLING);
|
||||
if timed_out && let Some(p) = self.dig_position(m, cx.w) {
|
||||
self.sniff_target = Some(p);
|
||||
self.walk = Some(WalkTarget::new(p, 1.25, 0));
|
||||
}
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
Run::DoNothing => {
|
||||
if timed_out {
|
||||
self.run = Run::None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/// `Sniffer.tick` and `Sniffer.aiStep` additions: the animation states,
|
||||
/// the dropped seed and the water malus.
|
||||
pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
@@ -540,14 +104,7 @@ pub fn ai_step(m: &mut Mob, events: &mut Vec<MobEvent>) {
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
if current == SEARCHING && m.age.is_multiple_of(20) {
|
||||
events.push(MobEvent::Sound(
|
||||
"entity.sniffer.searching",
|
||||
m.center(),
|
||||
1.0,
|
||||
1.0,
|
||||
));
|
||||
}
|
||||
// The searching sound is the client's (`playSearchingSound`).
|
||||
// onPathfindingStart / Done: water only blocks the way while it is dry.
|
||||
let wet = m.fluids.in_water || m.fire_ticks > 0;
|
||||
m.set_malus(PathType::Water, if wet { 0.0 } else { -1.0 });
|
||||
|
||||
@@ -65,7 +65,7 @@ pub fn register(m: &mut Mob) {
|
||||
g.add(1, Float);
|
||||
g.add(1, TamePanic(Panic::new(1.5)));
|
||||
g.add(2, SitWhenOrdered);
|
||||
g.add(3, AvoidLlamas);
|
||||
g.add(3, AvoidLlamas::new());
|
||||
g.add(4, LeapAtTarget::new(0.4));
|
||||
g.add(5, MeleeAttack::new(1.0, true));
|
||||
g.add(6, FollowOwner::new(1.0, 10.0, 2.0));
|
||||
@@ -255,38 +255,56 @@ impl Goal for SitWhenOrdered {
|
||||
}
|
||||
/// `Wolf.WolfAvoidEntityGoal`: untamed wolves flee llamas.
|
||||
#[derive(Clone, Debug)]
|
||||
struct AvoidLlamas;
|
||||
struct AvoidLlamas(super::goals::AvoidEntity);
|
||||
impl AvoidLlamas {
|
||||
fn new() -> Self {
|
||||
Self(super::goals::AvoidEntity::new(
|
||||
super::goals::Avoid::Species(vec![Species::Llama, Species::TraderLlama]),
|
||||
24.0,
|
||||
1.5,
|
||||
1.5,
|
||||
))
|
||||
}
|
||||
}
|
||||
/// `Wolf.WolfAvoidEntityGoal`: a wild wolf runs from a llama, the more
|
||||
/// likely the stronger it is (`strength >= random.nextInt(5)`), and drops
|
||||
/// its target while it does.
|
||||
impl Goal for AvoidLlamas {
|
||||
goal_clone!();
|
||||
fn name(&self) -> &'static str {
|
||||
"WolfAvoidEntityGoal"
|
||||
}
|
||||
fn flags(&self) -> u8 {
|
||||
MOVE
|
||||
self.0.flags()
|
||||
}
|
||||
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
if m.extra.tame {
|
||||
if !self.0.can_use(m, cx) {
|
||||
return false;
|
||||
}
|
||||
let pos = m.position;
|
||||
let llama =
|
||||
cx.w.nearby(pos, 24.0, |s| {
|
||||
matches!(s.species, Species::Llama | Species::TraderLlama) && s.alive
|
||||
})
|
||||
.map(|s| s.position)
|
||||
.next();
|
||||
let Some(from) = llama else {
|
||||
// Seen.profession is the llama's strength (`variant2`).
|
||||
let Some(strength) = self
|
||||
.0
|
||||
.found
|
||||
.and_then(|id| cx.w.seen(id))
|
||||
.map(|s| s.profession)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// DefaultRandomPos.getPosAway(16, 7, from).
|
||||
let away = Vec3::new(pos.x - from.x, 0.0, pos.z - from.z);
|
||||
let len = (away.x * away.x + away.z * away.z).sqrt().max(1e-6);
|
||||
let target = [
|
||||
pos.x + away.x / len * 16.0,
|
||||
pos.y,
|
||||
pos.z + away.z / len * 16.0,
|
||||
];
|
||||
m.nav_move_to(cx.w, target, 1.5)
|
||||
!m.extra.tame && i32::from(strength) >= m.random.next_int_bound(5).unwrap_or(0)
|
||||
}
|
||||
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
|
||||
!m.ai.nav.is_done()
|
||||
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
|
||||
self.0.can_continue(m, cx)
|
||||
}
|
||||
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
self.0.start(m, cx)
|
||||
}
|
||||
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
self.0.stop(m, cx)
|
||||
}
|
||||
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
|
||||
m.ai.target = None;
|
||||
self.0.tick(m, cx)
|
||||
}
|
||||
}
|
||||
/// `FollowOwnerGoal(speed, startDistance, stopDistance)`.
|
||||
|
||||
@@ -115,6 +115,16 @@ public final class VanillaEntityAnimOracle {
|
||||
else if (t == boolean.class) f.setBoolean(state, value.getAsBoolean());
|
||||
else if (t.isEnum()) {
|
||||
for (Object c : t.getEnumConstants()) if (((Enum<?>) c).name().equals(value.getAsString())) f.set(state, c);
|
||||
} else if (t == net.minecraft.world.item.ItemStack.class) {
|
||||
// value = an item id. The item components are not bound outside a level, so the stack
|
||||
// carries none: models only test that it is not empty.
|
||||
var item = net.minecraft.core.registries.BuiltInRegistries.ITEM.wrapAsHolder(net.minecraft.core.registries.BuiltInRegistries.ITEM.getValue(
|
||||
net.minecraft.resources.Identifier.parse(value.getAsString())));
|
||||
var ctor = net.minecraft.world.item.ItemStack.class.getDeclaredConstructor(net.minecraft.core.Holder.class, int.class,
|
||||
net.minecraft.core.component.PatchedDataComponentMap.class);
|
||||
ctor.setAccessible(true);
|
||||
f.set(state, ctor.newInstance(item, 1, new net.minecraft.core.component.PatchedDataComponentMap(
|
||||
net.minecraft.core.component.DataComponentMap.EMPTY)));
|
||||
} else if (t.getSimpleName().equals("AnimationState")) {
|
||||
// value = age in ticks since start (negative = stopped)
|
||||
var a = (net.minecraft.world.entity.AnimationState) f.get(state);
|
||||
|
||||
@@ -162,6 +162,8 @@ public final class VanillaMobAiOracle {
|
||||
/** The tick from which the player faces turnYaw (head and body), else 0. */
|
||||
int turnTick = Integer.MAX_VALUE;
|
||||
float turnYaw;
|
||||
/** What the player holds in its main hand (an item id), or null. */
|
||||
String hand;
|
||||
List<MobSpec> mobs = new ArrayList<>();
|
||||
long levelSeed = 0;
|
||||
/** Blocks placed when the scenario starts, so their block entities start afresh and tick. */
|
||||
@@ -207,7 +209,8 @@ public final class VanillaMobAiOracle {
|
||||
String[] tv = f[i].substring(5).split(",");
|
||||
s.turnTick = Integer.parseInt(tv[0]);
|
||||
s.turnYaw = Float.parseFloat(tv[1]);
|
||||
} else throw new IllegalArgumentException(line);
|
||||
} else if (f[i].startsWith("hand=")) s.hand = f[i].substring(5);
|
||||
else throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
case "mob" -> {
|
||||
@@ -461,6 +464,8 @@ public final class VanillaMobAiOracle {
|
||||
method(player.connection.getClass(), "markClientLoaded").invoke(player.connection);
|
||||
}
|
||||
player.setGameMode(s.creative ? GameType.CREATIVE : GameType.SURVIVAL);
|
||||
player.setItemInHand(net.minecraft.world.InteractionHand.MAIN_HAND, s.hand == null ? net.minecraft.world.item.ItemStack.EMPTY
|
||||
: new net.minecraft.world.item.ItemStack(BuiltInRegistries.ITEM.getValue(net.minecraft.resources.Identifier.parse(s.hand))));
|
||||
player.snapTo(s.player[0], s.player[1], s.player[2], 0.0F, 0.0F);
|
||||
// snapTo leaves the head and body as the player was created
|
||||
// (a random head yaw): face +z like the probe's player.
|
||||
@@ -493,6 +498,14 @@ public final class VanillaMobAiOracle {
|
||||
for (String flag : spec.flags) {
|
||||
if (flag.equals("persistent")) mob.setPersistenceRequired();
|
||||
else if (flag.equals("noai")) mob.setNoAi(true);
|
||||
else if (flag.equals("inlove")) ((net.minecraft.world.entity.animal.Animal) mob).setInLoveTime(600);
|
||||
else if (flag.equals("tame") && mob instanceof net.minecraft.world.entity.animal.equine.AbstractHorse horse) horse.setTamed(true);
|
||||
else if (flag.startsWith("age=")) ((AgeableMob) mob).setAge(Integer.parseInt(flag.substring(4)));
|
||||
else if (flag.startsWith("strength=")) method(net.minecraft.world.entity.animal.equine.Llama.class, "setStrength", int.class)
|
||||
.invoke(mob, Integer.parseInt(flag.substring(9)));
|
||||
else if (flag.equals("leashed") || flag.startsWith("leashto=")) {
|
||||
// Leashed once every mob exists (below).
|
||||
}
|
||||
else throw new IllegalArgumentException(flag);
|
||||
}
|
||||
level.addFreshEntity(mob);
|
||||
@@ -506,6 +519,14 @@ public final class VanillaMobAiOracle {
|
||||
brains.add(brain);
|
||||
seeds.add(spec.seed);
|
||||
}
|
||||
// Leads: to the player ("leashed") or to the n-th mob ("leashto=n").
|
||||
for (int i = 0; i < s.mobs.size(); i++) {
|
||||
for (String flag : s.mobs.get(i).flags) {
|
||||
if (flag.equals("leashed")) ((net.minecraft.world.entity.Leashable) mobs.get(i)).setLeashedTo(player, true);
|
||||
else if (flag.startsWith("leashto=")) ((net.minecraft.world.entity.Leashable) mobs.get(i))
|
||||
.setLeashedTo(mobs.get(Integer.parseInt(flag.substring(8))), true);
|
||||
}
|
||||
}
|
||||
// Hearts start with the scenario: their tickers have not run during the warm-up.
|
||||
var blockLookup = level.holderLookup(Registries.BLOCK);
|
||||
List<BlockPos> heartPositions = new ArrayList<>();
|
||||
|
||||
@@ -48,6 +48,8 @@ EXTRAS = [
|
||||
('minecraft:pillager#main', 'IllagerModel'), ('minecraft:vindicator#main', 'IllagerModel'),
|
||||
('minecraft:llama#main', 'LlamaModel'), ('minecraft:trader_llama#main', 'LlamaModel'),
|
||||
('minecraft:llama_baby#main', 'BabyLlamaModel'), ('minecraft:trader_llama_baby#main', 'BabyLlamaModel'),
|
||||
# LlamaDecorLayer: the carpet and the trader's blanket.
|
||||
('minecraft:llama#decor', 'LlamaModel'), ('minecraft:llama_baby#decor', 'BabyLlamaModel'),
|
||||
('minecraft:donkey#main', 'DonkeyModel'), ('minecraft:mule#main', 'DonkeyModel'),
|
||||
('minecraft:donkey_baby#main', 'BabyDonkeyModel'), ('minecraft:mule_baby#main', 'BabyDonkeyModel'),
|
||||
('minecraft:skeleton_horse#main', 'HorseModel'), ('minecraft:zombie_horse#main', 'HorseModel'),
|
||||
@@ -138,6 +140,8 @@ PIGLIN = [{'armPose': pose, 'maxCrossbowChageDuration': 25.0, 'ticksUsingItem':
|
||||
EQUINE = [{'eatAnimation': 0.6}, {'standAnimation': 0.5}, {'eatAnimation': 0.3, 'standAnimation': 0.4, 'feedingAnimation': 0.7},
|
||||
{'isInWater': T}, {'standAnimation': 1.0, 'eatAnimation': 1.0}]
|
||||
WATER = [{'isInWater': T}, {'isInWater': F}]
|
||||
GHAST_BODY = [{'bodyItem': 'minecraft:white_harness'}, {'isRidden': T}, {'bodyItem': 'minecraft:red_harness', 'isRidden': T},
|
||||
{'isLeashHolder': T, 'bodyItem': 'minecraft:blue_harness'}]
|
||||
SPECIES = {
|
||||
'horse': EQUINE, 'donkey': EQUINE + [{'hasChest': T}], 'mule': EQUINE + [{'hasChest': T}], 'zombie_horse': EQUINE, 'skeleton_horse': EQUINE,
|
||||
'iron_golem': [{'attackTicksRemaining': 7.0}, {'offerFlowerTick': 30}, {'attackTicksRemaining': 0.0, 'offerFlowerTick': 0}],
|
||||
@@ -176,6 +180,11 @@ SPECIES = {
|
||||
{'sitAmount': 0.6, 'isEating': T}, {'sitAmount': 1.0, 'isScared': T}, {'sitAmount': 0.3},
|
||||
{'lieOnBackAmount': 0.5}, {'rollAmount': 0.7}],
|
||||
'llama': [{'hasChest': T}, {'hasChest': F}],
|
||||
'sniffer': [{'isSearching': T}, {'diggingAnimationState': 2}, {'sniffingAnimationState': 5}, {'risingAnimationState': 1},
|
||||
{'feelingHappyAnimationState': 3}, {'scentingAnimationState': 0}, {'diggingAnimationState': 50, 'isSearching': T},
|
||||
{'feelingHappyAnimationState': 30, 'scentingAnimationState': 20}],
|
||||
'happy_ghast': GHAST_BODY, 'happy_ghast_ropes': GHAST_BODY, 'happy_ghast_baby_ropes': GHAST_BODY,
|
||||
'happy_ghast_harness': GHAST_BODY, 'happy_ghast_baby_harness': GHAST_BODY,
|
||||
'trader_llama': [{'hasChest': T}, {'hasChest': F}],
|
||||
'turtle': [{'isOnLand': T}, {'isOnLand': T, 'isLayingEgg': T}, {'isOnLand': F, 'hasEgg': T}, {'isOnLand': T, 'hasEgg': T}],
|
||||
'strider': [{'isRidden': T}, {'isRidden': F}],
|
||||
|
||||
@@ -98,6 +98,52 @@ def scenarios():
|
||||
add('heart_hurt', 260, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 0.5 -60 -6.5',
|
||||
'hurt 60 0', 'hurt 64 0', 'hurt 200 0'], 'time=18000 spawning')
|
||||
add('heart_far', 120, TRUNK + ['heart 3 -59 3 minecraft:creaking_heart[axis=y,creaking_heart_state=awake,natural=true]', 'player 40.5 -60 0.5'], 'time=18000 spawning')
|
||||
# Llamas and trader llamas: strolling, looking at the player, a baby following its parent and a
|
||||
# llama hunting a wolf (LlamaAttackWolfGoal) and spitting at it.
|
||||
for species, seed in [('llama', 61), ('trader_llama', 62)]:
|
||||
add(f'{species}_player', 200, ['player 6.5 -60 0.5', f'mob minecraft:{species} 0.5 -60 0.5 0 {seed} persistent'])
|
||||
add(f'{species}_alone', 200, [f'mob minecraft:{species} 0.5 -60 0.5 90 {seed * 7 + 1} persistent'])
|
||||
add('llama_family', 200, ['mob minecraft:llama 0.5 -60 0.5 0 63 persistent',
|
||||
'mob minecraft:llama 6.5 -60 2.5 0 64 persistent baby'])
|
||||
add('llama_wolf', 200, ['mob minecraft:llama 0.5 -60 0.5 0 65 persistent',
|
||||
'mob minecraft:wolf 8.5 -60 0.5 0 66 persistent'])
|
||||
# Sniffers on diggable grass: scenting, sniffing, searching and digging.
|
||||
add('sniffer_player', 400, ['player 8.5 -60 0.5', 'mob minecraft:sniffer 0.5 -60 0.5 0 71 persistent'])
|
||||
for i, seed in enumerate([72, 73, 74]):
|
||||
add(f'sniffer_alone_{i}', 600, [f'mob minecraft:sniffer 0.5 -60 0.5 {90 * i} {seed} persistent'])
|
||||
add('sniffer_baby', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 75 persistent baby'])
|
||||
# Happy ghasts float above the grass; ghastlings follow players and adults.
|
||||
add('happy_ghast_player', 200, ['player 6.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -55 0.5 0 81 persistent'])
|
||||
add('happy_ghast_alone', 200, ['mob minecraft:happy_ghast 0.5 -55 0.5 90 82 persistent'])
|
||||
add('ghastling_player', 200, ['player 8.5 -60 0.5', 'mob minecraft:happy_ghast 0.5 -57 0.5 0 83 persistent baby'])
|
||||
add('ghastling_alone', 200, ['mob minecraft:happy_ghast 0.5 -57 0.5 0 84 persistent baby'])
|
||||
add('ghastling_adult', 200, ['mob minecraft:happy_ghast 10.5 -55 0.5 0 85 persistent',
|
||||
'mob minecraft:happy_ghast 0.5 -57 0.5 0 86 persistent baby'])
|
||||
# Breeding, temptation and growing up.
|
||||
add('sniffer_love', 300, ['mob minecraft:sniffer 0.5 -60 0.5 0 91 persistent inlove',
|
||||
'mob minecraft:sniffer 4.5 -60 0.5 0 92 persistent inlove'])
|
||||
add('sniffer_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:torchflower_seeds',
|
||||
'mob minecraft:sniffer 0.5 -60 0.5 0 93 persistent'])
|
||||
add('llama_love', 300, ['mob minecraft:llama 0.5 -60 0.5 0 94 persistent tame inlove strength=3',
|
||||
'mob minecraft:llama 4.5 -60 0.5 0 95 persistent tame inlove strength=2'])
|
||||
add('llama_tempted', 200, ['player 7.5 -60 0.5 hand=minecraft:hay_block',
|
||||
'mob minecraft:llama 0.5 -60 0.5 0 96 persistent'])
|
||||
add('ghastling_tempted', 200, ['player 8.5 -60 0.5 hand=minecraft:snowball',
|
||||
'mob minecraft:happy_ghast 0.5 -57 0.5 0 97 persistent baby'])
|
||||
add('happy_ghast_tempted', 200, ['player 12.5 -60 0.5 hand=minecraft:snowball',
|
||||
'mob minecraft:happy_ghast 0.5 -55 0.5 0 98 persistent'])
|
||||
add('ghastling_grows', 200, ['player 8.5 -60 0.5',
|
||||
'mob minecraft:happy_ghast 0.5 -57 0.5 0 99 persistent age=-40'])
|
||||
# Llama caravans: two llamas fall in behind one on the player's lead; a wandering trader's two
|
||||
# llamas on its leads.
|
||||
add('llama_caravan', 300, ['player 0.5 -60 0.5',
|
||||
'mob minecraft:llama 3.5 -60 0.5 0 101 persistent leashed strength=3',
|
||||
'mob minecraft:llama 9.5 -60 2.5 0 102 persistent strength=2',
|
||||
'mob minecraft:llama 13.5 -60 -1.5 0 103 persistent strength=1'])
|
||||
add('trader_llamas', 300, ['player 14.5 -60 0.5',
|
||||
'mob minecraft:wandering_trader 0.5 -60 0.5 0 104 persistent',
|
||||
'mob minecraft:trader_llama 3.5 -60 1.5 0 105 persistent leashto=0 strength=2',
|
||||
'mob minecraft:trader_llama 3.5 -60 -1.5 0 106 persistent leashto=0 strength=4'])
|
||||
return s
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user