Merge main into fix/sweep-hits-players

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 16:36:41 +01:00
135 changed files with 9012 additions and 681 deletions
@@ -54,7 +54,7 @@ pub fn main() -> Result<()> {
match c["axis"].as_i64() {
Some(axis @ 0..=2) => {
let line = record("electric_spark");
particles::along_axis(&mut random, axis as usize, p, |p, v| {
particles::along_axis(&mut random, axis as usize, p, (10, 19), |p, v| {
lines.push(line(p, v))
});
}
@@ -24,6 +24,7 @@ fn stack(spec: &str) -> LootStack {
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
names: Vec::new(),
};
for e in parts {
let (name, level) = e.rsplit_once(':').unwrap_or((e, "1"));
@@ -223,6 +223,7 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
display_health: int("displayHealth", 0),
last_health_time: millis - i64::from(int("lastHealthAgo", 0)),
health_blink_time: i64::from(int("healthBlinkTime", 0)),
..HealthHud::default()
};
let kind = if has("minecraft:poison") {
HeartKind::Poisoned
@@ -101,7 +101,7 @@ fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
}
let partial = float(c, "partial", 0.0);
let bg = background(c);
let mut out = t.overlay_message(w, h, partial, &atlas.font, bg);
let mut out = t.overlay_message(w, h, 39, partial, &atlas.font, bg);
out.extend(t.title(w, h, partial, &atlas.font, bg));
out
}
@@ -129,7 +129,7 @@ fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
}
let mode = c["gameMode"].as_str().unwrap_or("survival");
let can_hurt = mode == "survival" || mode == "adventure";
highlight.draw(w, h, can_hurt, &atlas.font, background(c))
highlight.draw(w, h, 39, can_hurt, &atlas.font, background(c))
}
fn boss(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
@@ -75,6 +75,10 @@ pub fn main() -> Result<()> {
registry: assets.registry,
raining_at: &|_| false,
marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)),
model_offset: &|_, _, _| None,
gateway_particles: &|_, _| 0,
thundering: false,
ultrawarm: false,
};
engine.seed_randoms(1057, 0, 0);
engine.requested = Some(Vec::new());
@@ -567,7 +567,9 @@ fn print_heart(
/// The damage of a mob's direct hit on the player (others count as none).
fn player_damage(e: &MobEvent) -> f32 {
match e {
MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount,
MobEvent::AttackPlayer(amount, _)
| MobEvent::AttackPlayerWithEffect { amount, .. }
| MobEvent::DamagePlayer { amount, .. } => *amount,
_ => 0.0,
}
}
@@ -578,7 +580,9 @@ fn player_hurt(player: Option<&PlayerView>, e: &MobEvent) -> bool {
return false;
};
match e {
MobEvent::AttackPlayer(amount, _) | MobEvent::DamagePlayer { amount, .. } => *amount > 0.0,
MobEvent::AttackPlayer(amount, _)
| MobEvent::AttackPlayerWithEffect { amount, .. }
| MobEvent::DamagePlayer { amount, .. } => *amount > 0.0,
// ServerExplosion.hurtEntities: within twice the radius every hit does damage.
MobEvent::Explode(at, radius, _) => {
let d = Vec3::new(at[0], at[1], at[2])
@@ -1045,6 +1049,7 @@ pub fn main() -> horizon_client::Result<()> {
alive: true,
creative: s.creative,
sneaking: false,
swimming: false,
look: [0.0, 0.0, 1.0],
main_hand: s.hand.as_deref().map(Into::into),
off_hand: None,
@@ -1057,6 +1062,8 @@ pub fn main() -> horizon_client::Result<()> {
last_hurt: None,
velocity: Vec3::ZERO,
yaw: 0.0,
sprinting: false,
riding: false,
hero: false,
effects: Vec::new(),
uuid: PLAYER_UUID,
@@ -208,7 +208,7 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
)),
MotionEvent::Emission {
state,
in_water: true,
muffled: true,
..
} => Some(format!("muffled-step {}", state.0)),
MotionEvent::BubbleColumnParticle { bubble, position } => Some(format!(
+36 -1
View File
@@ -4,7 +4,7 @@
//! conditions advancements use).
use serde_json::Value;
use std::{
collections::{BTreeMap, HashMap},
collections::{BTreeMap, BTreeSet, HashMap},
path::Path,
};
@@ -753,6 +753,41 @@ pub fn entity(v: &Value, e: &EntityView, w: &dyn World, origin: [f64; 3]) -> boo
}
true
}
/// `KilledByArrowTrigger.TriggerInstance.matches`: the weapon, each listed
/// victim condition matched by a distinct victim, and the count of entity types.
pub fn killed_by_arrow(
c: &Value,
me: &EntityView,
victims: &[EntityView],
weapon: Option<&ItemView>,
w: &dyn World,
) -> bool {
fn ctx<'a>(e: &'a EntityView, me: &EntityView) -> Entities<'a> {
Entities {
this: Some(e),
origin: me.position,
tool: None,
block_pos: None,
}
}
if !conditions(&c["player"], &ctx(me, me), w) {
return false;
}
if !c["fired_from_weapon"].is_null()
&& !weapon.is_some_and(|it| item(&c["fired_from_weapon"], it, w))
{
return false;
}
let mut left: Vec<&EntityView> = victims.iter().collect();
for want in c["victims"].as_array().into_iter().flatten() {
let Some(i) = left.iter().position(|e| conditions(want, &ctx(e, me), w)) else {
return false;
};
left.remove(i);
}
let kinds: BTreeSet<&str> = victims.iter().map(|e| e.kind.as_str()).collect();
range_i(&c["unique_entity_types"], kinds.len() as i64)
}
/// A damage event as `DamagePredicate` sees it.
#[derive(Clone, Debug, Default)]
pub struct DamageView {
+235 -1
View File
@@ -8,7 +8,7 @@ use crate::{
blocks::{BlockFacts, Fluid},
command::args::GameMode,
items::ItemStack,
particles::{ParticleEngine, ParticleOptions, ParticleType as T},
particles::{ParticleEngine, ParticleOptions, ParticleType as T, along_axis},
world::World,
};
use horizon_core::{
@@ -75,6 +75,22 @@ enum Animate {
waterlogged: bool,
},
EndPortal,
/// A powered lever: its facing and the direction it is attached toward.
Lever {
facing: [i32; 3],
connected: [i32; 3],
},
/// A powered repeater.
Repeater {
facing: [i32; 3],
delay: i32,
},
/// A free-hanging stalactite tip that is not waterlogged.
PointedDripstone,
WitherRose,
EndGateway,
/// A lightning rod, by the axis it points along (0, 1, 2 for X, Y, Z).
LightningRod(usize),
/// `WetSpongeBlock.animateTick`.
WetSponge,
}
@@ -91,6 +107,7 @@ fn step(facing: &str) -> [i32; 3] {
fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
let lit = prop("lit").as_deref() == Some("true");
let powered = prop("powered").as_deref() == Some("true");
let facing = || step(&prop("facing").unwrap_or_default());
match name {
"torch" => Animate::Torch(T::Flame),
@@ -172,6 +189,38 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
waterlogged: prop("waterlogged").as_deref() == Some("true"),
},
"end_portal" => Animate::EndPortal,
"lever" if powered => Animate::Lever {
facing: facing(),
// FaceAttachedHorizontalDirectionalBlock.getConnectedDirection.
connected: match prop("face").as_deref() {
Some("ceiling") => [0, -1, 0],
Some("floor") => [0, 1, 0],
_ => facing(),
},
},
"repeater" if powered => Animate::Repeater {
facing: facing(),
delay: prop("delay").and_then(|d| d.parse().ok()).unwrap_or(1),
},
"pointed_dripstone"
if prop("vertical_direction").as_deref() == Some("down")
&& prop("thickness").as_deref() == Some("tip")
&& prop("waterlogged").as_deref() != Some("true") =>
{
Animate::PointedDripstone
}
"wither_rose" => Animate::WitherRose,
"end_gateway" => Animate::EndGateway,
_ if name == "lightning_rod" || name.ends_with("_lightning_rod") => {
let [dx, dy, _] = facing();
Animate::LightningRod(if dx != 0 {
0
} else if dy != 0 {
1
} else {
2
})
}
"wet_sponge" => Animate::WetSponge,
// BrushableBlock has no dust colour of its own, so the dust is the map colour.
"suspicious_sand" => Animate::Falling(0xF7E9A3, false),
@@ -250,6 +299,8 @@ pub struct AnimateTables {
burnable: Vec<bool>,
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
ambient: Vec<Vec<(T, f32)>>,
/// Per state: 1 for a pointed dripstone, 2 for one whose tip points down.
dripstone: Vec<u8>,
}
impl AnimateTables {
pub fn load(root: &Path, registry: &BlockRegistry, biomes: &Biomes) -> crate::Result<Self> {
@@ -315,8 +366,25 @@ impl AnimateTables {
}
}
}
let dripstone = (0..registry.len() as u32)
.map(|id| {
registry.state(BlockStateId(id)).map_or(0, |s| {
let name = s.name.strip_prefix("minecraft:").unwrap_or(&s.name);
if name != "pointed_dripstone" {
0
} else if s.properties.get("vertical_direction").map(String::as_str)
== Some("down")
{
2
} else {
1
}
})
})
.collect();
Ok(Self {
kinds,
dripstone,
impermeable: by_state("minecraft:impermeable"),
power_provider: by_state("minecraft:enchantment_power_provider"),
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
@@ -350,6 +418,14 @@ pub struct AnimateContext<'a> {
pub raining_at: &'a dyn Fn([i32; 3]) -> bool,
/// Creative main-hand marker block and a resolver for each placed state's sprite.
pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option<ParticleOptions>)>,
/// `BlockState.getOffset` of a state at (x, z), for blocks with a random model offset.
pub model_offset: &'a dyn Fn(BlockStateId, i32, i32) -> Option<[f64; 3]>,
/// `TheEndGatewayBlockEntity.getParticleAmount` of the gateway state at a position.
pub gateway_particles: &'a dyn Fn(BlockStateId, [i32; 3]) -> usize,
/// `Level.isThundering`.
pub thundering: bool,
/// The dimension has `water_evaporates` and drips lava from dripstone (the Nether).
pub ultrawarm: bool,
}
/// `ClientLevel.getMarkerParticleTarget`: only the selected main-hand item counts.
@@ -398,6 +474,9 @@ impl AnimateContext<'_> {
],
))
}
fn offset_of(&self, state: BlockStateId, p: [i32; 3]) -> [f64; 3] {
(self.model_offset)(state, p[0], p[2]).unwrap_or([0.0; 3])
}
fn foliage(&self, p: [i32; 3]) -> u32 {
let biome = self
.world
@@ -1079,6 +1158,99 @@ fn block_animate_tick(
let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()];
add(engine, T::Smoke, p, [0.0; 3]);
}
Animate::Lever { facing, connected } => {
// LeverBlock.animateTick: a powered lever puffs red dust a quarter of the time.
if engine.random().next_float() < 0.25 {
// LeverBlock.makeParticle with scale 0.5.
let at = |base: f64, i: usize| {
base + 0.5 + 0.1 * f64::from(-facing[i]) + 0.2 * f64::from(-connected[i])
};
let p = [at(fx, 0), at(fy, 1), at(fz, 2)];
engine.add(&ParticleOptions::dust([1.0, 0.0, 0.0], 0.5), p, [0.0; 3]);
}
}
Animate::Repeater { facing, delay } => {
// RepeaterBlock.animateTick: dust at one of the torches.
let r = engine.random();
let x = fx + 0.5 + (r.next_double() - 0.5) * 0.2;
let y = fy + 0.4 + (r.next_double() - 0.5) * 0.2;
let z = fz + 0.5 + (r.next_double() - 0.5) * 0.2;
let mut offset = -5.0f32;
if r.next_boolean() {
offset = (delay * 2 - 1) as f32;
}
offset /= 16.0;
let xo = f64::from(offset * facing[0] as f32);
let zo = f64::from(offset * facing[2] as f32);
redstone(engine, [x + xo, y, z + zo]);
}
Animate::PointedDripstone => dripstone_drip(tables, engine, ctx, state, pos),
Animate::WitherRose => {
// WitherRoseBlock.animateTick: smoke puffs at the centre of the shape.
let center = ctx.shape_y(pos).map_or([0.5; 2], |s| {
[(s.2[0] + s.2[1]) / 2.0, (s.2[2] + s.2[3]) / 2.0]
});
let offset = ctx.offset_of(state, pos);
let x = fx + center[0] + offset[0];
let z = fz + center[1] + offset[2];
for _ in 0..3 {
let r = engine.random();
if r.next_boolean() {
let p = [
x + r.next_double() / 5.0,
fy + (0.5 - r.next_double()),
z + r.next_double() / 5.0,
];
add(engine, T::Smoke, p, [0.0; 3]);
}
}
}
Animate::EndGateway => {
// EndGatewayBlock.animateTick: portal particles, one for each visible face.
for _ in 0..(ctx.gateway_particles)(state, pos) {
let r = engine.random();
let mut p = [
fx + r.next_double(),
fy + r.next_double(),
fz + r.next_double(),
];
let mut v = [
(r.next_double() - 0.5) * 0.5,
(r.next_double() - 0.5) * 0.5,
(r.next_double() - 0.5) * 0.5,
];
let flip = next_int(r, 2) * 2 - 1;
if r.next_boolean() {
p[2] = fz + 0.5 + 0.25 * f64::from(flip);
v[2] = f64::from(r.next_float() * 2.0 * flip as f32);
} else {
p[0] = fx + 0.5 + 0.25 * f64::from(flip);
v[0] = f64::from(r.next_float() * 2.0 * flip as f32);
}
add(engine, T::Portal, p, v);
}
}
Animate::LightningRod(axis) => {
// LightningRodBlock.animateTick: in a thunderstorm, sparks along the
// topmost rod, more often as the game time within 200 ticks grows.
if ctx.thundering
&& i64::from(next_int(engine.level_random(), 200)) <= ctx.world.game_time % 200
&& pos[1]
== ctx
.world
.world_surface(pos[0], pos[2], |id| ctx.facts.is_air(id))
- 1
{
let mut sparks = Vec::new();
along_axis(engine.level_random(), axis, pos, (1, 2), |p, v| {
sparks.push((p, v));
});
let options = ParticleOptions::simple(T::ElectricSpark);
for (p, v) in sparks {
engine.add(&options, p, v);
}
}
}
Animate::EnderChest => {
for _ in 0..3 {
let r = engine.random();
@@ -1382,6 +1554,68 @@ fn leaves_ambient_sound(
}
}
}
/// `PointedDripstoneBlock.animateTick`: a free-hanging stalactite tip drips the
/// fluid above the root of its stalactite.
fn dripstone_drip(
tables: &AnimateTables,
engine: &mut ParticleEngine,
ctx: &AnimateContext,
state: BlockStateId,
pos: [i32; 3],
) {
let roll = engine.random().next_float();
if roll > 0.12 {
return;
}
// getFluidAboveStalactite: findRootBlock climbs at most ten blocks of
// stalactite and stops at the first block that is not pointed dripstone.
let mut root = None;
for step in 1..11 {
let p = [pos[0], pos[1] + step, pos[2]];
match tables
.dripstone
.get(ctx.state(p).0 as usize)
.copied()
.unwrap_or(0)
{
0 => {
root = Some(p);
break;
}
2 => {}
_ => return,
}
}
let Some(root) = root else {
return;
};
let above = ctx.facts.get(ctx.state([root[0], root[1] + 1, root[2]]));
// Mud above the root counts as a water source unless water evaporates here.
let (fluid, source) = if &*above.name == "minecraft:mud" && !ctx.ultrawarm {
(Fluid::Water, true)
} else {
(above.fluid, above.fluid_level >= 8 && !above.fluid_falling)
};
// canFillCauldron: only a water or lava source passes below a 2% roll.
if roll >= 0.02 && !(fluid != Fluid::None && source) {
return;
}
// getDripParticle: no fluid drips what the dimension's default says.
let lava = fluid == Fluid::Lava || (fluid == Fluid::None && ctx.ultrawarm);
let ty = if lava {
T::DrippingDripstoneLava
} else {
T::DrippingDripstoneWater
};
let offset = ctx.offset_of(state, pos);
// STALACTITE_DRIP_START_PIXEL is the tip's lowest point, 5/16.
let p = [
f64::from(pos[0]) + 0.5 + offset[0],
f64::from(pos[1]) + 0.3125 - 0.0625,
f64::from(pos[2]) + 0.5 + offset[2],
];
add(engine, ty, p, [0.0; 3]);
}
/// `AmbientDesertBlockSoundsPlayer.shouldPlayAmbientSandSound`: sand in the
/// surface column eight blocks away on all four sides.
fn sand_sound_nearby(tables: &AnimateTables, ctx: &AnimateContext, pos: [i32; 3]) -> bool {
+3
View File
@@ -159,6 +159,8 @@ pub struct ArrowState {
pub pickup: Pickup,
/// `pickupItemStack`: what picking the arrow up gives.
pub pickup_item: crate::items::ItemStack,
/// `AbstractArrow.firedFromWeapon`: the crossbow or bow it was shot from.
pub fired_from_weapon: Option<crate::items::ItemStack>,
pub no_physics: bool,
/// `AbstractArrow.getPierceLevel`.
pub pierce: u8,
@@ -208,6 +210,7 @@ impl ArrowState {
last_state: None,
pickup: Pickup::Disallowed,
pickup_item: crate::items::ItemStack::new("minecraft:arrow", 1),
fired_from_weapon: None,
no_physics: false,
pierce: 0,
pierced: Vec::new(),
@@ -938,6 +938,30 @@ impl BlockEntityRenderer {
let lights = diffuse_lights(scene.nether);
self.render_one(scene, pos, kind, base, packed, lights, false, false, out);
}
/// `TheEndGatewayBlockEntity.shouldRenderFace` for each face of the gateway
/// at `pos`: the faces its portal is drawn on.
pub fn gateway_faces(
&self,
world: &World,
state: BlockStateId,
pos: [i32; 3],
) -> Vec<Direction> {
Direction::ALL
.into_iter()
.filter(|&d| {
let [dx, dy, dz] = d.normal();
let neighbor = world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz);
self.visibility.as_ref().is_none_or(|v| {
v.lock()
.map(|mut v| {
v.should_render_face(state, neighbor, d, true)
.unwrap_or(true)
})
.unwrap_or(true)
})
})
.collect()
}
/// Whether this block state has a block-entity renderer here.
pub fn renders(&self, state: u32) -> bool {
!matches!(self.kind(state), Kind::None)
@@ -1439,22 +1463,8 @@ impl BlockEntityRenderer {
out,
);
}
// AbstractEndPortalRenderer.extractRenderState: TheEndGatewayBlockEntity.shouldRenderFace.
let faces: Vec<Direction> = Direction::ALL
.into_iter()
.filter(|&d| {
let [dx, dy, dz] = d.normal();
let neighbor = scene.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz);
self.visibility.as_ref().is_none_or(|v| {
v.lock()
.map(|mut v| {
v.should_render_face(BlockStateId(*state), neighbor, d, true)
.unwrap_or(true)
})
.unwrap_or(true)
})
})
.collect();
// AbstractEndPortalRenderer.extractRenderState.
let faces = self.gateway_faces(scene.world, BlockStateId(*state), pos);
portal_cube(base, &faces, END_GATEWAY_LAYER, out);
}
Kind::Conduit => {
+11
View File
@@ -211,6 +211,17 @@ impl Contents {
self.weight.n >= self.weight.d
}
/// `BundleItem.isBarVisible`, `getBarWidth` and `getBarColor`: the fullness bar
/// (width, RGB), blue until the bundle is full, then red.
pub fn bar(&self) -> Option<(i32, u32)> {
if self.weight.n <= 0 {
return None;
}
let width = (1 + self.weight.n * 12 / self.weight.d).min(13) as i32;
let color = if self.is_full() { 0xFF5454 } else { 0x7087FF };
Some((width, color))
}
/// `toImmutable`, written back into the bundle's component.
pub fn store(self, bundle: &mut ItemStack) {
let data = bundle.data_mut();
+99 -1
View File
@@ -16,6 +16,9 @@ use crate::{
#[path = "chat_tests.rs"]
mod tests;
/// `CommandHistory.PERSISTED_COMMANDS_FILE_NAME` and its size cap.
const COMMAND_HISTORY_FILE: &str = "command_history.txt";
const MAX_PERSISTED_COMMAND_HISTORY: usize = 50;
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
@@ -80,6 +83,10 @@ impl ChatAbilities {
ChatSource::Client => true,
}
}
/// `ChatAbilities.hasAnyRestrictions`: the Chat option takes something.
pub fn any_restriction(&self) -> bool {
*self != Self::new(ChatVisibility::Full)
}
/// Whether the chat screen may send `input` (`hasAllowedInput`).
pub fn allows(&self, input: &str) -> bool {
if input.starts_with('/') {
@@ -185,6 +192,10 @@ pub struct Chat {
lines: Vec<Line>,
/// Sent messages and commands (ChatComponent.recentChat).
pub recent: Vec<String>,
/// `CommandHistory`: the last commands, kept in `command_history.txt`
/// in the game folder once `load_history` has set it.
commands: Vec<String>,
history_file: Option<std::path::PathBuf>,
scroll: usize,
new_since_scroll: bool,
pub options: ChatOptions,
@@ -310,6 +321,17 @@ impl Chat {
self.lines.clear();
self.scroll = 0;
}
/// `new CommandHistory(gameFolder)`: the commands kept from earlier runs
/// start the chat's history (`ChatComponent`'s constructor).
pub fn load_history(&mut self, game_folder: &std::path::Path) {
let file = game_folder.join(COMMAND_HISTORY_FILE);
if let Ok(text) = std::fs::read_to_string(&file) {
self.commands = text.lines().map(str::to_owned).collect();
self.recent.extend(self.commands.iter().cloned());
}
self.history_file = Some(file);
}
/// `ChatComponent.addRecentChat`: a command also goes to the saved history.
pub fn add_recent(&mut self, message: &str) {
if self.recent.last().map(String::as_str) != Some(message) {
if self.recent.len() >= 100 {
@@ -317,6 +339,21 @@ impl Chat {
}
self.recent.push(message.to_owned());
}
if message.starts_with('/') && self.commands.last().map(String::as_str) != Some(message) {
if self.commands.len() >= MAX_PERSISTED_COMMAND_HISTORY {
self.commands.remove(0);
}
self.commands.push(message.to_owned());
if let Some(file) = &self.history_file {
let mut text = self.commands.join("\n");
text.push('\n');
if let Err(e) = std::fs::write(file, text) {
log::error!(
"Failed to write {COMMAND_HISTORY_FILE}, command history will be missing: {e}"
);
}
}
}
}
pub fn reset_scroll(&mut self) {
self.scroll = 0;
@@ -438,10 +475,71 @@ impl Chat {
out.push(GuiDraw::Pop);
out
}
/// Draws [`Chat::layout`] into the HUD batch.
/// Draws [`Chat::layout`] into the HUD batch, and with the chat screen
/// open the restricted prompt above the lines.
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) {
let draws = self.layout(batch.height as i32, ticks, focused);
hud_layout::paint(batch, atlas, &draws);
if focused && self.abilities.any_restriction() {
let prompt = self.restricted_prompt(&atlas.font, batch.height as i32);
hud_layout::paint(batch, atlas, &prompt);
}
}
/// `ChatComponent.extractRenderState` for `FOREGROUND_RESTRICTED`: a
/// background row and the red, underlined "Chat is restricted" line in
/// the row above the messages, clipped to the chat's width.
fn restricted_prompt(&self, font: &crate::font::Font, height: i32) -> Vec<GuiDraw> {
let o = &self.options;
let scale = o.scale as f32;
let max_width = hud_layout::ceil(o.width_px() as f32 / scale);
let chat_bottom = hud_layout::floor((height - 40) as f32 / scale);
let entry_height = o.line_height();
let bottom_to_text =
(8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing + 0.5).floor() as i32;
let shown = self
.lines
.len()
.saturating_sub(self.scroll)
.min(self.lines_per_page(true));
let top = chat_bottom - (shown as i32 + 1) * entry_height;
let mut prompt = Text::translate("chat_screen.restricted", &[]).with_style(&Style {
color: Some(text::RED),
underlined: Some(true),
..Style::default()
});
// ComponentRenderUtils.clipText.
let mut width = 0.0;
let fits = prompt
.chars()
.take_while(|(c, style)| {
width += font.advance(*c, style);
width <= max_width as f32
})
.count();
if fits < prompt.chars().count() {
prompt = prompt.slice(0, fits);
}
vec![
GuiDraw::Push(vec![
PoseOp::Scale(scale, scale),
PoseOp::Translate(4.0, 0.0),
]),
hud_layout::fill(
-2,
top,
max_width + 4 + 4,
top + entry_height,
hud_layout::as8(o.background_opacity as f32) << 24,
),
GuiDraw::Text {
text: prompt,
x: 0,
y: top + entry_height - bottom_to_text - 1,
color: hud_layout::white(o.opacity as f32 * 0.9 + 0.1),
shadow: true,
},
GuiDraw::Pop,
]
}
/// The click action under a GUI-space cursor while chat is focused.
pub fn click_at(
+23
View File
@@ -103,6 +103,22 @@ pub enum BlockEntity {
/// `DaylightDetectorBlockEntity`: no data, only the ticker
/// (`DaylightDetectorBlock.tickEntity`).
DaylightDetector,
/// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots.
ChiseledBookshelf(Box<ChiseledBookshelf>),
}
/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`.
#[derive(Clone, Debug, PartialEq)]
pub struct ChiseledBookshelf {
pub items: [Option<ItemStack>; 6],
pub last_slot: i32,
}
impl Default for ChiseledBookshelf {
fn default() -> Self {
Self {
items: Default::default(),
last_slot: -1,
}
}
}
/// `TheEndGatewayBlockEntity`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -407,6 +423,9 @@ impl BlockEntity {
if name == "minecraft:campfire" || name == "minecraft:soul_campfire" {
return Some(Self::Campfire(Box::default()));
}
if name == "minecraft:chiseled_bookshelf" {
return Some(Self::ChiseledBookshelf(Box::default()));
}
let size = match name {
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
n if n.ends_with("copper_chest") => 27,
@@ -447,6 +466,7 @@ impl BlockEntity {
Self::EndGateway(_) => "minecraft:end_gateway",
Self::DaylightDetector => "minecraft:daylight_detector",
Self::Campfire(_) => "minecraft:campfire",
Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -471,6 +491,7 @@ impl BlockEntity {
Self::Banner(_) => Vec::new(),
Self::Crafter(c) => c.items.iter().flatten().cloned().collect(),
Self::Campfire(c) => c.items.iter().flatten().cloned().collect(),
Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(),
}
}
pub fn slots(&self) -> &[Option<ItemStack>] {
@@ -488,6 +509,7 @@ impl BlockEntity {
| Self::Skull(_)
| Self::DaylightDetector => &[],
Self::Crafter(c) => &c.items,
Self::ChiseledBookshelf(b) => &b.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
@@ -513,6 +535,7 @@ impl BlockEntity {
| Self::Skull(_)
| Self::DaylightDetector => &mut [],
Self::Crafter(c) => &mut c.items,
Self::ChiseledBookshelf(b) => &mut b.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
| Self::TrialSpawner(_)
+16 -3
View File
@@ -105,9 +105,13 @@ impl Report {
}
}
/// The release this binary is (`v0.2.3`); for a release from before 0.2, its tag and the client's
/// crate version; for a build from source, that version alone.
/// The release this binary is (`v0.2.3`); a nightly's label (`Nightly 2026-10-28 · 0c02067`); for a
/// release from before 0.2, its tag and the client's crate version; for a build from source, that
/// version alone.
pub fn version() -> String {
if let Some(label) = horizon_core::release::nightly_label() {
return label;
}
let version = env!("CARGO_PKG_VERSION");
match (horizon_core::release::RELEASE, release_tag()) {
(Some(_), Some(tag)) => tag,
@@ -117,8 +121,12 @@ pub fn version() -> String {
}
/// The release this binary came with: the version release.yml built in (docs/versioning.md), else
/// the folder the launcher installed it in, named after the tag (releases from before 0.2).
/// the folder the launcher installed it in, named after the tag (releases from before 0.2). A
/// nightly is its version as the launcher installs it (`nightly-2026-10-28-0c02067`).
pub fn release_tag() -> Option<String> {
if let Some(nightly) = horizon_core::release::nightly_version() {
return Some(nightly);
}
if let Some(version) = horizon_core::release::RELEASE {
return Some(format!("v{version}"));
}
@@ -525,6 +533,11 @@ mod tests {
#[test]
fn a_release_reports_its_built_in_version() {
// release.yml builds with HORIZON_VERSION (docs/versioning.md): `v0.2.3`, wherever it is installed.
if let Some(label) = horizon_core::release::nightly_label() {
assert_eq!(super::version(), label);
assert_eq!(release_tag(), horizon_core::release::nightly_version());
return;
}
match horizon_core::release::RELEASE {
Some(version) => {
assert_eq!(release_tag(), Some(format!("v{version}")));
+16
View File
@@ -771,9 +771,24 @@ pub struct ArmorStand {
pub name_visible: bool,
/// Game time of the last hit (the wobble and the second-hit window).
pub last_hit: i64,
/// `DATA_HEAD_POSE` to `DATA_RIGHT_LEG_POSE`: head, body, left arm, right
/// arm, left leg, right leg, in degrees (`POSE_KEYS` order).
pub pose: [[f32; 3]; 6],
}
impl ArmorStand {
pub const SLOTS: [&'static str; 6] = ["mainhand", "offhand", "feet", "legs", "chest", "head"];
/// The `Pose` compound's keys.
pub const POSE_KEYS: [&'static str; 6] =
["Head", "Body", "LeftArm", "RightArm", "LeftLeg", "RightLeg"];
/// `ArmorStand.DEFAULT_*_POSE`.
pub const DEFAULT_POSE: [[f32; 3]; 6] = [
[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0],
[-10.0, 0.0, -10.0],
[-15.0, 0.0, 10.0],
[-1.0, 0.0, -1.0],
[1.0, 0.0, 1.0],
];
pub fn new(id: u32, position: Vec3, yaw: f32) -> Self {
Self {
fire_ticks: 0,
@@ -792,6 +807,7 @@ impl ArmorStand {
custom_name: None,
name_visible: false,
last_hit: i64::MIN / 2,
pose: Self::DEFAULT_POSE,
}
}
pub fn environment_tick(
+39
View File
@@ -339,6 +339,18 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting)));
map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8));
}
"minecraft:panda" => {
use crate::mobs::panda::GENES;
for (key, gene) in [
("MainGene", m.extra.variant),
("HiddenGene", m.extra.variant2),
] {
map.insert(
key.into(),
string(GENES[usize::from(gene).min(GENES.len() - 1)]),
);
}
}
"minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => {
// Only Piglin.addAdditionalSaveData writes CannotHunt.
if id == "minecraft:piglin_brute" {
@@ -1094,6 +1106,11 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.color =
number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15);
}
if m.species() == crate::mobs::Species::Panda {
let gene = |key| text(tag.get(key)).map_or(0, |n| crate::mobs::panda::gene_from_name(&n));
m.extra.variant = gene("MainGene");
m.extra.variant2 = gene("HiddenGene");
}
if m.species() == crate::mobs::Species::Wolf {
let health = m.health;
m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner"));
@@ -1832,6 +1849,15 @@ pub fn armor_stand_to_nbt(a: &ArmorStand, uuid: [i32; 4], raw: Option<&Tag>) ->
}
put(&mut tag, "Health", Tag::Float(a.health.to_bits()));
put(&mut tag, "Fire", Tag::Short(a.fire_ticks as i16));
// ArmorStand.addAdditionalSaveData: the `Pose` parts that are not default.
let pose: Vec<(&str, Tag)> = ArmorStand::POSE_KEYS
.into_iter()
.zip(a.pose)
.zip(ArmorStand::DEFAULT_POSE)
.filter(|((_, rotation), default)| rotation != default)
.map(|((key, rotation), _)| (key, floats(&rotation)))
.collect();
put(&mut tag, "Pose", Tag::compound(pose));
// LivingEntity.addAdditionalSaveData and ArmorStand's own fields.
if let Tag::Compound(map) = &mut tag {
for (key, value) in [
@@ -1871,6 +1897,19 @@ pub fn armor_stand_from_nbt(tag: &Tag, id: u32) -> Option<ArmorStand> {
a.invisible = flag(tag, "Invisible");
a.marker = flag(tag, "Marker");
a.on_ground = flag(tag, "OnGround");
// ArmorStand.readAdditionalSaveData: each part of `Pose` that is a list of
// three numbers, the others staying at their defaults.
if let Some(pose) = tag.get("Pose") {
for (rotation, key) in a.pose.iter_mut().zip(ArmorStand::POSE_KEYS) {
if let Some(Tag::List(values)) = pose.get(key)
&& values.len() == 3
{
for (r, v) in rotation.iter_mut().zip(values) {
*r = float(Some(v)).unwrap_or(0.0) as f32;
}
}
}
}
Some(a)
}
/// A boat entity (`minecraft:<wood>_boat`, `minecraft:bamboo_chest_raft`...):
+199 -69
View File
@@ -22,7 +22,9 @@ mod bundles;
mod campfire;
mod campfire_douse;
mod cartography;
mod cat_spawner;
mod chat;
mod chiseled_bookshelf;
mod client_ambient;
mod clipboard;
mod combat;
@@ -34,6 +36,7 @@ mod consume;
mod control;
mod copper_golems;
mod creaking;
mod creative_hotbar;
mod creatures;
mod crossbow;
pub(crate) mod cushions;
@@ -128,9 +131,11 @@ mod packs;
mod pad;
mod pad_menu;
mod paintings;
mod pandas;
mod passengers;
mod persist;
mod perspective;
mod pick_entity;
mod pickups;
mod piglins;
mod piston_push;
@@ -741,7 +746,7 @@ impl LevelAccess for GameLevel<'_> {
&self,
pos: BlockPos,
state: BlockStateId,
_direction: Direction,
direction: Direction,
) -> i32 {
if let Some(s) = self.registry.state(state)
&& s.name == "minecraft:detector_rail"
@@ -774,6 +779,11 @@ impl LevelAccess for GameLevel<'_> {
if let Some(signal) = books::lectern_signal(self.world, pos) {
return signal;
}
if let Some(signal) =
machines::shelf_signal(self.world, self.registry, state, pos, direction)
{
return signal;
}
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
}
fn block_entity_signal(
@@ -1484,6 +1494,9 @@ struct Game<'a> {
armor: [Option<ItemStack>; 4],
/// The off hand (Inventory slot 40, saved as slot 150; menu slot 504 here).
offhand: Option<ItemStack>,
/// `ItemStack.popTime` of the nine hotbar stacks, then the off hand: set to 5
/// when a slot gains items, counted down each tick.
hotbar_pop: [u8; 10],
/// The hand an item use acts with (`InteractionHand`): the off hand only
/// for its turn in `use_item` and while its item is being used.
hand: Hand,
@@ -1538,6 +1551,8 @@ struct Game<'a> {
sleep_timer: u32,
dim: Dim,
world_root: PathBuf,
/// The world is superflat (`ServerLevel.isFlat`, for every dimension).
world_flat: bool,
/// A player carried through a portal, re-placed once the destination loads.
travelling: Option<(PlayerMotion, Vec3)>,
/// A server's players on their way to another level, each waiting for
@@ -3132,6 +3147,11 @@ impl Game<'_> {
pos,
data,
} => self.consume_teleport_particles([pos.x, pos.y, pos.z], data),
LevelEvent::LevelEvent {
id: 2018,
pos,
data,
} => self.enderman_teleport_particles([pos.x, pos.y, pos.z], data),
LevelEvent::LevelEvent { id: 2003, pos, .. } => {
self.eye_break_particles([pos.x, pos.y, pos.z]);
}
@@ -3881,6 +3901,20 @@ impl Game<'_> {
);
}
}
// IceBlock.playerDestroy: the ice melts back into water (the
// #prevents_ice_melting tool tag holds only silk touch).
let prevents_melting = held
.as_ref()
.is_some_and(|h| h.enchantment_level("minecraft:silk_touch") > 0);
self.with_level(|b, level, ticks| {
b.ice_destroyed_by_player(
level,
ticks,
BlockPos::new(pos[0], pos[1], pos[2]),
broken,
prevents_melting,
);
});
}
self.pending.clear(pos);
self.process_level_events()?;
@@ -3989,10 +4023,20 @@ impl Game<'_> {
self.swing_arm();
return Ok(true);
}
if self.use_golem_statue(hit.pos, held.as_ref()) {
self.swing_arm();
return Ok(true);
}
if self.use_jukebox(hit.pos, held.as_ref()) {
self.swing_arm();
return Ok(true);
}
if let Some(swings) = self.use_chiseled_bookshelf(hit, held.as_ref()) {
if swings {
self.swing_arm();
}
return Ok(true);
}
if self.use_composter(hit.pos, held.as_ref()) {
self.swing_arm();
return Ok(true);
@@ -4155,6 +4199,7 @@ impl Game<'_> {
|| self.place_minecart(hit, &stack)
|| self.place_painting(hit, &stack)
|| self.place_item_frame(hit, &stack)
|| self.use_lodestone_compass(hit, &stack)
|| self.place_armor_stand(hit, &stack)
|| self.place_cushion(hit, &stack)
|| self.place_end_crystal(hit, &stack))
@@ -4205,6 +4250,7 @@ impl Game<'_> {
return Ok(true);
};
let target = [pos.x, pos.y, pos.z];
let state = self.apply_item_block_state(target, state, &stack)?;
self.mod_block_event(target, state, true);
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
let key = (target[0], target[1], target[2]);
@@ -4889,15 +4935,13 @@ impl Game<'_> {
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet),
MotionEvent::Emission {
state, in_water, ..
} => {
MotionEvent::Emission { state, muffled, .. } => {
let sounds = self.res.facts().get(state).sounds.clone();
// Entity.playStepSound: the block's step sound at 0.15 volume,
// muffled under the swim sound in water. Whether it plays is
// Player.getMovementEmission's call (shift on the ground),
// not the pose: a forced crouch still steps.
let (volume, pitch) = if in_water {
let (volume, pitch) = if muffled {
(sounds.volume * 0.05, sounds.pitch * 0.8)
} else {
(sounds.volume * 0.15, sounds.pitch)
@@ -5125,6 +5169,7 @@ impl Game<'_> {
horizon_client::spans::time("tick_thunder", || self.tick_thunder());
horizon_client::spans::time("tick_lecterns", || self.tick_lecterns());
horizon_client::spans::time("tick_maps", || self.tick_maps());
self.tick_lodestone_compasses();
horizon_client::spans::time("tick_bolts", || self.tick_bolts());
horizon_client::spans::time("tick_fishing", || self.tick_fishing());
horizon_client::spans::time("tick_tridents", || self.tick_tridents());
@@ -5523,7 +5568,10 @@ impl Game<'_> {
let decorations = hud_overlays::ItemDecorations {
count: stack.count,
count_text,
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
// BundleItem overrides the bar with its fullness.
bar: horizon_client::bundle::Contents::of(self.res.items(), stack)
.map(|c| c.bar())
.unwrap_or_else(|| hud_overlays::damage_bar(stack.damage as i32, max_damage)),
cooldown: self.cooldowns.percent(&cooldown, partial),
};
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
@@ -5590,12 +5638,12 @@ impl Game<'_> {
// The ToastManager draws over every screen: a server's packs
// download while the connection screen shows.
if self.remote_overlay(&mut batch) {
self.draw_pack_toasts(&mut batch);
self.draw_pack_toasts(&mut batch, false);
return batch;
}
if let Some(reason) = self.loading_reason() {
self.draw_level_loading(&mut batch, reason);
self.draw_pack_toasts(&mut batch);
self.draw_pack_toasts(&mut batch, false);
return batch;
}
// Hud.extractRenderState: F1 (keyToggleGui) hides camera overlays, the
@@ -5604,6 +5652,9 @@ impl Game<'_> {
let spectator = self.spectator();
let (wi, hi) = (w as i32, h as i32);
let show_hud = !self.ui.hide_gui;
// max(Hud.leftHeight, Hud.rightHeight) after the bars: the item name and
// the action bar sit above it.
let mut bar_height = 39;
if show_hud {
self.draw_spyglass(&mut batch);
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
@@ -5625,12 +5676,17 @@ impl Game<'_> {
hud_layout::paint(&mut batch, &self.gui.atlas, &draws);
}
if !spectator {
let partial = self.clock.fraction() as f32;
let inputs = hud_layout::HotbarInputs {
selected: self.selected as i32,
right_handed: !self.settings.main_hand_left,
offhand: self.offhand.is_some(),
slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)),
offhand_pop: 0.0,
slots: std::array::from_fn(|i| {
self.inventory[i]
.as_ref()
.map(|_| (f32::from(self.hotbar_pop[i]) - partial).max(0.0))
}),
offhand_pop: (f32::from(self.hotbar_pop[9]) - partial).max(0.0),
attack: (indicator == 2).then_some(strength),
};
let draws = hud_layout::hotbar(wi, hi, &inputs);
@@ -5677,6 +5733,8 @@ impl Game<'_> {
contextual == ContextualBar::JumpableVehicle,
)
};
// Without the survival bars only the mount's hearts raise it.
bar_height = 39 + 10 * ((vehicle_hearts + 9) / 10);
if contextual == ContextualBar::Locator {
let (sprite, [x, y, w, h]) = horizon_client::locator_bar::background(wi, hi);
horizon_client::ui::nine_slice(
@@ -5715,17 +5773,9 @@ impl Game<'_> {
} else {
hud_layout::HeartKind::Normal
};
let eye = p.position.y + f64::from(p.dimensions.eye_height);
let under_water = self
.res
.facts()
.get(self.world.block(
p.position.x.floor() as i32,
eye.floor() as i32,
p.position.z.floor() as i32,
))
.fluid
== horizon_client::blocks::Fluid::Water;
// Hud.extractAirBubbles: `isEyeInFluidMatching`, so the eyes are below
// the surface, not merely in the water block.
let under_water = p.is_eye_in_fluid(horizon_client::motion::WATER);
let inputs = hud_layout::HealthInputs {
tick: self.ticks as i32,
millis: self.started.elapsed().as_millis() as i64,
@@ -5750,20 +5800,24 @@ impl Game<'_> {
};
let draws = self.health_hud.layout(&inputs, wi, hi);
hud_layout::paint(&mut batch, atlas, &draws);
bar_height = self
.health_hud
.left_height
.max(self.health_hud.right_height);
}
if contextual == ContextualBar::Locator {
let draws = self.locator_bar_draws(wi, hi);
hud_layout::paint(&mut batch, &self.gui.atlas, &draws);
}
if !spectator {
self.draw_selected_name(&mut batch, !self.creative);
self.draw_selected_name(&mut batch, bar_height, !self.creative);
}
}
// Hud.extractSleepOverlay: over all health/food bars, under titles and chat.
let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32);
hud_layout::paint(&mut batch, &self.gui.atlas, &draws);
if show_hud {
self.draw_titles(&mut batch);
self.draw_titles(&mut batch, bar_height);
self.draw_scoreboard(&mut batch);
self.draw_subtitles(&mut batch);
}
@@ -5817,8 +5871,9 @@ impl Game<'_> {
Screen::Playing | Screen::Options | Screen::Win => {}
}
self.draw_saving_indicator(&mut batch);
self.draw_toasts(&mut batch);
self.draw_pack_toasts(&mut batch);
// ToastManager.extractRenderState: F1 hides the toasts too.
self.draw_toasts(&mut batch, !show_hud);
self.draw_pack_toasts(&mut batch, !show_hud);
self.remote_hud(&mut batch);
self.draw_sign_editor(&mut batch);
self.draw_book(&mut batch);
@@ -5876,7 +5931,8 @@ impl Game<'_> {
| BlockEntity::EndGateway(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
| BlockEntity::Campfire(_)
| BlockEntity::ChiseledBookshelf(_),
) => {}
None => {
v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i));
@@ -6149,7 +6205,8 @@ impl Game<'_> {
| BlockEntity::EndGateway(_)
| BlockEntity::Skull(_)
| BlockEntity::DaylightDetector
| BlockEntity::Campfire(_),
| BlockEntity::Campfire(_)
| BlockEntity::ChiseledBookshelf(_),
) => {}
None if self.mount_active() => self.draw_mount_background(batch, ox, oy),
None => {
@@ -8462,24 +8519,34 @@ impl Game<'_> {
}
/// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle.
/// Returns the sun and moon quads, and the stars' frame and brightness
/// (the renderer keeps their geometry, built once).
/// (the renderer keeps their geometry, built once). The bodies fade with
/// the rain (`rainBrightness = 1 - rainLevel`, their colour's alpha).
fn celestial_geometry(
&self,
sky: &horizon_client::environment::Sky,
rain: f32,
) -> (Vec<Vertex>, Option<(glam::Mat4, f32)>) {
let body_color =
0x00FF_FFFF | (((1.0 - rain).clamp(0.0, 1.0) * 255.0).round() as u32) << 24;
let mut out = Vec::new();
let atlas = &self.gui.atlas;
let frame = |angle: f32| {
glam::Mat4::from_rotation_y((-90.0f32).to_radians())
* glam::Mat4::from_rotation_x(angle.to_radians())
};
let mut body = |name: &str, angle: f32, size: f32, color: u32| {
let mut body = |name: &str, angle: f32, size: f32, moon: bool| {
let Some(r) = atlas.sprites.get(name).copied() else {
return;
};
let m = frame(angle);
let corners = [(-size, -size), (size, -size), (size, size), (-size, size)];
let uv = [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]];
// buildCelestialQuad (sun) vs buildMoonPhases: the moon's UVs run
// the other way round.
let uv = if moon {
[[r.u1, r.v1], [r.u0, r.v1], [r.u0, r.v0], [r.u1, r.v0]]
} else {
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]]
};
for ((x, z), uv) in corners.iter().zip(uv) {
let p = m.transform_point3(glam::Vec3::new(*x, 100.0, *z));
out.push(Vertex {
@@ -8487,19 +8554,14 @@ impl Game<'_> {
pos: p.to_array(),
uv,
layer: 2,
color,
color: body_color,
light: 0,
glint_uv: [0.0, 0.0],
});
}
};
body(
"environment/celestial/sun",
sky.sun_angle,
30.0,
0xFFFF_FFFF,
);
body("environment/celestial/sun", sky.sun_angle, 30.0, false);
let phases = [
"full_moon",
"waning_gibbous",
@@ -8515,7 +8577,7 @@ impl Game<'_> {
&format!("environment/celestial/moon/{phase}"),
sky.moon_angle,
20.0,
0xFFFF_FFFF,
true,
);
// SkyRenderer.renderStars: the static star buffer on the same frame.
let stars =
@@ -8672,6 +8734,7 @@ impl Game<'_> {
book.to_be_displayed.retain(|r| index.contains(r));
self.dim = dim;
self.world_root = save_root.clone();
self.world_flat = horizon_client::save::WorldGen::read(&save_root).is_some_and(|w| w.flat);
self.block_ticks = Ticks::new(self.level.seed as i32);
self.tick_chunks.clear();
self.clear_entities();
@@ -8690,6 +8753,7 @@ impl Game<'_> {
self.spawn_spiral = Default::default();
self.player_spawn = None;
self.creatures.reset_trader();
self.creatures.cat_tick = 0;
self.portals = Default::default();
self.experience = Experience {
level: self.level.xp_level,
@@ -10448,11 +10512,29 @@ impl Game<'_> {
rain.extend(snow_vertices);
rain
}
/// A translated message for the player the game acts for: `overlay` is
/// `sendOverlayMessage` (the action bar), else `sendSystemMessage` (chat).
/// A guest gets a packet, so its own client translates it.
fn tell_sleeper(&mut self, key: &str, fallback: &str, overlay: bool) {
if self.lan_acting.is_some() {
self.guest_packets
.push(horizon_protocol::packets::play::Clientbound::SystemChat(
horizon_protocol::packets::play::SystemChat {
content: horizon_protocol::text::translatable(key, &[]),
overlay,
},
));
} else if overlay {
self.message = Some((self.translate(key, fallback), Instant::now()));
} else {
self.system_message(horizon_client::text::Text::translate(key, &[]));
}
}
/// ServerPlayer.startSleepInBed: in reach, not obstructed, night or thunder,
/// and (outside creative) no monsters within 8 blocks; the bed becomes the
/// respawn point either way.
fn try_sleep(&mut self, pos: [i32; 3]) {
let Some(p) = self.player.as_ref() else {
let Some((position, yaw)) = self.player.as_ref().map(|p| (p.position, p.yaw)) else {
return;
};
let time = self.world.day_time.rem_euclid(24000);
@@ -10475,15 +10557,16 @@ impl Game<'_> {
// ServerPlayer.bedInRange / isReachableBedBlock: within 3 blocks
// sideways and 2 vertically of the head or the foot.
let reachable = |bed: [i32; 3]| {
(p.position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0
&& (p.position.y - f64::from(bed[1])).abs() <= 2.0
&& (p.position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0
(position.x - f64::from(bed[0]) - 0.5).abs() <= 3.0
&& (position.y - f64::from(bed[1])).abs() <= 2.0
&& (position.z - f64::from(bed[2]) - 0.5).abs() <= 3.0
};
if !reachable(head) && !reachable(foot) {
self.message = Some((
"You may not rest now; the bed is too far away".into(),
Instant::now(),
));
self.tell_sleeper(
"block.minecraft.bed.too_far_away",
"You may not rest now; the bed is too far away",
true,
);
return;
}
// ServerPlayer.bedBlocked: Player.freeAt (not suffocating) for the
@@ -10496,7 +10579,11 @@ impl Game<'_> {
f.full_collision && f.solid_render
});
if blocked {
self.message = Some(("This bed is obstructed".into(), Instant::now()));
self.tell_sleeper(
"block.minecraft.bed.obstructed",
"This bed is obstructed",
true,
);
return;
}
// In reach (bedInRange), day or night: setRespawnPosition(
@@ -10505,9 +10592,16 @@ impl Game<'_> {
// and finds where to stand up (findRespawnAndUseSpawnBlock).
// Straw beds never set it (`straw_bed_rule`).
if self.bed_sets_spawn(state) {
self.respawn_config = Some(respawn_anchor::RespawnConfig::wrapped(
self.dim, head, p.yaw, false,
));
let config = respawn_anchor::RespawnConfig::wrapped(self.dim, head, yaw, false);
// ServerPlayer.setRespawnPosition: the chat message only when the
// point moved (`isSamePosition`).
let moved = self
.respawn_config
.is_none_or(|c| (c.dim, c.pos) != (config.dim, config.pos));
self.respawn_config = Some(config);
if moved {
self.tell_sleeper("block.minecraft.set_spawn", "Respawn point set", false);
}
// The fallback becomes the world spawn: a guest's is none of its
// own, so it follows `setworldspawn`.
self.spawn = if self.lan_acting.is_some() {
@@ -10522,10 +10616,11 @@ impl Game<'_> {
};
}
if !night {
self.message = Some((
"You can sleep only at night or during thunderstorms".into(),
Instant::now(),
));
self.tell_sleeper(
"block.minecraft.bed.no_sleep",
"You can sleep only at night or during thunderstorms",
true,
);
return;
}
// Creative players skip the monster check (`!this.isCreative()`).
@@ -10533,18 +10628,26 @@ impl Game<'_> {
&& self.mobs.iter().any(|m| {
m.hostile()
&& m.alive()
&& (m.position.x - p.position.x).abs() < 8.0
&& (m.position.y - p.position.y).abs() < 5.0
&& (m.position.z - p.position.z).abs() < 8.0
&& (m.position.x - position.x).abs() < 8.0
&& (m.position.y - position.y).abs() < 5.0
&& (m.position.z - position.z).abs() < 8.0
});
if monsters {
self.message = Some((
"You may not rest now; there are monsters nearby".into(),
Instant::now(),
));
self.tell_sleeper(
"block.minecraft.bed.not_safe",
"You may not rest now; there are monsters nearby",
true,
);
return;
}
self.message = Some(("Respawn point set".into(), Instant::now()));
// ServerPlayer.startSleepInBed: a percentage above 100 cannot skip the night.
if self.ui.rules.int("players_sleeping_percentage") > 100 {
self.tell_sleeper(
"sleep.not_possible",
"No amount of rest can pass this night",
true,
);
}
self.stop_mining();
self.left = false;
self.right = false;
@@ -10567,7 +10670,9 @@ impl Game<'_> {
fn tick_sleep(&mut self) {
self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
if let Some(head) = self.sleeping {
if self.keys.contains(&KeyCode::ShiftLeft)
// Vanilla has no Shift wake-up: the chat screen's capitals must
// not get the sleeper up.
if (self.screen != Screen::Chat && self.keys.contains(&KeyCode::ShiftLeft))
|| self
.player
.as_ref()
@@ -11174,8 +11279,11 @@ impl Game<'_> {
horizon_client::environment::apply_weather(&mut sky, rain, thunder);
self.end_flash_sky(&mut sky, alpha);
if self.flash > 0 && !self.settings.file.bool("hideLightningFlashes") {
// Lightning flash brightens the sky (LevelRenderer skyFlashTime).
sky.sky_color = [0.9, 0.9, 1.0];
// ClientLevel's flash layer while skyFlashTime > 0: the sky colour
// moves 22% of the way to (0.8, 0.8, 1.0).
let flash = [0.8, 0.8, 1.0];
sky.sky_color =
std::array::from_fn(|i| sky.sky_color[i] + (flash[i] - sky.sky_color[i]) * 0.22);
sky.sky_light_factor = 1.0;
}
// FishingHookRenderer's line, then DebugRenderer: chunk borders and
@@ -11314,7 +11422,7 @@ impl Game<'_> {
&& self.potions.effects.get("blindness").is_none()
{
// Camera.doesMobEffectBlockSky: no sun, moon or stars.
self.celestial_geometry(&sky)
self.celestial_geometry(&sky, rain)
} else if self.dim == Dim::End && self.settings.horizon.sky {
(self.end_flash_geometry(), None)
} else {
@@ -11740,7 +11848,7 @@ impl Game<'_> {
| KeyCode::Digit9
if self.screen == Screen::Playing =>
{
self.selected = match key {
let slot = match key {
KeyCode::Digit1 => 0,
KeyCode::Digit2 => 1,
KeyCode::Digit3 => 2,
@@ -11751,6 +11859,15 @@ impl Game<'_> {
KeyCode::Digit8 => 7,
_ => 8,
};
// Minecraft.handleKeybinds: a creative player holding the load
// or save toolbar key loads or saves a toolbar instead (load
// first when both are held).
let load = self.mapped_key_down("key.loadToolbarActivator");
if self.creative && (load || self.mapped_key_down("key.saveToolbarActivator")) {
self.hotbar_load_or_save(slot, load);
} else {
self.selected = slot;
}
}
_ => {}
}
@@ -11793,7 +11910,18 @@ impl Game<'_> {
// Minecraft.pickBlockOrEntity -> the server's handlePickItemFromBlock:
// the block's clone item, with its block entity's data on Ctrl in
// creative, picked from the inventory (`pick_item`).
if let Some(hit) = self.pick() {
if let Some(entity) = self.pick_entity_hit() {
// handlePickItemFromEntity: the entity's pick result.
if let Some(stack) = entity.and_then(|id| self.entity_pick_result(id)) {
let infinite = self.creative;
horizon_client::pick_item::pick(
&mut self.inventory[..36],
&mut self.selected,
&stack,
infinite,
);
}
} else if let Some(hit) = self.pick() {
let include_data = self.creative && self.has_control_down();
if let Some(stack) = self.picked_stack(hit.pos, include_data) {
let infinite = self.creative;
@@ -13276,6 +13404,7 @@ impl<'a> Game<'a> {
title: None,
armor: [None, None, None, None],
offhand: None,
hotbar_pop: [0; 10],
hand: Hand::Main,
shield_cooldown: 0,
cooldowns: Default::default(),
@@ -13308,6 +13437,7 @@ impl<'a> Game<'a> {
sleep_timer: 0,
dim: Dim::Overworld,
world_root: PathBuf::new(),
world_flat: false,
travelling: None,
server_trips: Vec::new(),
level_teleports: Vec::new(),
@@ -13448,7 +13578,7 @@ impl<'a> Game<'a> {
admin_feedback: Vec::new(),
console_broadcast: None,
cmds: Default::default(),
ui: Default::default(),
ui: chat::UiState::new(),
combat: Default::default(),
guest_combat: Default::default(),
mount: Default::default(),
+117 -35
View File
@@ -22,6 +22,9 @@ pub(super) struct Toast {
frame: Frame,
title: Text,
slide: Slide,
/// `ToastInstance.firstSlotIndex`: the 32-pixel slot it stacks in once it
/// leaves the queue.
slot: Option<usize>,
/// A `RecipeToast`: the crafting station and result of each display
/// unlocked while it lasts (`recipeItems`); empty for an advancement.
recipes: Vec<(String, ItemStack)>,
@@ -37,6 +40,7 @@ impl Toast {
frame: Frame::Task,
title: Text::literal(""),
slide: Slide::default(),
slot: None,
recipes: items,
changed: true,
last_changed: 0,
@@ -535,6 +539,7 @@ impl Game<'_> {
frame: d.frame,
title: text_of(&d.title),
slide: Slide::default(),
slot: None,
recipes: Vec::new(),
changed: false,
last_changed: 0,
@@ -714,6 +719,19 @@ impl Game<'_> {
adv::conditions(&c["player"], &pctx, w) && adv::conditions(&c[&key], &ectx, w)
});
}
/// `KilledByArrowTrigger`: what the arrow killed and the weapon it came from.
pub(super) fn trigger_killed_by_arrow(
&mut self,
victims: &[EntityView],
weapon: Option<&ItemStack>,
) {
let me = self.player_entity();
let victims = victims.to_vec();
let weapon = weapon.map(item_view);
self.trigger("minecraft:killed_by_arrow", move |c, w| {
adv::killed_by_arrow(c, &me, &victims, weapon.as_ref(), w)
});
}
/// `LevitationTrigger`: how far the player rose from where it started
/// levitating, and for how long.
fn trigger_levitation(&mut self, start: [f64; 3], duration: i64) {
@@ -858,6 +876,22 @@ impl Game<'_> {
let it = item_view(stack);
self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w));
}
/// `EnchantedItemTrigger`: the enchanted item and the levels it cost.
pub(super) fn trigger_enchanted_item(&mut self, stack: &ItemStack, levels: i32) {
let me = self.player_entity();
let it = item_view(stack);
self.trigger("minecraft:enchanted_item", move |c, w| {
let pctx = adv::Entities {
this: Some(&me),
origin: me.position,
tool: None,
block_pos: None,
};
adv::conditions(&c["player"], &pctx, w)
&& adv::item(&c["item"], &it, w)
&& adv::range_i(&c["levels"], i64::from(levels))
});
}
/// `BrewedPotionTrigger`: the potion contents of a stack taken from a
/// brewing stand.
pub(super) fn trigger_brewed_potion(&mut self, stack: &ItemStack) {
@@ -1022,58 +1056,105 @@ impl Game<'_> {
c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to)
});
}
/// `ToastManager` with the `AdvancementToast` and the `RecipeToast`,
/// one at a time.
pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) {
/// `ToastManager.SLOT_COUNT`.
pub(super) const TOAST_SLOTS: usize = 5;
/// `ToastManager.update` and `extractRenderState` for the `AdvancementToast`s and
/// `RecipeToast`s: up to five stack in 32-pixel slots, the rest queue. `hidden` (F1)
/// keeps them timing out without drawing them.
pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch, hidden: bool) {
let multiplier = f64::from(self.settings.notification_display_time);
let Some(t) = self.adv.toasts.front_mut() else {
return;
};
let first = t.slide.origin.is_none();
let origin = *t.slide.origin.get_or_insert_with(Instant::now);
let now = origin.elapsed().as_millis() as i64;
let mut slide = std::mem::take(&mut t.slide);
let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier));
t.slide = slide;
if finished {
self.adv.toasts.pop_front();
let mut sound_played = false;
let mut i = 0;
while i < self.adv.toasts.len() {
let t = &mut self.adv.toasts[i];
if t.slot.is_none() {
i += 1;
continue;
}
let origin = *t.slide.origin.get_or_insert_with(Instant::now);
let now = origin.elapsed().as_millis() as i64;
let mut slide = std::mem::take(&mut t.slide);
let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier));
t.slide = slide;
if finished {
self.adv.toasts.remove(i);
continue;
}
// Only the first visibility change of an update plays its sound.
if let Some(show) = sound
&& !std::mem::replace(&mut sound_played, true)
{
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
self.audio
.play(&format!("minecraft:{event}"), None, 1.0, 1.0);
}
i += 1;
}
// The queued toasts take the free slots in order; a challenge's own sound
// plays once as it leaves the queue.
let mut used = self.toast_slots_used();
let mut challenge_sound = false;
for t in &mut self.adv.toasts {
if t.slot.is_some() {
continue;
}
let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else {
break;
};
used |= 1 << slot;
t.slot = Some(slot);
challenge_sound |= !t.is_recipe() && t.frame == Frame::Challenge;
}
if challenge_sound {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
if hidden {
return;
}
for i in 0..self.adv.toasts.len() {
if let Some(slot) = self.adv.toasts[i].slot {
self.draw_toast(batch, i, 32.0 * slot as f32, multiplier);
}
}
}
/// The slots held by shown advancement, recipe and pack toasts, as bits.
pub(super) fn toast_slots_used(&self) -> u32 {
let packs = self.server_packs.toast_slots();
self.adv
.toasts
.iter()
.filter_map(|t| t.slot)
.chain(packs)
.fold(0, |used, slot| used | 1 << slot)
}
/// The `AdvancementToast` or `RecipeToast` at `index` in its slot at `y`.
fn draw_toast(&mut self, batch: &mut HudBatch, index: usize, y: f32, multiplier: f64) {
let t = &self.adv.toasts[index];
let x = batch.width - 160.0 * t.slide.portion;
let fully_for = t.slide.fully_for;
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
let recipe = t
.is_recipe()
.then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone());
// ToastManager.update: the sound of the new visibility, and a
// challenge's own sound as it leaves the queue.
if let Some(show) = sound {
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
self.audio
.play(&format!("minecraft:{event}"), None, 1.0, 1.0);
}
if first && recipe.is_none() && frame == Frame::Challenge {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
batch.sprite(atlas, "gui/sprites/toast/recipe", x, y);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.gui.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
batch.text(atlas, &title, x + 30.0, y + 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, y + 18.0, 0xFF00_0000, false);
let start = batch.vertices.len();
self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0);
batch.scale_since(start, x, 0.0, 0.6, 0.6);
self.draw_item_model(batch, &item, x + 8.0, 8.0);
self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, y + 3.0);
batch.scale_since(start, x, y, 0.6, 0.6);
self.draw_item_model(batch, &item, x + 8.0, y + 8.0);
return;
}
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
batch.sprite(atlas, "gui/sprites/toast/advancement", x, y);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
Frame::Goal => ("advancements.toast.goal", 0xFF00_FFFF),
@@ -1083,12 +1164,12 @@ impl Game<'_> {
atlas,
&Text::translate(key, &[]),
x + 30.0,
7.0,
y + 7.0,
color,
false,
);
batch.text_styled(atlas, &title, x + 30.0, 18.0, u32::MAX, false);
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
batch.text_styled(atlas, &title, x + 30.0, y + 18.0, u32::MAX, false);
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, y + 8.0);
}
}
/// `Advancement.name`: the bracketed title in the frame's colour, with the
@@ -1269,6 +1350,7 @@ impl Game<'_> {
frame: d.frame,
title: text_of(&d.title),
slide: Slide::default(),
slot: None,
recipes: Vec::new(),
changed: false,
last_changed: 0,
+32 -16
View File
@@ -627,21 +627,8 @@ impl Game<'_> {
* glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0));
let mut poses = Poses::new(model);
// ArmorStand.DEFAULT_*_POSE and ArmorStandModel part visibility.
let deg = |v: f32| v.to_radians();
for (name, rot) in [
("left_arm", [-10.0, 0.0, -10.0]),
("right_arm", [-15.0, 0.0, 10.0]),
("left_leg", [-1.0, 0.0, -1.0]),
("right_leg", [1.0, 0.0, 1.0]),
] {
if poses.has(name) {
let pose = poses.get(name);
pose[3] = deg(rot[0]);
pose[4] = deg(rot[1]);
pose[5] = deg(rot[2]);
}
}
// ArmorStandModel.setupAnim: the stand's pose and part visibility.
apply_pose(&mut poses, &a.pose);
// Item layers pose from the hidden arms too (`visible` only skips drawing).
let posed = poses.clone();
let mut hide = |name: &str| {
@@ -725,7 +712,9 @@ impl Game<'_> {
} else {
0
};
let layer_poses = Poses::new(part);
// ArmorStandArmorModel.setupAnim: the same pose as the stand.
let mut layer_poses = Poses::new(part);
apply_pose(&mut layer_poses, &a.pose);
horizon_client::mobs::render::draw(
part,
base,
@@ -757,6 +746,33 @@ impl Game<'_> {
}
}
}
/// The `Pose` rotations on the parts of an armor stand model or its armor
/// (`ArmorStandArmorModel.setupAnim`); the body also turns the sticks.
fn apply_pose(poses: &mut Poses, pose: &[[f32; 3]; 6]) {
let parts: [&[&str]; 6] = [
&["head"],
&[
"body",
"right_body_stick",
"left_body_stick",
"shoulder_stick",
],
&["left_arm"],
&["right_arm"],
&["left_leg"],
&["right_leg"],
];
for (names, rotation) in parts.into_iter().zip(pose) {
for name in names {
if poses.has(name) {
let part = poses.get(name);
part[3] = rotation[0].to_radians();
part[4] = rotation[1].to_radians();
part[5] = rotation[2].to_radians();
}
}
}
}
fn overlaps(a: Aabb, b: Aabb) -> bool {
let (a0, a1, b0, b1) = (
a.min_position(),
+42 -2
View File
@@ -4,9 +4,13 @@
//! placed item gives its block entity.
use super::Game;
use horizon_client::{
block_entity_item, block_entity_nbt, containers::BlockEntity, item_data, items::ItemStack, save,
Result, block_entity_item, block_entity_nbt, containers::BlockEntity, item_data,
items::ItemStack, save,
};
use horizon_world::{
nbt::{Compound, Tag},
registry::BlockStateId,
};
use horizon_world::nbt::{Compound, Tag};
/// The component patch of `stack`.
fn components(stack: &ItemStack) -> Compound {
@@ -77,6 +81,42 @@ impl Game<'_> {
Some(stack)
}
/// `BlockItem.updateBlockStateFromTag`: the properties of the item's
/// `block_state` component (a hive's honey level, a statue's pose) set on
/// the block just placed at `pos`. Returns the state it has now.
pub(super) fn apply_item_block_state(
&mut self,
pos: [i32; 3],
state: BlockStateId,
stack: &ItemStack,
) -> Result<BlockStateId> {
let Some(Tag::Compound(saved)) =
stack.data().and_then(|d| d.other("minecraft:block_state"))
else {
return Ok(state);
};
let Some(current) = self.pack.assets.registry.state(state) else {
return Ok(state);
};
// Only the properties the block has.
let props: Vec<(String, String)> = saved
.iter()
.filter_map(|(k, v)| match v {
Tag::String(v) => Some((k.to_string_lossy(), v.to_string_lossy())),
_ => None,
})
.filter(|(k, v)| current.properties.get(k).is_some_and(|old| old != v))
.collect();
let props: Vec<(&str, &str)> = props.iter().map(|(k, v)| (&**k, &**v)).collect();
match self.with_props(state, &props) {
Some(new) if !props.is_empty() && new != state => {
self.level_set(pos, new)?;
Ok(new)
}
_ => Ok(state),
}
}
/// `BlockItem.updateCustomBlockEntityTag` and `updateBlockEntityComponents`
/// for the block entity just placed at `pos` from `stack`; `game_master`:
/// the placer can use game master blocks (a dispenser can't).
+6 -1
View File
@@ -1144,7 +1144,12 @@ impl Game<'_> {
BLACK,
);
}
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", super::chat::PLAYER_NAME);
// BookSignScreen: `owner.getName()`, the account's name on a server.
let owner = self
.remote
.as_ref()
.map_or(super::chat::PLAYER_NAME, |r| r.profile_name.as_str());
let by = tr("book.byAuthor", "by %1$s").replace("%1$s", owner);
let tw = HudBatch::text_width(atlas, &by);
batch.text(
atlas,
@@ -0,0 +1,138 @@
//! `CatSpawner`: every 1200 ticks a cat may appear near a random player,
//! in a village with enough occupied beds or inside a swamp hut.
use super::{
Dim, Game,
raids::{section, sections_to_village},
};
use horizon_client::mobs::{Species, spawn_rules};
use horizon_core::{geometry::Vec3, random::RandomSource};
const TICK_DELAY: i32 = 1200;
impl Game<'_> {
/// `CatSpawner.tick` (the overworld's custom spawner).
pub(super) fn tick_cat_spawner(&mut self) {
if self.dim != Dim::Overworld {
return;
}
self.creatures.cat_tick -= 1;
if self.creatures.cat_tick > 0 {
return;
}
self.creatures.cat_tick = TICK_DELAY;
// ServerLevel.getRandomPlayer: one of the living players.
let alive: Vec<Vec3> = self
.level_players()
.into_iter()
.filter(|p| p.alive)
.map(|p| p.position)
.collect();
if alive.is_empty() {
return;
}
let pick = self
.world
.random
.next_int_bound(alive.len() as i32)
.unwrap_or(0);
let p = alive[pick as usize];
let mut offset = || {
let n = 8 + self.world.random.next_int_bound(24).unwrap_or(0);
if self.world.random.next_boolean() {
-n
} else {
n
}
};
let x = offset();
let z = offset();
let pos = [
p.x.floor() as i32 + x,
p.y.floor() as i32,
p.z.floor() as i32 + z,
];
// hasChunksAt(pos +- 10)
let loaded = ((pos[0] - 10) >> 4..=(pos[0] + 10) >> 4).all(|cx| {
((pos[2] - 10) >> 4..=(pos[2] + 10) >> 4)
.all(|cz| self.world.chunks.contains_key(&(cx, cz)))
});
if !loaded {
return;
}
let ok = spawn_rules::is_spawn_position_ok(
Species::Cat,
&self.mob_world_base(&[]),
pos[0],
pos[1],
pos[2],
);
if !ok {
return;
}
if sections_to_village(&self.village_centers(), section(pos)) <= 2 {
self.spawn_cat_in_village(pos);
} else {
let hut = self.structure_tag("minecraft:cats_spawn_in");
if self.structures_at(pos).iter().any(|s| hut.contains(s)) {
self.spawn_cat_in_hut(pos);
}
}
}
/// `spawnInVillage`: more than four occupied beds within 48 blocks and
/// fewer than five cats around.
fn spawn_cat_in_village(&mut self, pos: [i32; 3]) {
// PoiManager.getCountInRange(HOME, IS_OCCUPIED): beds villagers have claimed.
let mut beds: Vec<[i32; 3]> = self
.mobs
.iter()
.filter(|m| m.species() == Species::Villager && m.alive())
.filter_map(|m| m.extra.bed)
.filter(|b| {
let d = |i: usize| i64::from(b[i] - pos[i]);
d(0).abs() <= 48
&& d(2).abs() <= 48
&& d(0).pow(2) + d(1).pow(2) + d(2).pow(2) <= 48 * 48
})
.collect();
beds.sort_unstable();
beds.dedup();
if beds.len() > 4 && self.cats_near(pos, 48.0) < 5 {
self.spawn_cat(pos, false);
}
}
/// `spawnInHut`: no cat within 16 blocks; the cat stays.
fn spawn_cat_in_hut(&mut self, pos: [i32; 3]) {
if self.cats_near(pos, 16.0) == 0 {
self.spawn_cat(pos, true);
}
}
/// Cats in `AABB(pos).inflate(radius, 8, radius)`.
fn cats_near(&self, pos: [i32; 3], radius: f64) -> usize {
let [x, y, z] = pos.map(f64::from);
let min = Vec3::new(x - radius, y - 8.0, z - radius);
let max = Vec3::new(x + 1.0 + radius, y + 9.0, z + 1.0 + radius);
self.mobs
.iter()
.filter(|m| {
m.species() == Species::Cat && m.alive() && m.bounds().intersects_corners(min, max)
})
.count()
}
/// `spawnCat`: finalized for a natural spawn, black inside
/// `#cats_spawn_as_black` structures (`Cat.finalizeSpawn`).
fn spawn_cat(&mut self, pos: [i32; 3], persistent: bool) {
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
let Some(id) = self.spawn_mob("minecraft:cat", at, persistent) else {
return;
};
let black = self.structure_tag("minecraft:cats_spawn_as_black");
let in_black = self.structures_at(pos).iter().any(|s| black.contains(s));
if in_black && let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.extra.variant = 10;
}
}
}
+90 -2
View File
@@ -81,6 +81,8 @@ pub struct UiState {
pub chat_screen: Option<ChatScreen>,
/// When the chat screen opened (its input took the focus: the cursor blink).
pub chat_opened: Option<std::time::Instant>,
/// The chat screen is `InBedChatScreen`: the sleeper's, with a Leave Bed button.
pub in_bed_chat: bool,
pub registries: Registries,
pub rules: GameRules,
pub clock: WorldClock,
@@ -106,6 +108,18 @@ pub struct UiState {
pub death_time: u32,
}
impl UiState {
/// The state a window starts with: the chat remembers the commands kept
/// in the game folder (`ChatComponent`'s constructor).
pub fn new() -> Self {
let mut ui = Self::default();
if let Ok(dir) = std::env::current_dir() {
ui.chat.load_history(&dir);
}
ui
}
}
impl Game<'_> {
/// `PlayerList.isOp` for the single-player owner: the world's Allow Commands.
pub(super) fn allow_commands(&self) -> bool {
@@ -440,6 +454,12 @@ impl Game<'_> {
self.capture(false);
}
pub(super) fn close_chat(&mut self) {
// InBedChatScreen.onClose: leaving the screen means getting up; the
// screen goes once the player has woken (`tick_in_bed_chat`).
if self.ui.in_bed_chat && self.sleeping.is_some() {
self.wake_up();
return;
}
self.ui.chat_screen = None;
self.ui.chat.reset_scroll();
if self.screen == Screen::Chat {
@@ -447,6 +467,35 @@ impl Game<'_> {
self.capture(true);
}
}
/// `Gui.tick`: a sleeper gets `InBedChatScreen`; when the player has
/// woken (`onPlayerWokeUp`) it closes, or turns into the plain chat
/// screen if something was typed.
pub(super) fn tick_in_bed_chat(&mut self) {
if self.screen != Screen::Chat {
self.ui.in_bed_chat = false;
}
if self.ui.in_bed_chat {
if self.sleeping.is_none() {
self.ui.in_bed_chat = false;
let text = self
.ui
.chat_screen
.as_ref()
.map_or_else(String::new, |s| s.value().to_owned());
self.close_chat();
if !text.is_empty() {
self.open_chat(&text);
}
}
} else if self.sleeping.is_some() && self.screen == Screen::Playing {
self.open_chat("");
self.ui.in_bed_chat = self.screen == Screen::Chat;
}
}
/// The Leave Bed button of `InBedChatScreen`: its bounds.
fn leave_bed_button(width: f32, height: f32) -> (i32, i32, i32, i32) {
(width as i32 / 2 - 100, height as i32 - 40, 200, 20)
}
/// `Minecraft.computeChatAbilities` from the Chat option.
pub(super) fn chat_abilities(&self) -> ChatAbilities {
ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility))
@@ -559,7 +608,15 @@ impl Game<'_> {
match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) {
ChatAction::Close => self.close_chat(),
ChatAction::Submit(message) => {
self.close_chat();
// InBedChatScreen sends without closing (`closeOnSubmit` is
// false): the box empties and the screen stays.
if self.ui.in_bed_chat && self.sleeping.is_some() {
screen.suggest_command(&m, &c, "");
self.ui.chat.reset_scroll();
self.ui.chat_screen = Some(screen);
} else {
self.close_chat();
}
if !message.is_empty() {
self.handle_chat_input(&message);
}
@@ -661,7 +718,8 @@ impl Game<'_> {
{
return;
}
let shift = self.keys.contains(&KeyCode::ShiftLeft);
// ChatScreen.mouseScrolled: `hasShiftDown`, either Shift key.
let shift = self.has_shift_down();
let amount = amount.clamp(-1.0, 1.0) * if shift { 1.0 } else { 7.0 };
self.ui.chat.scroll_by(amount as i32, true);
}
@@ -675,6 +733,16 @@ impl Game<'_> {
dispatcher: chat_tree(&self.remote, &self.mods),
registries: &self.ui.registries,
};
if self.ui.in_bed_chat && self.sleeping.is_some() {
let width = self.renderer.as_ref().map_or(1280.0, |r| {
HudBatch::new([r.config.width, r.config.height]).width
});
let (x, y, w, h) = Self::leave_bed_button(width, height);
if horizon_client::screen_draw::inside((cursor.0 as i32, cursor.1 as i32), x, y, w, h) {
self.wake_up();
return;
}
}
if let Some(screen) = self.ui.chat_screen.as_mut() {
if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) {
return;
@@ -803,6 +871,26 @@ impl Game<'_> {
let draws = screen.draw(&m, mouse, blink, background);
horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws);
self.ui.chat_screen = Some(screen);
if self.ui.in_bed_chat && self.sleeping.is_some() {
let (x, y, w, h) = Self::leave_bed_button(batch.width, batch.height);
let label = Text::literal(horizon_client::lang::get_or(
"multiplayer.stopSleeping",
"Leave Bed",
));
let mut button = Vec::new();
horizon_client::screen_draw::button(
&mut button,
&m,
&label,
x,
y,
w,
h,
true,
horizon_client::screen_draw::inside(mouse, x, y, w, h),
);
horizon_client::screen_draw::paint(batch, &self.gui.atlas, &button);
}
// The hovered message part's tooltip, one row per line of its text.
if let Some(hover) = self.ui.chat.hover_at(
&self.gui.atlas.font,
@@ -0,0 +1,178 @@
//! Chiseled bookshelves: `ChiseledBookShelfBlock.useItemOn` / `useWithoutItem`
//! (a book into the slot under the crosshair, or out of it) and
//! `ChiseledBookShelfBlockEntity.updateState`, which also follows the books a
//! hopper or dropper moved (`machines::container_changed`). The slots' books
//! show through the block state's `slot_N_occupied`, which reaches a server's
//! clients with the block update.
use super::{Game, Hit, machines::dir_from_name};
use horizon_client::{containers::BlockEntity, items::ItemStack, mobs::Who};
use horizon_core::{
geometry::{Direction, Vec3},
position::BlockPos,
};
use horizon_world::level::{flags, hit_slot};
const BLOCK: &str = "minecraft:chiseled_bookshelf";
impl Game<'_> {
/// `useItemOn` with `held` in the acting hand, then `useWithoutItem` on
/// the main hand's turn: None when the block passes the click, else
/// whether the use succeeded and the arm swings (a click on an empty slot
/// without a book only consumes it).
pub(super) fn use_chiseled_bookshelf(
&mut self,
hit: &Hit,
held: Option<&ItemStack>,
) -> Option<bool> {
let pos = hit.pos;
let state = self.world.block(pos[0], pos[1], pos[2]);
let info = self
.pack
.assets
.registry
.state(state)
.filter(|s| s.name == BLOCK)?;
let facing = info
.properties
.get("facing")
.and_then(|f| dir_from_name(f))?;
let face = Direction::ALL
.into_iter()
.find(|d| d.normal() == hit.face)?;
let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
let slot = hit_slot(
facing,
face,
BlockPos::new(pos[0], pos[1], pos[2]),
at,
2,
3,
)?;
let occupied = info
.properties
.get(&format!("slot_{slot}_occupied"))
.map(String::as_str)
== Some("true");
let book = held.filter(|s| {
self.res
.items()
.item_tags
.get("minecraft:bookshelf_books")
.is_some_and(|m| m.contains(&*s.item))
});
let centre = pos.map(|v| f64::from(v) + 0.5);
if let Some(book) = book
&& !occupied
{
// addBook: one book goes in (a creative player keeps theirs).
let book = book.clone();
self.stats.add("used", &book.item, 1);
let sound = if &*book.item == "minecraft:enchanted_book" {
"minecraft:block.chiseled_bookshelf.insert.enchanted"
} else {
"minecraft:block.chiseled_bookshelf.insert"
};
self.bookshelf_items(pos)?[slot] = Some(ItemStack {
count: 1,
..book.clone()
});
self.consume_held();
self.chiseled_bookshelf_update_state(pos, slot);
self.audio.play(sound, Some(centre), 1.0, 1.0);
self.trigger_block("minecraft:item_used_on_block", pos, &book);
return Some(true);
}
// TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem.
if self.hand != horizon_client::first_person::Hand::Main {
return None;
}
if !occupied {
return Some(false);
}
// removeBook: the book goes to the inventory, or is dropped.
let retrieved = self.bookshelf_items(pos)?[slot].take()?;
self.chiseled_bookshelf_update_state(pos, slot);
let sound = if &*retrieved.item == "minecraft:enchanted_book" {
"minecraft:block.chiseled_bookshelf.pickup.enchanted"
} else {
"minecraft:block.chiseled_bookshelf.pickup"
};
self.audio.play(sound, Some(centre), 1.0, 1.0);
self.give_or_drop(retrieved);
self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None);
Some(true)
}
/// The bookshelf's six slots (made if the block has no block entity yet).
fn bookshelf_items(&mut self, pos: [i32; 3]) -> Option<&mut [Option<ItemStack>; 6]> {
let entity = self
.world
.block_entities
.get_or_insert_with((pos[0], pos[1], pos[2]), || {
BlockEntity::ChiseledBookshelf(Box::default())
});
match entity {
BlockEntity::ChiseledBookshelf(b) => Some(&mut b.items),
_ => None,
}
}
/// `ChiseledBookShelfBlockEntity.updateState`: `slot` becomes the last
/// one touched, the block state takes the slots' occupancy
/// (`setBlockAndUpdate`) and `BLOCK_CHANGE` goes out.
fn chiseled_bookshelf_update_state(&mut self, pos: [i32; 3], slot: usize) {
let key = (pos[0], pos[1], pos[2]);
let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get_mut(&key)
else {
return;
};
b.last_slot = slot as i32;
let occupied: Vec<bool> = b.items.iter().map(Option::is_some).collect();
let registry = self.pack.assets.registry;
let Some(mut state) = registry
.state(self.world.block(pos[0], pos[1], pos[2]))
.cloned()
else {
return;
};
for (i, occupied) in occupied.into_iter().enumerate() {
state
.properties
.insert(format!("slot_{i}_occupied"), occupied.to_string());
}
let Some(new) = registry.id(&state) else {
return;
};
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, at, new, flags::UPDATE_ALL));
self.world.modified.insert((pos[0] >> 4, pos[2] >> 4));
self.post_block_game_event("minecraft:block_change", pos, None, Some(new));
}
/// The books a hopper or dropper put in or took out: the slot whose
/// occupancy no longer matches the block state is the one `setItem` or
/// `removeItem` updated.
pub(super) fn chiseled_bookshelf_synced(&mut self, pos: (i32, i32, i32)) {
let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get(&pos) else {
return;
};
let Some(info) = self
.pack
.assets
.registry
.state(self.world.block(pos.0, pos.1, pos.2))
else {
return;
};
let moved = (0..6).rev().find(|i| {
let shown = info
.properties
.get(&format!("slot_{i}_occupied"))
.map(String::as_str);
b.items[*i].is_some() != (shown == Some("true"))
});
if let Some(slot) = moved {
self.chiseled_bookshelf_update_state([pos.0, pos.1, pos.2], slot);
}
}
}
@@ -17,8 +17,10 @@ impl Game<'_> {
return;
}
let mut events = Vec::new();
let random = self.particles.level_random();
for m in self.mobs.iter_mut().filter(|m| !m.removed) {
ambient::client_ai_step(m, &mut events);
ambient::client_particles(m, random, &mut events);
}
for event in events {
match event {
@@ -37,6 +39,7 @@ impl Game<'_> {
}
}
self.eye_particles();
self.panda_effects();
self.sprint_dust();
self.effect_swirls();
}
+4
View File
@@ -42,6 +42,10 @@ pub(super) struct CombatTracker {
/// The projectile hitting the player now is another player's that
/// `ServerPlayer.canHarmPlayer` refuses (the `pvp` rule, an ally).
pub(super) refuse_player_hit: bool,
/// The player whose melee hit is landing on the player now: where they
/// stand and the seconds their weapon disables a shield for
/// (`getSecondsToDisableBlocking`).
pub(super) player_attacker: Option<([f64; 3], f32)>,
/// The mob exploding now (`ServerExplosion.source`): its team's friendly
/// fire decides whom the blast may hurt.
pub(super) explosion_source: Option<u32>,
+105 -69
View File
@@ -2210,7 +2210,8 @@ impl Game<'_> {
let dmax = [dest[0] + size[0], dest[1] + size[1], dest[2] + size[2]];
let overlap = (0..3).all(|i| dest[i] <= max[i] && dmax[i] >= min[i]);
let moving = ctx.has("move");
if !ctx.has("force") && overlap {
// Mode.canOverlap: only the normal mode refuses overlapping regions.
if !ctx.has("force") && !moving && overlap {
return Err(err("commands.clone.overlap", &[]));
}
let area = (0..3).map(|i| i64::from(size[i] + 1)).product::<i64>();
@@ -2419,26 +2420,54 @@ impl Game<'_> {
let levels = ctx.has("levels");
let unit = if levels { "levels" } else { "points" };
if ctx.has("query") {
let _ = self.entities(ctx, "target", true)?;
let e = &self.experience;
let value = if levels {
e.level
} else {
(e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32
};
let target = self.entities(ctx, "target", true)?[0];
// ExperienceCommand.queryExperience: the target's own level or points.
let value = self
.for_player(target, |g| {
let e = &g.experience;
if levels {
e.level
} else {
(e.progress * horizon_client::entities::Experience::needed(e.level) as f32)
as i32
}
})
.unwrap_or(0);
self.system_message(Text::translate(
&format!("commands.experience.query.{unit}"),
&[
Text::literal(self.acting_player_name()),
Text::literal(value.to_string()),
],
&[self.target_name(target), Text::literal(value.to_string())],
));
return Ok(value);
}
let targets = self.entities(ctx, "target", true)?;
let amount = Self::int(ctx, "amount").unwrap_or(0);
let op = if ctx.has("add") { "add" } else { "set" };
if op == "add" {
let add = ctx.has("add");
let op = if add { "add" } else { "set" };
// Every target changes (a set of points can be refused for some).
let changed: Vec<Target> = targets
.iter()
.copied()
.filter(|&t| {
self.for_player(t, |g| g.change_experience(add, levels, amount)) == Some(true)
})
.collect();
if changed.is_empty() {
return Err(err("commands.experience.set.points.invalid", &[]));
}
let (key, who) = match changed[..] {
[only] => ("single", self.target_name(only)),
_ => ("multiple", Text::literal(changed.len().to_string())),
};
self.feedback(Text::translate(
&format!("commands.experience.{op}.{unit}.success.{key}"),
&[Text::literal(amount.to_string()), who],
));
Ok(changed.len() as i32)
}
/// ExperienceCommand's add and set on the player in place: false when
/// the points to set do not fit the level.
fn change_experience(&mut self, add: bool, levels: bool, amount: i32) -> bool {
if add {
if levels {
self.experience.level = (self.experience.level + amount).max(0);
if self.experience.level == 0 && amount < 0 {
@@ -2452,26 +2481,11 @@ impl Game<'_> {
} else {
let needed = horizon_client::entities::Experience::needed(self.experience.level);
if amount > needed - 1 {
return Err(err("commands.experience.set.points.invalid", &[]));
return false;
}
self.experience.progress = amount as f32 / needed as f32;
}
let key = format!(
"commands.experience.{op}.{unit}.success.{}",
if targets.len() == 1 {
"single"
} else {
"multiple"
}
);
self.feedback(Text::translate(
&key,
&[
Text::literal(amount.to_string()),
Text::literal(self.acting_player_name()),
],
));
Ok(targets.len() as i32)
true
}
fn cmd_gamerule(&mut self, ctx: &Context) -> R<i32> {
let Some(name) = ctx.literals.get(1).cloned() else {
@@ -2556,21 +2570,26 @@ impl Game<'_> {
};
let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0;
let pitch = rot[1].clamp(-90.0, 90.0);
// SetSpawnCommand: a forced point in the source's level.
if self.dim == Dim::Overworld {
self.spawn = Some(Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
self.respawn_config = None;
} else {
self.spawn = None;
self.respawn_config = Some(super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos,
yaw,
forced: true,
// SetSpawnCommand: a forced point in the source's level, for each target.
let level = self.dim;
for &t in &targets {
self.for_player(t, |g| {
if level == Dim::Overworld {
g.spawn = Some(Vec3::new(
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
g.respawn_config = None;
} else {
g.spawn = None;
g.respawn_config = Some(super::respawn_anchor::RespawnConfig {
dim: level,
pos,
yaw,
forced: true,
});
}
});
}
let dim = Text::literal(self.dim.id());
@@ -2750,6 +2769,44 @@ impl Game<'_> {
},
};
let max = Self::int(ctx, "maxCount").unwrap_or(-1);
let counting = max == 0;
// ClearInventoryCommands.clearInventory: each player on their own.
let mut removed = 0i32;
let mut found = Vec::new();
for &t in &targets {
let n = self
.for_player(t, |g| g.clear_matching(&predicate, max))
.unwrap_or(0);
removed += n;
if n != 0 {
found.push(t);
}
}
if removed == 0 {
return Err(if targets.len() == 1 {
CommandError::new(Text::translate(
"clear.failed.single",
&[self.target_name(targets[0])],
))
} else {
err("clear.failed.multiple", &[&targets.len()])
});
}
let kind = if counting { "test" } else { "success" };
let (key, who) = match found[..] {
[only] => ("single", self.target_name(only)),
_ => ("multiple", Text::literal(found.len().to_string())),
};
self.feedback(Text::translate(
&format!("commands.clear.{kind}.{key}"),
&[Text::literal(removed.to_string()), who],
));
Ok(removed)
}
/// Inventory.clearOrCountMatchingItems for the player in place: `max`
/// of the matching items go (all when negative, none and only counted
/// when 0). Returns how many matched.
fn clear_matching(&mut self, predicate: &ItemInput, max: i32) -> i32 {
let counting = max == 0;
// Inventory slots 0..40: main, armor feet to head, off hand;
// then clearOrCountMatchingItems visits the crafting grid and carried stack.
@@ -2765,10 +2822,7 @@ impl Game<'_> {
};
let matching: Vec<bool> = all(self)
.iter()
.map(|s| {
s.as_ref()
.is_some_and(|s| self.stack_matches(&predicate, s))
})
.map(|s| s.as_ref().is_some_and(|s| self.stack_matches(predicate, s)))
.collect();
let mut slots: Vec<&mut Option<ItemStack>> = Vec::new();
slots.extend(self.inventory.iter_mut());
@@ -2798,25 +2852,7 @@ impl Game<'_> {
}
}
}
if removed == 0 {
return Err(if targets.len() == 1 {
CommandError::new(Text::translate(
"clear.failed.single",
&[Text::literal(self.acting_player_name())],
))
} else {
err("clear.failed.multiple", &[&targets.len()])
});
}
let kind = if counting { "test" } else { "success" };
self.feedback(Text::translate(
&format!("commands.clear.{kind}.single"),
&[
Text::literal(removed.to_string()),
Text::literal(self.acting_player_name()),
],
));
Ok(removed)
removed
}
/// `PoiTypes`: the point of interest type of a block state.
fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> {
@@ -204,6 +204,64 @@ impl Game<'_> {
}
}
// ---- interactions -----------------------------------------------------
/// `WeatheringCopperGolemStatueBlock.useItemOn`: an axe on an unoxidized
/// statue turns it back into a golem (`CopperGolemStatueBlockEntity.removeStatue`),
/// wearing the axe. Weathered statues are scraped by the axe's own
/// transform instead.
pub(super) fn use_golem_statue(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool {
if !held.is_some_and(|s| s.item.ends_with("_axe")) {
return false;
}
let registry = self.pack.assets.registry;
let Some(state) = registry.state(self.world.block(pos[0], pos[1], pos[2])) else {
return false;
};
if state.name != "minecraft:copper_golem_statue" {
return false;
}
// `Direction.toYRot` of the statue's facing.
let yaw = match state.properties.get("facing").map(String::as_str) {
Some("west") => 90.0,
Some("north") => 180.0,
Some("east") => 270.0,
_ => 0.0,
};
let waterlogged = state
.properties
.get("waterlogged")
.is_some_and(|w| w == "true");
// initCopperGolem: at the block's feet, facing as the statue does.
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
];
let Some(id) = self.spawn_mob("minecraft:copper_golem", at, true) else {
return false;
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.yaw = yaw;
m.previous_yaw = yaw;
m.body_yaw = yaw;
m.previous_body_yaw = yaw;
m.head_yaw = yaw;
m.previous_head_yaw = yaw;
}
self.damage_held(1);
self.audio
.play("minecraft:entity.copper_golem.spawn", Some(at), 1.0, 1.0);
// Level.removeBlock(pos, false): air, or the water the statue stood in.
let replacement = registry.default_state(if waterlogged {
"minecraft:water"
} else {
"minecraft:air"
});
if let Some(replacement) = replacement {
let _ = self.level_set(pos, replacement);
}
self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
true
}
/// `CopperGolem.mobInteract`; true when handled.
pub(super) fn interact_copper_golem(&mut self, index: usize, item: &str) -> bool {
if self.mobs[index].species() != Species::CopperGolem || !self.mobs[index].alive() {
@@ -0,0 +1,39 @@
//! The creative toolbars, `hotbar.nbt` beside `options.txt`: hold the save or
//! load key and press a hotbar key (`Minecraft.handleKeybinds`).
use super::Game;
use horizon_client::{hotbar, keybinds, text::Text};
impl Game<'_> {
/// Whether the key bound to `mapping` is held.
pub(super) fn mapped_key_down(&self, mapping: &str) -> bool {
keybinds::key_code(self.settings.keys.get(mapping))
.is_some_and(|k| self.physical_keys.contains(&k))
}
/// `CreativeModeInventoryScreen.handleHotbarLoadOrSave` for the hotbar key
/// `index`: load puts the saved row in the hotbar (the creative slot
/// packets follow from the inventory change), save stores the hotbar and
/// says so on the action bar.
pub(super) fn hotbar_load_or_save(&mut self, index: usize, load: bool) {
let path = Self::options_path().with_file_name("hotbar.nbt");
let known = |id: &str| self.res.items().get(id).is_some();
let mut rows = hotbar::load(&path, &known);
if load {
for (slot, stack) in rows[index].iter().enumerate() {
self.inventory[slot] = stack.clone();
}
return;
}
rows[index] = self.inventory[..hotbar::SIZE].to_vec();
let _ = hotbar::save(&path, &rows);
let key = |mapping: &str| keybinds::display_name(self.settings.keys.get(mapping));
let message = Text::translate(
"inventory.hotbarSaved",
&[
key("key.loadToolbarActivator"),
key(&format!("key.hotbar.{}", index + 1)),
],
);
self.titles.set_overlay(message, false);
}
}
+147 -23
View File
@@ -46,6 +46,9 @@ pub(super) struct Creatures {
pub projectiles: Vec<Projectile>,
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
pub wind_bursts: Vec<super::wind::Burst>,
/// Mace smash knockback on the other players from a guest's turn, waiting
/// for it to end (game/mace.rs).
pub smash_pushes: Vec<super::mace::SmashPush>,
/// Sweep attacks from a guest's turn, waiting for it to end
/// (game/lan_pvp.rs).
pub sweeps: Vec<super::lan_pvp::Sweep>,
@@ -56,6 +59,8 @@ pub(super) struct Creatures {
pub elder_apparition: i32,
/// The wandering trader spawner's clock.
pub trader: super::wandering_trader::Spawner,
/// The cat spawner's countdown (`CatSpawner.nextTick`).
pub cat_tick: i32,
/// Particles from a guest's turn, waiting for it to end
/// (`lan_send_particles`: options, centre, spread, speed, count).
pub lan_particles: Vec<(
@@ -199,6 +204,7 @@ impl Game<'_> {
// EntitySelector.NO_CREATIVE_OR_SPECTATOR.
creative: self.creative || self.spectator(),
sneaking: self.keys.contains(&winit::keyboard::KeyCode::ShiftLeft),
swimming: p.swimming,
look: view_vector(self.yaw, self.pitch),
main_hand: self.held().map(|s| s.item.clone()),
off_hand: None,
@@ -211,6 +217,8 @@ impl Game<'_> {
last_hurt: self.combat.last_hurt_mob.map(|(id, at)| (Who::Mob(id), at)),
velocity: p.velocity,
yaw: self.yaw,
sprinting: p.sprinting,
riding: self.riding.is_some(),
hero: self.potions.effects.get("hero_of_the_village").is_some(),
effects: self.potions.effects.list.iter().map(|e| e.id).collect(),
uuid: self.level.player_uuid.unwrap_or_default(),
@@ -502,6 +510,7 @@ impl Game<'_> {
if self.ui.rules.bool("spawn_mobs") {
self.tick_wandering_trader();
self.tick_patrol_spawner();
self.tick_cat_spawner();
}
self.tick_raids();
self.tick_creature_entities()
@@ -584,6 +593,9 @@ impl Game<'_> {
..base.clone()
};
let m = &mut mobs[i];
// getCurrentDifficultyAt(blockPosition()): the mob's own chunk,
// not the local player's (a server thread has no player).
w.difficulty = self.local_difficulty([m.position.x, m.position.y, m.position.z]);
w.nearest_player = super::natural_spawning::nearest_player(
&players,
m.position.x,
@@ -729,6 +741,7 @@ impl Game<'_> {
self.tick_projectiles()?;
self.tick_fangs();
self.tick_allays();
self.tick_pandas();
self.tick_breeze_effects();
self.tick_sniffer_effects();
self.piglin_pickups();
@@ -763,11 +776,12 @@ impl Game<'_> {
let by_player = killer.is_some() || m.ai.last_hurt_by_player > 0;
let mut dying = m.clone();
// LivingEntity.die: the death is heard, and a sculk catalyst nearby
// takes the experience (before the loot is dropped).
// takes the experience (before the loot is dropped). It takes what
// would drop, whoever killed the mob.
self.sculk_mob_died(m);
let consumed =
self.catalyst_takes_experience([m.position.x, m.position.y, m.position.z], |_| {
if by_player {
if horizon_client::mobs::drops::drops_experience(&dying) {
horizon_client::mobs::drops::base_experience(&mut dying).max(0) as u32
} else {
0
@@ -1034,6 +1048,18 @@ impl Game<'_> {
MobEvent::AttackPlayer(amount, from) => {
self.mob_hits_player(amount, from, "minecraft:mob_attack");
}
// doHurtTarget: the effect only when hurtServer took damage.
MobEvent::AttackPlayerWithEffect {
amount,
from,
effect,
ticks,
amplifier,
} => {
if self.mob_hits_player(amount, from, "minecraft:mob_attack") {
self.give_player_effect(effect, ticks, amplifier);
}
}
MobEvent::DamagePlayer { amount, from, kind } => {
self.mob_hits_player(amount, from, kind);
}
@@ -1053,6 +1079,19 @@ impl Game<'_> {
}
}
}
MobEvent::Knockback {
target,
power,
x,
z,
} => match target {
Who::Player => self.knock_back_player(power, x, z),
Who::Mob(id) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) {
m.knockback(power, x, z);
}
}
},
MobEvent::Shift { target, delta } => {
let d = Vec3::new(delta[0], delta[1], delta[2]);
match target {
@@ -1398,6 +1437,27 @@ impl Game<'_> {
.list
.retain(|e| e.id != "mining_fatigue");
}
MobEvent::DolphinTreasure { mob } => {
// ServerLevel.findNearestMapStructure(#dolphin_located, 50).
let Some(at) = self.mobs.iter().find(|m| m.id == mob).map(|m| {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}) else {
continue;
};
let names = self.structure_tag("minecraft:dolphin_located");
let found = self
.end
.locator()
.filter(|_| !names.is_empty())
.and_then(|t| t.locate(&names, at, 50));
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
m.extra.home = found.map(|(_, p)| p);
}
}
MobEvent::EffectPlayer {
effect,
ticks,
@@ -1481,6 +1541,7 @@ impl Game<'_> {
m.ai.aggressive |= aggressive;
}
}
MobEvent::PandaSneezed { mob } => self.panda_sneezed(mob),
MobEvent::ShedScute { mob, at, pitch } => {
// The mob already checked `shouldDropLoot` (a baby, `mob_drops`).
let table = "minecraft:gameplay/armadillo_shed";
@@ -1498,8 +1559,12 @@ impl Game<'_> {
self.post_game_event("minecraft:entity_place", at, ctx);
}
MobEvent::GiftLoot { mob, table, at } => {
// Turtle.ageBoundaryReached: only with mob loot on.
if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
// Turtle.ageBoundaryReached and Panda.afterSneeze: only
// with mob loot on.
if matches!(
table,
"minecraft:gameplay/turtle_grow" | "minecraft:gameplay/panda_sneeze"
) && !self.ui.rules.bool("mob_drops")
{
continue;
}
@@ -1738,6 +1803,13 @@ impl Game<'_> {
self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
return;
}
// Panda.getBreedOffspring: genes from both parents.
if p.species() == Species::Panda {
horizon_client::mobs::panda::inherit(child, &p, q.as_ref().unwrap_or(&p));
let xp = 1 + self.world.random.next_int_bound(7).unwrap_or(0) as u32;
self.spawn_breeding_orb([p.position.x, p.position.y, p.position.z], xp);
return;
}
// Nautilus.getBreedOffspring: a tame parent's baby is tame too.
if p.species() == Species::Nautilus && p.extra.tame {
child.extra.tame = true;
@@ -1746,6 +1818,10 @@ impl Game<'_> {
}
// Offspring inherit a parent's variant (pigs/cows/chickens) or mixed wool.
child.extra.variant = p.extra.variant;
// Fox.getBreedOffspring: either parent's variant.
if p.species() == Species::Fox && !coin {
child.extra.variant = q.as_ref().map_or(p.extra.variant, |q| q.extra.variant);
}
if p.species() == Species::Sheep {
child.extra.color = p.extra.color;
}
@@ -2622,6 +2698,17 @@ impl Game<'_> {
};
self.player_hit(&victim, "minecraft:arrow", Some(direct), amount);
}
// AbstractArrow.onHitEntity: KILLED_BY_ARROW for a kill
// (piercing arrows are not modelled).
if hurt
&& let Some(m) = self.mobs.iter().find(|m| m.id == id)
&& !m.alive()
{
let victim = self.mob_entity(m);
let weapon =
p.arrow.as_ref().and_then(|a| a.fired_from_weapon.as_ref());
self.trigger_killed_by_arrow(&[victim], weapon);
}
}
hurt
}
@@ -3050,6 +3137,14 @@ impl Game<'_> {
let creative = self.creative;
// The hand's slot (Player.interactOn passes the hand).
let selected = self.held_slot();
// Panda.mobInteract: bamboo, or a click on a panda lying on its back.
if self.mobs[index].species() == Species::Panda && self.mobs[index].alive() {
let taken = self.interact_panda(index, &item);
if taken {
self.swing_arm();
}
return Ok(taken);
}
if self.interact_zombie_villager(index, &item) {
return Ok(true);
}
@@ -3105,6 +3200,12 @@ impl Game<'_> {
.item_tags
.get("minecraft:creeper_igniters")
.is_some_and(|t| t.contains(&*item));
let fish = self
.res
.items()
.item_tags
.get("minecraft:fishes")
.is_some_and(|t| t.contains(&*item));
let damageable = self
.res
.items()
@@ -3169,6 +3270,7 @@ impl Game<'_> {
at: pos,
setup,
}])?;
self.damage_held_tool();
}
Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => {
m.extra.sheared = true;
@@ -3208,8 +3310,9 @@ impl Game<'_> {
.items()
.get(&item)
.and_then(|i| i.food.as_ref())
.map_or(2.0, |f| f.0 as f32);
// TamableAnimal.feed: playEatingSound, which wolves leave empty.
.map_or(2.0, |f| f.0 as f32 * 2.0);
// TamableAnimal.feed(.., 2.0F, 2.0F): heals twice the nutrition,
// then playEatingSound, which wolves leave empty.
m.health = (m.health + heal).min(m.attrs.max_health);
consume = true;
}
@@ -3398,6 +3501,18 @@ impl Game<'_> {
self.trigger_entity("minecraft:tame_animal", "entity", &view);
}
}
// Dolphin.mobInteract: a fish makes a baby grow by a tenth and an
// adult remember it (`gotFish`), to swim to a treasure.
Species::Dolphin if fish => {
eat = Some(("entity.dolphin.eat", 1.0, 1.0));
if m.extra.age < 0 {
let secs = ((-m.extra.age / 20) as f32 * 0.1) as i32;
horizon_client::mobs::ai::age_up(m, secs, true);
} else {
m.extra.flag = true;
}
consume = true;
}
// Tadpole.feed: frog food ages it by a tenth of the time left to
// grow into a frog (it grows on its next tick once past 24000).
Species::Tadpole if is_food && !m.extra.age_locked => {
@@ -3411,6 +3526,22 @@ impl Game<'_> {
horizon_client::particles::Burst::HORSE_EATING,
);
}
// Bee.mobInteract: a wither rose or an open eyeblossom is eaten for
// its `getBeeInteractionEffect` instead of breeding the bee.
Species::Bee
if is_food
&& matches!(
&*item,
"minecraft:wither_rose" | "minecraft:open_eyeblossom"
) =>
{
if &*item == "minecraft:wither_rose" {
m.add_effect("minecraft:wither", 40, 0);
} else {
m.add_effect("minecraft:poison", 25, 0);
}
consume = true;
}
// HappyGhast.canFallInLove: never, so only a ghastling takes food.
_ if is_food
&& m.kind.flags.animal
@@ -3547,23 +3678,9 @@ impl Game<'_> {
}
true
}
/// `ItemStack.hurtAndBreak(1, ...)` on the held tool: Unbreaking, break sound and stat.
pub(super) fn damage_held_tool(&mut self) {
if self.creative {
return;
}
let slot = self.held_slot();
let max_damage = self
.held()
.and_then(|s| self.res.items().get(&s.item))
.map_or(0, |i| i.max_damage);
if max_damage > 0
&& let Some(stack) = self.stack_in_mut(slot).as_mut()
{
stack.damage += 1;
if stack.damage >= max_damage {
*self.stack_in_mut(slot) = None;
}
}
self.damage_held(1);
}
/// Throwables and spawn eggs (SnowballItem/EggItem/EnderpearlItem/SpawnEggItem.use).
pub(super) fn throw_item(&mut self, stack: &ItemStack) -> Result<bool> {
@@ -4139,6 +4256,7 @@ fn to_loot(stack: &ItemStack) -> horizon_world::loot::LootStack {
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
names: Vec::new(),
}
}
/// A generated loot stack as a Horizon item stack.
@@ -4158,6 +4276,9 @@ fn from_loot(stack: &horizon_world::loot::LootStack) -> ItemStack {
if let Some(amplifier) = stack.ominous_amplifier.filter(|a| *a > 0) {
item.data_mut().ominous_amplifier = Some(amplifier as u8);
}
for (id, text) in &stack.names {
item.data_mut().set_loot_name(id, text);
}
item
}
impl Game<'_> {
@@ -4201,6 +4322,9 @@ impl Game<'_> {
f64::from(y + 1),
f64::from(pos[2]) + 0.5,
];
let _ = self.spawn_mob("minecraft:zombified_piglin", at, false);
// setPortalCooldown: the new piglin does not travel at once.
if let Some(id) = self.spawn_mob("minecraft:zombified_piglin", at, false) {
self.set_portal_cooldown(id);
}
}
}
@@ -219,6 +219,7 @@ impl Game<'_> {
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(ammo);
a.set_owner(Some(Who::Player));
a.fired_from_weapon = Some(weapon.clone());
a.pierce = pierce;
}
arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0);
@@ -235,6 +236,11 @@ impl Game<'_> {
.play("minecraft:item.crossbow.shoot", Some(eye), 1.0, pitch);
self.damage_held(if rocket { 3 } else { 1 });
}
// CrossbowItem.performShooting: SHOT_CROSSBOW with the crossbow, which
// is an empty stack (no match) when the shots broke it.
if let Some(stack) = self.held().cloned() {
self.trigger_item("minecraft:shot_crossbow", &stack);
}
}
}
+3 -2
View File
@@ -244,7 +244,8 @@ impl Game<'_> {
if on { "visible" } else { "hidden" }
)
};
let remote = self.remote.is_some();
// `DebugScreenOverlay`: the single-player variants for a local server.
let remote = !self.has_singleplayer_server();
let c = &self.debug_charts;
[
format!(
@@ -463,7 +464,7 @@ impl Game<'_> {
height,
self.settings.max_fps,
1000.0 / self.clock.rate(),
self.remote.is_some(),
!self.has_singleplayer_server(),
);
draws.push(hud_layout::GuiDraw::Push(vec![hud_layout::PoseOp::Scale(
scale, scale,
+59 -1
View File
@@ -412,6 +412,8 @@ struct ServerState {
paused: bool,
/// `broadcast-console-to-ops`.
broadcast_console: bool,
/// `op-permission-level`: what `/op` grants (operatorUserPermissions).
op_level: i32,
}
/// The dedicated-only commands' replies vanilla sends with `broadcast`
@@ -573,6 +575,14 @@ impl Game<'_> {
// DedicatedServer.initServer: worldData.setGameType; forceDifficulty.
self.set_default_game_mode(game_mode);
self.ui.difficulty = props.difficulty as u8;
// DedicatedServer.initServer: a legacy `announce-player-achievements`
// sets the show_advancement_messages rule once, as the file is read.
if let Some(announce) = props.announce_player_achievements {
self.ui.rules.set(
"show_advancement_messages",
horizon_client::gamerules::Value::Bool(announce),
);
}
self.settings.render_distance = props.view_distance.clamp(2, 32);
self.settings.simulation_distance = props.simulation_distance.clamp(2, 32);
self.streaming.radius = self.settings.render_distance;
@@ -685,6 +695,7 @@ impl Game<'_> {
ticks: Default::default(),
paused: false,
broadcast_console: props.broadcast_console_to_ops,
op_level: props.op_permission_level,
};
let pause_after = props.pause_when_empty_seconds * 20;
let idle_timeout = props.player_idle_timeout;
@@ -946,7 +957,7 @@ impl Game<'_> {
let Some(user) = self.resolve(rest[0]) else {
return;
};
let level = 4;
let level = state.op_level;
let changed = {
let mut l = state.lists.lock().unwrap();
if command == "op" {
@@ -972,6 +983,10 @@ impl Game<'_> {
self.console_reply(Text::translate(key, &[lit(&user.name)]));
let lists = state.lists.clone();
self.sync_ops(&lists);
// DeOpCommands.deopPlayers.
if command == "deop" && changed {
self.kick_unlisted_players(&lists);
}
}
"whitelist" => self.console_whitelist(state, &rest),
"ban" if !rest.is_empty() => {
@@ -1183,6 +1198,7 @@ impl Game<'_> {
["on"] | ["off"] => {
let on = rest[0] == "on";
let mut l = state.lists.lock().unwrap();
let turned_on = on && !l.use_whitelist;
let key = match (on, l.use_whitelist) {
(true, true) => "commands.whitelist.alreadyOn",
(true, false) => "commands.whitelist.enabled",
@@ -1193,6 +1209,10 @@ impl Game<'_> {
drop(l);
self.store_property("white-list", on.to_string());
self.console_reply(Text::translate(key, &[]));
if turned_on {
let lists = state.lists.clone();
self.kick_unlisted_players(&lists);
}
}
["list"] => {
let names: Vec<String> = state
@@ -1216,6 +1236,8 @@ impl Game<'_> {
["reload"] => {
let _ = state.lists.lock().unwrap().white.load();
self.console_reply(Text::translate("commands.whitelist.reloaded", &[]));
let lists = state.lists.clone();
self.kick_unlisted_players(&lists);
}
["add", name] | ["remove", name] => {
let Some(user) = self.resolve(name) else {
@@ -1241,6 +1263,10 @@ impl Game<'_> {
Vec::new()
};
self.console_reply(Text::translate(key, &args));
if ok && rest[0] == "remove" {
let lists = state.lists.clone();
self.kick_unlisted_players(&lists);
}
}
_ => self.console_reply(Text::translate("command.unknown.argument", &[])),
}
@@ -1256,6 +1282,38 @@ impl Game<'_> {
}
}
/// MinecraftServer.kickUnlistedPlayers: with `enforce-whitelist` and the
/// whitelist on, whoever is online and not on the whitelist file is
/// disconnected (operators are not spared here).
fn kick_unlisted_players(&mut self, lists: &Arc<Mutex<Lists>>) {
let unlisted: Vec<u128> = {
let l = lists.lock().unwrap();
let Some(host) = self.lan.as_ref() else {
return;
};
if !(l.enforce_whitelist && l.use_whitelist) {
return;
}
host.hub
.guests
.iter()
.filter(|g| {
!l.white.contains(&NameAndId {
id: g.uuid,
name: g.name.clone(),
})
})
.map(|g| g.uuid)
.collect()
};
for uuid in unlisted {
self.kick_uuid(
uuid,
translatable("multiplayer.disconnect.not_whitelisted", &[]),
);
}
}
fn kick_uuid(&mut self, uuid: u128, reason: Tag) {
if let Some(h) = self.lan.as_mut() {
let conns: Vec<u32> = h
@@ -1548,6 +1548,7 @@ impl Game<'_> {
return Ok((Some(stack), FAIL));
};
let target = (placed.x, placed.y, placed.z);
let state = self.apply_item_block_state([target.0, target.1, target.2], state, &stack)?;
if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) {
self.world.block_entities.insert(target, entity);
self.apply_placed_item([target.0, target.1, target.2], &stack, false);
+10 -1
View File
@@ -1465,7 +1465,16 @@ impl Game<'_> {
}
}
let d2 = (pp.x - pos.x).powi(2) + (pp.y - pos.y).powi(2) + (pp.z - pos.z).powi(2);
if d2 < 4096.0 {
// Entity.hasLineOfSight: eye to eye (the dragon's eye is 0.85 of
// its 8 block height), blocks only.
let sees = d2 < 4096.0 && {
let eye = Vec3::new(pos.x, pos.y + 6.8, pos.z);
let target_eye =
tracked.map_or(pp.y + 1.62, |p| p.bounds.max_position().y - 0.18);
self.mob_world_base(&[])
.line_of_sight(eye, Vec3::new(pp.x, target_eye, pp.z))
};
if sees {
*charge += 1;
let d = self.dragon.as_ref().expect("dragon");
let r = d.yaw.to_radians();
+8 -4
View File
@@ -15,6 +15,7 @@ use horizon_client::{
};
use horizon_core::{
geometry::{Aabb, Vec3, trig},
position::BlockPos,
random::RandomSource,
};
use horizon_protocol::entity_data::{Value, serializer};
@@ -248,7 +249,7 @@ impl Game<'_> {
item,
[hook.position.x, hook.position.y, hook.position.z],
v,
10,
0,
);
let xp = self.world.random.next_int_bound(6).unwrap_or(0) as u32 + 1;
self.spawn_orbs([owner.x, owner.y + 0.5, owner.z + 0.5], xp);
@@ -339,9 +340,12 @@ impl Game<'_> {
let mut speed = 1;
let above = [b[0], b[1] + 1, b[2]];
let sky = self.world.light(above[0], above[1], above[2]) >> 4 == 15;
let raining = self.world.weather.raining;
let r = &mut self.world.random;
if r.next_float() < 0.25 && raining && sky {
// Level.isRainingAt: rain (not snow) reaches the position.
if self.world.random.next_float() < 0.25
&& self.with_level(|b, level, _| {
b.is_raining_at(level, BlockPos::new(above[0], above[1], above[2]))
})
{
speed += 1;
}
let r = &mut self.world.random;
+6 -3
View File
@@ -144,6 +144,11 @@ impl Game<'_> {
let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name);
speed / facts.hardness / if harvest { 30.0 } else { 100.0 }
}
/// A key for the main-hand stack (`destroyingItem`): its item and components.
pub(super) fn main_hand_key(&self) -> String {
self.held()
.map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra))
}
/// Whether an attack would hit an entity rather than the block behind
/// it: the crosshair's `EntityHitResult`.
pub(super) fn entity_targeted(&self) -> bool {
@@ -503,9 +508,7 @@ impl HandWorld for GameHands<'_, '_> {
true
}
fn main_hand_key(&mut self) -> String {
self.game
.held()
.map_or(String::new(), |s| format!("{} {:?}", s.item, s.extra))
self.game.main_hand_key()
}
fn destroy_stage(&mut self, _: [i32; 3], _: Option<i32>) {}
fn swing(&mut self, hand: Hand, animation: SwingAnimation) {
+281 -1
View File
@@ -181,6 +181,136 @@ pub(super) fn baby_index(kind: &str) -> Option<u8> {
}
}
/// The variant and look entries of `mob_meta`'s mobs (registry holders, the
/// fish's, the bee's, the copper golem's weathering...), in a match of their
/// own: `mob_meta`'s arms hold these mobs' other entries.
fn mob_variant_meta(
m: &Mob,
hub: &Hub,
meta: &mut Vec<(u8, i32, Value)>,
defaults: &mut Vec<(u8, i32, Value)>,
) {
let (kind, e) = (m.kind.id.as_str(), &m.extra);
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
match kind {
// Axolotl.DATA_VARIANT (after AgeableMob's two).
"minecraft:axolotl" => {
if e.variant != 0 {
meta.push((18, serializer::INT, Value::Int(i32::from(e.variant))));
}
}
// Frog.DATA_VARIANT_ID, Pig's, Cow's, Chicken's and ZombieNautilus's
// (after the entries of their parents): registry holders.
"minecraft:frog"
| "minecraft:pig"
| "minecraft:cow"
| "minecraft:chicken"
| "minecraft:zombie_nautilus" => {
let (index, serializer, registry) = match kind {
"minecraft:frog" => (18, serializer::FROG_VARIANT, "minecraft:frog_variant"),
"minecraft:pig" => (19, serializer::PIG_VARIANT, "minecraft:pig_variant"),
"minecraft:cow" => (18, serializer::COW_VARIANT, "minecraft:cow_variant"),
"minecraft:chicken" => {
(18, serializer::CHICKEN_VARIANT, "minecraft:chicken_variant")
}
_ => (
21,
serializer::ZOMBIE_NAUTILUS_VARIANT,
"minecraft:zombie_nautilus_variant",
),
};
// Each registry's default (`define(DATA_VARIANT_ID, ... TEMPERATE)`)
// stays out of the pairing data, as other default values do.
let name = horizon_client::mobs::finalize::variant_name(m.species(), e.variant);
let name = name.trim_start_matches("minecraft:");
if let Some(v) = id(registry, name)
&& name != "temperate"
{
meta.push((index, serializer, Value::Id(v)));
}
if let Some(v) = id(registry, "temperate") {
defaults.push((index, serializer, Value::Id(v)));
}
}
// Rabbit.DATA_TYPE_ID (after AgeableMob's two) and
// Parrot.DATA_VARIANT_ID (after TamableAnimal's two and its flags and
// owner). The fox's type goes with its flags (#2538).
"minecraft:rabbit" | "minecraft:parrot" => {
let index = if kind == "minecraft:parrot" { 20 } else { 18 };
if e.variant != 0 {
meta.push((index, serializer::INT, Value::Int(i32::from(e.variant))));
}
}
// Bee.DATA_FLAGS_ID (rolling 2, stung 4, nectar 8) and
// DATA_ANGER_END_TIME: the texture shows the nectar and the anger.
"minecraft:bee" => {
let bee = horizon_client::mobs::bee::get(m);
let flags = bee.map_or(0, |b| b.flags);
if flags != 0 {
meta.push((18, serializer::BYTE, Value::Byte(flags as i8)));
}
defaults.push((18, serializer::BYTE, Value::Byte(0)));
let anger_end = bee.map_or(-1, |b| b.anger_end);
if anger_end != -1 {
meta.push((19, serializer::LONG, Value::Long(anger_end)));
}
defaults.push((19, serializer::LONG, Value::Long(-1)));
}
// AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0,
// medium 1, large 2; medium is the data's default, so always sent),
// Pufferfish.PUFF_STATE and TropicalFish.DATA_ID_TYPE_VARIANT: the
// pattern's packed id (size, then index << 8), base colour << 16 and
// pattern colour << 24.
"minecraft:salmon" => {
meta.push((17, serializer::INT, Value::Int(i32::from(e.variant.min(2)))));
}
"minecraft:pufferfish" => {
if e.size > 0 {
meta.push((17, serializer::INT, Value::Int(e.size)));
}
defaults.push((17, serializer::INT, Value::Int(0)));
}
"minecraft:tropical_fish" => {
let pattern = e.variant.min(11);
let packed = i32::from(pattern >= 6)
| i32::from(pattern % 6) << 8
| i32::from(e.variant2 & 15) << 16
| i32::from(e.variant3 & 15) << 24;
if packed != 0 {
meta.push((17, serializer::INT, Value::Int(packed)));
}
}
// CopperGolem.DATA_WEATHER_STATE: unaffected 0 to oxidized 3, and it
// goes back down when the golem is scraped.
"minecraft:copper_golem" => {
if e.variant != 0 {
meta.push((
16,
serializer::WEATHERING_COPPER_STATE,
Value::Id(i32::from(e.variant.min(3))),
));
}
defaults.push((16, serializer::WEATHERING_COPPER_STATE, Value::Id(0)));
}
// Ghast.DATA_IS_CHARGING: the shooting texture.
"minecraft:ghast" => {
if e.flag {
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
}
// WitherBoss.DATA_ID_INV (after the three head targets): the
// invulnerable ticks, the blinking texture and the growing scale.
"minecraft:wither" => {
if e.counter > 0 {
meta.push((19, serializer::INT, Value::Int(e.counter)));
}
defaults.push((19, serializer::INT, Value::Int(0)));
}
_ => {}
}
}
/// A mob's synched data as ServerEntity sends it (only the values that differ
/// from the defaults the client constructs), with vanilla's entry indices:
/// Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses.
@@ -258,6 +388,7 @@ fn mob_meta(
}
let e = &m.extra;
let id = |registry: &str, name: &str| hub.registry_id(registry, &format!("minecraft:{name}"));
mob_variant_meta(m, hub, meta, defaults);
match kind {
"minecraft:guardian" | "minecraft:elder_guardian" => {
// Guardian.DATA_ID_MOVING and DATA_ID_ATTACK_TARGET.
@@ -314,6 +445,18 @@ fn mob_meta(
}
defaults.push((18, serializer::BYTE, Value::Byte(0)));
}
// Fox.DATA_TYPE_ID and DATA_FLAGS_ID (after AgeableMob's two; sleeping 32, ...).
"minecraft:fox" => {
if e.variant != 0 {
meta.push((18, serializer::INT, Value::Int(i32::from(e.variant))));
}
defaults.push((18, serializer::INT, Value::Int(0)));
let flags = (e.ints[0] & 0xff) as u8 as i8;
if flags != 0 {
meta.push((19, serializer::BYTE, Value::Byte(flags)));
}
defaults.push((19, serializer::BYTE, Value::Byte(0)));
}
"minecraft:cat" | "minecraft:wolf" => {
// TamableAnimal.DATA_FLAGS_ID: sitting 1, tame 4.
let flags = i8::from(e.sitting) | if e.tame { 4 } else { 0 };
@@ -342,6 +485,14 @@ fn mob_meta(
meta.push((collar, serializer::INT, Value::Int(i32::from(e.color & 15))));
}
defaults.push((collar, serializer::INT, Value::Int(red)));
// Wolf.DATA_ANGER_END_TIME: the game time the anger ends, -1 when calm.
if kind == "minecraft:wolf" {
if e.anger > 0 {
let end = game_time + i64::from(e.anger);
meta.push((22, serializer::LONG, Value::Long(end)));
}
defaults.push((22, serializer::LONG, Value::Long(-1)));
}
}
"minecraft:horse"
| "minecraft:donkey"
@@ -420,6 +571,29 @@ fn mob_meta(
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
}
// Panda: UNHAPPY_COUNTER, SNEEZE_COUNTER and EAT_COUNTER (after
// AgeableMob's two), MAIN_GENE_ID, HIDDEN_GENE_ID and DATA_ID_FLAGS;
// the client animates the states from them.
"minecraft:panda" => {
let (flags, counters) = horizon_client::mobs::panda::get(m)
.map_or((0, [0; 3]), |s| (s.flags, [s.unhappy, s.sneeze, s.eat]));
for (index, value) in (18..).zip(counters) {
if value != 0 {
meta.push((index, serializer::INT, Value::Int(value)));
}
defaults.push((index, serializer::INT, Value::Int(0)));
}
for (index, gene) in [(21, e.variant), (22, e.variant2)] {
if gene != 0 {
meta.push((index, serializer::BYTE, Value::Byte(gene as i8)));
}
defaults.push((index, serializer::BYTE, Value::Byte(0)));
}
if flags != 0 {
meta.push((23, serializer::BYTE, Value::Byte(flags as i8)));
}
defaults.push((23, serializer::BYTE, Value::Byte(0)));
}
// PolarBear.DATA_STANDING_ID (after AgeableMob's two): the bear
// rears up; the client animates it.
"minecraft:polar_bear" => {
@@ -470,6 +644,86 @@ fn mob_meta(
}
defaults.push((18, serializer::BYTE, Value::Byte(16)));
}
// Vex.DATA_FLAGS_ID: charging in bit 0 (the arms and the glowing
// texture).
"minecraft:vex" => {
if e.flag {
meta.push((16, serializer::BYTE, Value::Byte(1)));
}
defaults.push((16, serializer::BYTE, Value::Byte(0)));
}
// Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN.
"minecraft:creaking" => {
if e.flag2 {
meta.push((16, serializer::BOOLEAN, Value::Bool(false)));
}
defaults.push((16, serializer::BOOLEAN, Value::Bool(true)));
if e.flag {
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
if horizon_client::mobs::creaking::tearing_down(m) {
meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((18, serializer::BOOLEAN, Value::Bool(false)));
}
// Allay.DATA_DANCING and DATA_CAN_DUPLICATE (the held item is its
// main hand equipment).
"minecraft:allay" => {
if e.flag {
meta.push((16, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((16, serializer::BOOLEAN, Value::Bool(false)));
if e.egg_time > 0 {
meta.push((17, serializer::BOOLEAN, Value::Bool(false)));
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(true)));
}
// Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT).
"minecraft:axolotl" => {
if horizon_client::mobs::axolotl::is_playing_dead(m) {
meta.push((19, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((19, serializer::BOOLEAN, Value::Bool(false)));
}
// CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE).
"minecraft:copper_golem" => {
if e.variant3 != 0 {
meta.push((
17,
serializer::COPPER_GOLEM_STATE,
Value::Id(i32::from(e.variant3)),
));
}
defaults.push((17, serializer::COPPER_GOLEM_STATE, Value::Id(0)));
}
// Armadillo.ARMADILLO_STATE (after AgeableMob's two).
"minecraft:armadillo" => {
let state = horizon_client::mobs::armadillo::state(m);
if state != 0 {
meta.push((18, serializer::ARMADILLO_STATE, Value::Id(i32::from(state))));
}
defaults.push((18, serializer::ARMADILLO_STATE, Value::Id(0)));
}
// Frog.DATA_TONGUE_TARGET_ID (after the variant): the entity id plus
// one, 0 for none.
"minecraft:frog" => {
if let Some(target) = e.frog.tongue_target {
let id = i32::try_from(target).map_or(0, |t| t + 1);
meta.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(id)));
}
defaults.push((19, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(0)));
}
// Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN (after
// DATA_IS_SCREAMING_GOAT): both true by default.
"minecraft:goat" => {
for (index, lost) in [(19, e.lost_horns[0]), (20, e.lost_horns[1])] {
if lost {
meta.push((index, serializer::BOOLEAN, Value::Bool(false)));
}
defaults.push((index, serializer::BOOLEAN, Value::Bool(true)));
}
}
// Enderman.DATA_CARRY_STATE.
"minecraft:enderman" => {
if let Some(state) = e.carried {
@@ -760,7 +1014,8 @@ impl Game<'_> {
let host_uuid = host.unwrap_or(0);
self.next_entity += 1;
let host_entity = self.next_entity as i32;
let hub = Hub::new(lan, sync, encoder, config);
let mut hub = Hub::new(lan, sync, encoder, config);
hub.flat_world = self.world_flat;
let port = hub.lan.port;
self.world.block_log = Some(Vec::new());
self.world.light_log = Some(Default::default());
@@ -1223,6 +1478,16 @@ impl Game<'_> {
"INFO",
&format!("System chat: {} joined the game", g.name),
);
} else if self.player.is_some()
&& let Some(g) = host.hub.guest(conn)
&& g.placed
{
// The host's chat hears of the newcomer as the guests do.
let who = self.player_text(&g.name, g.uuid);
self.system_message(
Text::translate("multiplayer.player.joined", &[who])
.with_color(horizon_client::text::YELLOW),
);
}
}
HostEvent::Left(mut guest) => {
@@ -1257,6 +1522,13 @@ impl Game<'_> {
"INFO",
&format!("System chat: {} left the game", guest.name),
);
} else if self.player.is_some() && guest.placed {
// ServerGamePacketListenerImpl.removePlayerFromWorld.
let who = self.player_text(&guest.name, guest.uuid);
self.system_message(
Text::translate("multiplayer.player.left", &[who])
.with_color(horizon_client::text::YELLOW),
);
}
}
HostEvent::Packet(conn, packet) => {
@@ -1662,6 +1934,14 @@ impl Game<'_> {
.filter_map(|e| super::client_ambient::effect_particle(e.id, e.ambient))
.collect();
m.extra.effect_ambient = visible().all(|e| e.ambient);
// Entity.isInvisible: the invisibility effect hides the body (the
// model pass, the name tag rules and `trader::is_invisible` read it).
m.extra.effects.retain(|e| e.0 != "minecraft:invisibility");
if let Some(e) = g.effects.get("invisibility") {
m.extra
.effects
.push(("minecraft:invisibility", e.duration, e.amplifier));
}
// Lying in its bed (LivingEntity.getBedOrientation).
m.extra.ints[1] = g.bed.map_or(0, |b| self.bed_facing(b));
// LivingEntity.updateSwingTime: the arm swing lan_swings started.
+57 -7
View File
@@ -1434,19 +1434,68 @@ impl Game<'_> {
.unwrap_or_default();
host.hub.send_stats(conn, &stats);
}
// handlePickItemFromBlock: a block within the block reach plus 1, its
// data only with infinite materials.
S::PickItemFromBlock(p) => {
let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]);
let item = self.res.facts().get(state).item.clone();
let g = &mut host.hub.guests[gi];
if g.creative() && &*item != "minecraft:air" {
let slot = g.selected;
g.inventory[slot] = Some(ItemStack::new(&item, 1));
}
self.guest_pick_item(host, conn, |g| {
let eye = g.eye_position()?;
let d2: f64 = (0..3)
.map(|a| {
let lo = f64::from(p.pos[a]);
(eye[a] - eye[a].clamp(lo, lo + 1.0)).powi(2)
})
.sum();
let range = g.reach() + 1.0;
if d2 >= range * range {
return None;
}
g.picked_stack(p.pos, g.creative && p.include_data)
});
}
// handlePickItemFromEntity.
S::PickItemFromEntity(p) => {
self.guest_pick_item(host, conn, |g| {
g.within_entity_range(p.id)
.then(|| g.entity_pick_result(p.id))
.flatten()
});
}
_ => {}
}
}
/// `ServerGamePacketListenerImpl.tryPickItem` for the guest: a matching stack
/// is selected, else a creative player gets the item; the held slot is sent
/// back and the changed slots follow with the tick's inventory changes.
fn guest_pick_item(
&mut self,
host: &mut LanHost,
conn: u32,
stack: impl FnOnce(&mut Self) -> Option<ItemStack>,
) {
let picked = self.as_guest(host, conn, |g| {
let stack = stack(g)?;
let infinite = g.creative;
horizon_client::pick_item::pick(
&mut g.inventory[..36],
&mut g.selected,
&stack,
infinite,
);
Some(())
});
if picked.flatten().is_some()
&& let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn)
{
host.hub.send_to(
conn,
&C::SetHeldSlot(play::SetHeldSlot {
slot: g.selected as i32,
}),
);
}
}
fn item_from_network(
&self,
host: &LanHost,
@@ -2054,6 +2103,7 @@ impl Game<'_> {
self.as_guest(host, conn, |g| {
g.tick_fishing();
g.tick_maps();
g.tick_lodestone_compasses();
g.count_tick_stats(sleeping);
g.tick_advancements();
g.update_player_attributes();
+32 -38
View File
@@ -11,18 +11,6 @@ use horizon_client::lan::{
use horizon_protocol::entity_data::{Value, serializer};
use horizon_world::nbt::Tag;
/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg,
/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21),
/// under their `Pose` keys.
const STAND_POSES: [(&str, [f32; 3]); 6] = [
("Head", [0.0, 0.0, 0.0]),
("Body", [0.0, 0.0, 0.0]),
("LeftArm", [-10.0, 0.0, -10.0]),
("RightArm", [-15.0, 0.0, 10.0]),
("LeftLeg", [-1.0, 0.0, -1.0]),
("RightLeg", [1.0, 0.0, 1.0]),
];
fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState {
EntityState {
id: id as i32,
@@ -61,28 +49,21 @@ fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Val
meta
}
/// An armor stand's pose from its compound (`ArmorStandPose`), each part
/// that differs from the default.
fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> {
let Some(pose) = raw.and_then(|t| t.get("Pose")) else {
return Vec::new();
};
/// An armor stand's pose (`ArmorStandPose`), each part that differs from the
/// default, as DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21).
fn stand_poses(a: &horizon_client::entities::ArmorStand) -> Vec<(u8, i32, Value)> {
let mut meta = Vec::new();
for (i, (key, default)) in STAND_POSES.iter().enumerate() {
let Some(Tag::List(values)) = pose.get(key) else {
continue;
};
let mut r = *default;
for (k, v) in values.iter().take(3).enumerate() {
if let Tag::Float(bits) = v {
r[k] = f32::from_bits(*bits);
}
}
if r != *default {
for (i, (rotation, default)) in a
.pose
.iter()
.zip(horizon_client::entities::ArmorStand::DEFAULT_POSE)
.enumerate()
{
if *rotation != default {
meta.push((
16 + i as u8,
serializer::ROTATIONS,
Value::Floats(r.to_vec()),
Value::Floats(rotation.to_vec()),
));
}
}
@@ -185,7 +166,19 @@ impl Game<'_> {
if flags != 0 {
e.meta.push((15, serializer::BYTE, Value::Byte(flags)));
}
e.meta.extend(stand_poses(self.persist.raw.get(&a.id)));
e.meta.extend(stand_poses(a));
// A pose put back to its default (`/data`) is sent as that default.
e.defaults.push((15, serializer::BYTE, Value::Byte(0)));
for (i, default) in horizon_client::entities::ArmorStand::DEFAULT_POSE
.iter()
.enumerate()
{
e.defaults.push((
16 + i as u8,
serializer::ROTATIONS,
Value::Floats(default.to_vec()),
));
}
// Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5.
for (slot, item) in a.equipment.iter().enumerate() {
if item.is_some() {
@@ -498,7 +491,9 @@ impl Game<'_> {
// The dragon's breath and lingering potion clouds (AreaEffectCloud's DATA_RADIUS,
// DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the
// client draws them from these (`tick_remote_clouds`).
let breath = self.network_particle(
// The hub is out of `self.lan` meanwhile, so it is passed in.
let breath = Self::hub_particle(
hub,
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::DragonBreath,
),
@@ -560,11 +555,9 @@ mod tests {
#[test]
fn armor_stand_poses_send_only_what_differs() {
let tag =
horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}")
.unwrap()
.0;
let meta = stand_poses(Some(&tag));
let mut stand = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0);
stand.pose[0] = [10.0, 20.0, 0.0];
let meta = stand_poses(&stand);
assert_eq!(
meta,
vec![(
@@ -573,6 +566,7 @@ mod tests {
Value::Floats(vec![10.0, 20.0, 0.0])
)]
);
assert!(stand_poses(None).is_empty());
let plain = horizon_client::entities::ArmorStand::new(1, Default::default(), 0.0);
assert!(stand_poses(&plain).is_empty());
}
}
@@ -81,11 +81,16 @@ pub(super) fn acts_on_player(e: &MobEvent) -> bool {
matches!(
e,
MobEvent::AttackPlayer(..)
| MobEvent::AttackPlayerWithEffect { .. }
| MobEvent::DamagePlayer { .. }
| MobEvent::Push {
target: Who::Player,
..
}
| MobEvent::Knockback {
target: Who::Player,
..
}
| MobEvent::Ignite {
target: Who::Player,
..
@@ -369,6 +374,7 @@ mod tests {
alive: true,
creative,
sneaking: false,
swimming: false,
look: [0.0; 3],
main_hand: None,
off_hand: None,
@@ -381,6 +387,8 @@ mod tests {
last_hurt: None,
velocity: Vec3::ZERO,
yaw: 0.0,
sprinting: false,
riding: false,
hero: false,
effects: Vec::new(),
uuid: [0; 4],
@@ -156,7 +156,7 @@ impl Game<'_> {
/// `network_particle` for a hub that is out of `self.lan` meanwhile (a
/// guest's turn).
fn hub_particle(
pub(super) fn hub_particle(
hub: &Hub,
options: &ParticleOptions,
state: Option<BlockStateId>,
+13
View File
@@ -41,6 +41,8 @@ pub(super) struct Strike {
/// `Player.attack`'s `magicBoost > 0`: the enchantments added damage.
magic: bool,
from: [f64; 3],
/// `getSecondsToDisableBlocking` of the attacker's weapon.
disable_blocking: f32,
sweep: Option<[f64; 3]>,
/// `causeExtraKnockback`: its strength and direction (the attacker's
/// yaw), and whether the hit is a sprinting knockback attack.
@@ -154,6 +156,14 @@ impl Game<'_> {
let (xd, zd) = self.extra_knockback_direction();
self.attack_ticks = 0;
self.swing_arm();
// LivingEntity.getSecondsToDisableBlocking: the held weapon's value,
// none while another item is in use.
let disable_blocking = if self.using.is_some() {
0.0
} else {
self.attack_item_info()
.map_or(0.0, |i| i.disable_blocking_seconds)
};
Some(Strike {
attacker: self.lan_acting,
amount,
@@ -161,6 +171,7 @@ impl Game<'_> {
crit,
magic,
from,
disable_blocking,
sweep,
knockback: (strength, xd, zd),
knockback_attack,
@@ -276,7 +287,9 @@ impl Game<'_> {
// Player.attack: the hurt (with its knockback away from the
// attacker), then causeExtraKnockback along the attacker's yaw.
let land = |g: &mut Self| {
g.combat.player_attacker = Some((s.from, s.disable_blocking));
let hurt = g.mob_hits_player(s.amount, s.from, "minecraft:player_attack");
g.combat.player_attacker = None;
let (strength, xd, zd) = s.knockback;
if hurt && strength > 0.0 {
g.knock_back_player(f64::from(strength), xd, zd);
@@ -317,6 +317,8 @@ impl Game<'_> {
self.as_guest(host, conn, |game| {
game.give_levels(-need);
game.stats.custom("enchant_item", 1);
// CriteriaTriggers.ENCHANTED_ITEM, with the levels it cost.
game.trigger_enchanted_item(&enchanted, need);
});
host.hub.guests[gi].xp_seed = self.world.random.next_int();
let env = self.menu_env();
@@ -1,8 +1,9 @@
//! Level events whose client handler (`LevelEventHandler`) spawns particles
//! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a
//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax
//! off (3004) and scraping (3005), plus the smoke, drips, egg and dragon
//! fireball particles of 1501, 1502, 1504, 2006, 2009, 2012 and 3009.
//! consumable's teleport (2017), an enderman's (2018), electric sparks (3002),
//! waxing (3003), wax off (3004) and scraping (3005), plus the smoke, drips,
//! egg and dragon fireball particles of 1501, 1502, 1504, 2006, 2009, 2012
//! and 3009.
use super::Game;
use horizon_client::items::ItemStack;
use horizon_client::particles::{self, ParticleOptions, ParticleType};
@@ -24,6 +25,11 @@ impl Game<'_> {
self.particles
.block_teleportation(pos, data, [127, 127, 127]);
}
/// Event 2018: an enderman's portal trail.
pub(super) fn enderman_teleport_particles(&mut self, pos: [i32; 3], data: i32) {
self.particles
.enderman_teleportation(pos, data, self.settings.particles);
}
/// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client
/// level's random.
pub(super) fn block_particle_event(&mut self, id: i32, pos: BlockPos, data: i32) {
@@ -40,7 +46,7 @@ impl Game<'_> {
// 3002 with an axis: a lightning rod; otherwise copper cleaned by lightning.
match usize::try_from(data) {
Ok(axis) if id == 3002 && axis < 3 => {
particles::along_axis(random, axis, p, |p, v| spawned.push((p, v)));
particles::along_axis(random, axis, p, (10, 19), |p, v| spawned.push((p, v)));
}
_ => particles::on_block_faces(random, p, |p, v| spawned.push((p, v))),
}
+95 -29
View File
@@ -37,6 +37,41 @@ pub(super) fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
|| m.species() == Species::Allay && m.extra.tame
}
/// A smash's knockback on the players, put off while a guest's turn holds
/// the other players.
pub(super) struct SmashPush {
center: Vec3,
heavy: f64,
attacker: Option<u32>,
team: Option<horizon_client::scoreboard::Team>,
}
/// `MaceItem.getKnockbackPower` and the push of one entity at `at`, `heavy`
/// being 2 after a fall of more than five blocks.
fn smash_push(center: Vec3, heavy: f64, at: Vec3, velocity: &mut Vec3, resistance: f64) {
let d = [at.x - center.x, at.y - center.y, at.z - center.z];
let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
return;
}
let length = distance_sqr.sqrt();
let power =
(KNOCKBACK_RADIUS - length) * f64::from(KNOCKBACK_POWER) * heavy * (1.0 - resistance);
if power <= 0.0 {
return;
}
// Vec3.normalize: a vector shorter than 1e-5 has no direction.
let (x, z) = if length < f64::from(1.0e-5f32) {
(0.0, 0.0)
} else {
(d[0] / length * power, d[2] / length * power)
};
*velocity = Vec3::new(
velocity.x + x,
velocity.y + f64::from(KNOCKBACK_POWER),
velocity.z + z,
);
}
impl Game<'_> {
fn holds_mace(&self) -> bool {
self.inventory[self.selected]
@@ -220,44 +255,75 @@ impl Game<'_> {
];
self.level_event_at(2013, on_pos, 750);
let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 };
// getKnockbackPower and the push of one entity at `at`.
let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| {
let d = [at.x - center.x, at.y - center.y, at.z - center.z];
let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
return;
}
let length = distance_sqr.sqrt();
let power = (KNOCKBACK_RADIUS - length)
* f64::from(KNOCKBACK_POWER)
* heavy
* (1.0 - resistance);
if power <= 0.0 {
return;
}
// Vec3.normalize: a vector shorter than 1e-5 has no direction.
let (x, z) = if length < f64::from(1.0e-5f32) {
(0.0, 0.0)
} else {
(d[0] / length * power, d[2] / length * power)
};
*velocity = Vec3::new(
velocity.x + x,
velocity.y + f64::from(KNOCKBACK_POWER),
velocity.z + z,
);
};
let player = self.level.player_uuid.or(Some([0, 0, 0, 1]));
for m in self
.mobs
.iter_mut()
.filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player))
{
push(m.position, &mut m.velocity, m.attrs.knockback_resistance);
smash_push(
center,
heavy,
m.position,
&mut m.velocity,
m.attrs.knockback_resistance,
);
}
for s in self.armor_stands.iter_mut().filter(|s| !s.marker) {
push(s.position, &mut s.velocity, 0.0);
smash_push(center, heavy, s.position, &mut s.velocity, 0.0);
}
// The host and the LAN guests are living entities too. A guest's turn
// holds the other players (`as_guest`): the push waits for it to end.
let push = SmashPush {
center,
heavy,
attacker: self.lan_acting,
team: self.player_team().cloned(),
};
if self.lan_acting.is_some() {
self.creatures.smash_pushes.push(push);
} else {
self.smash_push_players(&push);
}
}
/// `MaceItem.knockback` on the players but the attacker: the host unless
/// it attacked, and every guest but the attacker.
fn smash_push_players(&mut self, push: &SmashPush) {
if push.attacker.is_some() {
self.smash_push_player(push);
}
self.each_guest_hit_except(push.attacker, |g| g.smash_push_player(push));
}
/// The pushes guests' smashes put off.
pub(super) fn flush_smash_pushes(&mut self) {
for push in std::mem::take(&mut self.creatures.smash_pushes) {
self.smash_push_players(&push);
}
}
/// `MaceItem.knockback` on the player here (the host, or the guest swapped
/// in): not a spectator, an ally of the attacker (`isAlliedTo`: the same
/// team) or a creative player flying.
fn smash_push_player(&mut self, push: &SmashPush) {
if self.spectator()
|| horizon_client::scoreboard::teams_allied(push.team.as_ref(), self.player_team())
{
return;
}
let creative = self.creative;
let Some(p) = self.player.as_mut() else {
return;
};
if creative && p.flying {
return;
}
let resistance = p.attribute("minecraft:knockback_resistance").unwrap_or(0.0);
smash_push(
push.center,
push.heavy,
p.position,
&mut p.velocity,
resistance,
);
}
/// `ServerPlayer.checkFallDamage` after a smash on a grounded target:
/// the landing block's particles, 50 for every block fallen (200 at most).
+207 -45
View File
@@ -41,6 +41,8 @@ enum Kind {
Crafter,
/// `BrewingStandBlockEntity` (a `WorldlyContainer`).
Brewing,
/// `ChiseledBookShelfBlockEntity`: books only, one to a slot.
Bookshelf,
/// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder`
/// without a block entity): input below 7, empty at 7, bone meal at 8.
Composter(i32),
@@ -82,7 +84,7 @@ impl View {
}
}
fn dir_from_name(name: &str) -> Option<Direction> {
pub(super) fn dir_from_name(name: &str) -> Option<Direction> {
Some(match name {
"down" => Direction::Down,
"up" => Direction::Up,
@@ -169,6 +171,7 @@ impl Containers<'_> {
(BlockEntity::Furnace(_), _) => Kind::Furnace,
(BlockEntity::Crafter(_), _) => Kind::Crafter,
(BlockEntity::Brewing(_), _) => Kind::Brewing,
(BlockEntity::ChiseledBookshelf(_), _) => Kind::Bookshelf,
(_, "minecraft:hopper") => Kind::Hopper,
_ => Kind::Generic,
};
@@ -250,6 +253,16 @@ impl Containers<'_> {
_ => false,
};
}
if view.kind == Kind::Bookshelf {
// ListBackedContainer.canPlaceItem: `acceptsItemType` (the books)
// and a free slot, as `getMaxStackSize` is 1.
return self
.items
.item_tags
.get("minecraft:bookshelf_books")
.is_some_and(|m| m.contains(&*stack.item))
&& self.get(view, slot).is_none();
}
if view.kind == Kind::Brewing {
// BrewingStandBlockEntity.canPlaceItem
return match slot {
@@ -399,6 +412,45 @@ pub(super) fn container_signal(
.map_or(0, |v| c.signal(&v))
}
/// `ChiseledBookShelfBlock.getAnalogOutputSignal` and
/// `ShelfBlock.getAnalogOutputSignal`, from the block entity Horizon keeps as
/// it was loaded; `None` for any other block. `direction` points from the
/// block to the comparator.
pub(super) fn shelf_signal(
world: &World,
registry: &'static horizon_world::registry::BlockRegistry,
state: BlockStateId,
pos: BlockPos,
direction: Direction,
) -> Option<i32> {
let info = registry.state(state)?;
let chiseled = info.name == "minecraft:chiseled_bookshelf";
if !chiseled && !info.name.ends_with("_shelf") {
return None;
}
if chiseled {
// The last slot touched, plus one (`lastInteractedSlot` starts at -1).
return Some(match world.block_entities.get(&(pos.x, pos.y, pos.z)) {
Some(BlockEntity::ChiseledBookshelf(b)) => b.last_slot + 1,
_ => 0,
});
}
let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]);
// Only read from the back: a bit for each of the three slots in use.
let facing = info.properties.get("facing").and_then(|f| dir_from_name(f));
if facing.map(Direction::opposite) != Some(direction) {
return Some(0);
}
let items = horizon_client::save::decode_items(tag.as_ref().and_then(|t| t.get("Items")), 3);
Some(
items
.iter()
.enumerate()
.map(|(slot, item)| i32::from(item.is_some()) << slot)
.sum(),
)
}
impl Game<'_> {
fn containers(&self) -> Containers<'_> {
Containers {
@@ -433,6 +485,7 @@ impl Game<'_> {
if pos.1 == super::minecarts::CART_KEY_Y {
return;
}
self.chiseled_bookshelf_synced(pos);
// A double chest's other half changes with it.
let halves: Vec<Pos> = std::iter::once(pos)
.chain(self.chest_other_half(pos))
@@ -595,27 +648,41 @@ impl Game<'_> {
self.container_changed(pos);
}
}
/// `HopperBlockEntity.ejectItems`.
/// `HopperBlockEntity.ejectItems`: into the block container in front, else
/// a container entity there (`getContainerAt`).
fn hopper_eject(&mut self, pos: Pos, hopper: &View) -> bool {
let state = self.world.block(pos.0, pos.1, pos.2);
let c = self.containers();
let Some(facing) = c.prop(state, "facing").and_then(dir_from_name) else {
return false;
};
let Some(target) = c.view(offset(pos, facing), false) else {
let front = offset(pos, facing);
let face = facing.opposite();
if let Some(target) = c.view(front, false) {
return self.eject_into(pos, hopper, &target, face);
}
let Some(id) = self.entity_container_at([
f64::from(front.0) + 0.5,
f64::from(front.1) + 0.5,
f64::from(front.2) + 0.5,
]) else {
return false;
};
let face = facing.opposite();
if c.is_full(&target, face) {
self.with_entity_container(id, |g, target| g.eject_into(pos, hopper, target, face))
.unwrap_or(false)
}
/// The rest of `HopperBlockEntity.ejectItems`: one item into `target`.
fn eject_into(&mut self, pos: Pos, hopper: &View, target: &View, face: Direction) -> bool {
if self.containers().is_full(target, face) {
return false;
}
for slot in 0..hopper.len() {
let Some(one) = self.take_one(hopper, slot) else {
continue;
};
match self.add_item(Some(pos), &target, one, Some(face)) {
match self.add_item(Some(pos), target, one, Some(face)) {
None => {
self.view_changed(&target);
self.view_changed(target);
return true;
}
Some(rest) => self.put_back(hopper, slot, rest),
@@ -626,7 +693,12 @@ impl Game<'_> {
/// `HopperBlockEntity.suckInItems`: from the container above, or item entities.
fn hopper_suck(&mut self, pos: Pos, hopper: &View) -> bool {
let above = (pos.0, pos.1 + 1, pos.2);
if let Some(took) = self.suck_from_container(above, hopper) {
let at = [
f64::from(pos.0) + 0.5,
f64::from(pos.1) + 1.5,
f64::from(pos.2) + 0.5,
];
if let Some(took) = self.suck_from_container(above, at, hopper) {
return took;
}
let above_state = self.world.block(above.0, above.1, above.2);
@@ -660,11 +732,16 @@ impl Game<'_> {
self.suck_item_entities(hopper, min, max)
}
/// The container half of `HopperBlockEntity.suckInItems`: one item from the
/// container at `above`, through its bottom face. `None` when there is no
/// container there.
fn suck_from_container(&mut self, above: Pos, hopper: &View) -> Option<bool> {
/// container at `above`, through its bottom face; with no block container
/// there, from a container entity whose box meets the one around `at`
/// (`getSourceContainerOrHandler`). `None` when there is no container.
fn suck_from_container(&mut self, above: Pos, at: [f64; 3], hopper: &View) -> Option<bool> {
let c = self.containers();
let source = c.view(above, false)?;
let Some(source) = c.view(above, false) else {
let id = self.entity_container_at(at)?;
return self
.with_entity_container(id, |g, source| g.suck_from_slots(None, source, hopper));
};
if let Kind::Composter(level) = source.kind {
if level != 8 {
return Some(false);
@@ -683,26 +760,133 @@ impl Game<'_> {
return Some(moved);
}
let source_hopper = (source.kind == Kind::Hopper).then_some(above);
Some(self.suck_from_slots(source_hopper, &source, hopper))
}
/// `HopperBlockEntity.tryTakeInItemFromSlot` over the `DOWN` face of `source`.
fn suck_from_slots(
&mut self,
source_hopper: Option<Pos>,
source: &View,
hopper: &View,
) -> bool {
for slot in source.slots_for_face(Some(Direction::Down)) {
let c = self.containers();
let Some(stack) = c.get(&source, slot) else {
let Some(stack) = c.get(source, slot) else {
continue;
};
if !c.can_take(&source, slot, stack, Direction::Down) {
if !c.can_take(source, slot, stack, Direction::Down) {
continue;
}
let Some(one) = self.take_one(&source, slot) else {
let Some(one) = self.take_one(source, slot) else {
continue;
};
match self.add_item(source_hopper, hopper, one, None) {
None => {
self.view_changed(&source);
return Some(true);
self.view_changed(source);
return true;
}
Some(rest) => self.put_back(&source, slot, rest),
Some(rest) => self.put_back(source, slot, rest),
}
}
Some(false)
false
}
/// `HopperBlockEntity.getEntityContainer`: one of the alive container
/// entities (`EntitySelector.CONTAINER_ENTITY_SELECTOR`: chest and hopper
/// minecarts, chest boats) whose box meets the 1x1x1 box around `at`,
/// picked at random.
fn entity_container_at(&mut self, at: [f64; 3]) -> Option<u32> {
let meets = |b: horizon_core::geometry::Aabb| {
let (lo, hi) = (b.min_position(), b.max_position());
lo.x < at[0] + 0.5
&& hi.x > at[0] - 0.5
&& lo.y < at[1] + 0.5
&& hi.y > at[1] - 0.5
&& lo.z < at[2] + 0.5
&& hi.z > at[2] - 0.5
};
let mut found: Vec<u32> = self
.carts
.iter()
.filter(|c| {
matches!(
c.kind,
super::minecarts::CartKind::Chest | super::minecarts::CartKind::Hopper
) && meets(c.bounds())
})
.map(|c| c.id)
.collect();
found.extend(
self.boats
.iter()
.filter(|b| b.chest && meets(b.bounds()))
.map(|b| b.id),
);
if found.is_empty() {
return None;
}
let pick = self
.world
.random
.next_int_bound(found.len() as i32)
.unwrap_or(0);
found.get(pick as usize).copied()
}
/// Runs `f` on a container entity's items as a container, under the
/// placeholder key its menu uses (the open menu's copy when it is open),
/// then hands the items back to the entity.
fn with_entity_container<R>(
&mut self,
id: u32,
f: impl FnOnce(&mut Self, &View) -> R,
) -> Option<R> {
let mut items = if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
std::mem::take(&mut c.items)
} else {
std::mem::take(&mut self.boats.iter_mut().find(|b| b.id == id)?.items)
};
let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, id as i32);
let (view, open) = self.lend_items(key, &mut items);
let result = f(self, &view);
self.reclaim_items(key, open, &mut items);
if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) {
c.items = items;
} else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) {
b.items = items;
}
Some(result)
}
/// A vehicle's slots as a container under its placeholder `key`. When its
/// menu is open the placeholder is the live copy and stays as it is.
/// Returns the view and whether the menu was open.
fn lend_items(&mut self, key: Pos, items: &mut Vec<Option<ItemStack>>) -> (View, bool) {
let open = self.world.block_entities.contains_key(&key);
if !open {
let slots = BlockEntity::Chest(std::mem::take(items));
self.world.block_entities.insert(key, slots);
}
let size = self
.world
.block_entities
.get(&key)
.map_or(0, |e| e.slots().len());
let view = View {
parts: vec![(key, size)],
kind: Kind::Generic,
};
(view, open)
}
/// Gives `lend_items`' slots back to the vehicle, so its own items stay
/// the one source of truth: a menu copy that is still around (open, or
/// left by a guest's close) gets the changed items copied to `items`.
fn reclaim_items(&mut self, key: Pos, open: bool, items: &mut Vec<Option<ItemStack>>) {
let slots = if open {
self.world.block_entities.get(&key).cloned()
} else {
self.world.block_entities.remove(&key)
};
if let Some(BlockEntity::Chest(slots)) = slots {
*items = slots;
}
}
/// The item half of `HopperBlockEntity.suckInItems` (`getItemsAtAndAbove`):
/// adds the item entities that meet the box, until one is taken whole.
@@ -738,20 +922,7 @@ impl Game<'_> {
// The cart's slots are edited as a container under the placeholder key
// its menu uses; when that menu is open the placeholder is the live copy.
let key = (i32::MAX - 15, super::minecarts::CART_KEY_Y, cart.id as i32);
let open = self.world.block_entities.contains_key(&key);
if !open {
let items = BlockEntity::Chest(std::mem::take(&mut cart.items));
self.world.block_entities.insert(key, items);
}
let size = self
.world
.block_entities
.get(&key)
.map_or(0, |e| e.slots().len());
let view = View {
parts: vec![(key, size)],
kind: Kind::Generic,
};
let (view, open) = self.lend_items(key, &mut cart.items);
let p = cart.position;
// getLevelY is the cart's y + 0.5, so the container is the block at
// y + 1.5, and Hopper.SUCK_AABB (moved by getLevel - 0.5) starts 11/16
@@ -761,7 +932,8 @@ impl Game<'_> {
(p.y + 1.5).floor() as i32,
p.z.floor() as i32,
);
let took = match self.suck_from_container(above, &view) {
let at = [p.x, p.y + 1.5, p.z];
let took = match self.suck_from_container(above, at, &view) {
Some(took) => took,
None => self.suck_item_entities(
&view,
@@ -779,17 +951,7 @@ impl Game<'_> {
[hi.x + 0.25, hi.y, hi.z + 0.25],
);
}
// The cart's own items stay the one source of truth: a menu copy that
// is still around (open, or left by a guest's close) gets the pulled
// items back into `cart.items`, so reopening never restores a stale copy.
let slots = if open {
self.world.block_entities.get(&key).cloned()
} else {
self.world.block_entities.remove(&key)
};
if let Some(BlockEntity::Chest(items)) = slots {
cart.items = items;
}
self.reclaim_items(key, open, &mut cart.items);
}
// ---- dispensers and droppers ----
+89 -3
View File
@@ -721,6 +721,93 @@ impl Game<'_> {
self.swing_arm();
true
}
/// `CompassItem.useOn`: a compass used on a lodestone locks onto it (a
/// single one in survival changes in place, else one is split off).
pub(super) fn use_lodestone_compass(&mut self, hit: &super::Hit, stack: &ItemStack) -> bool {
if &*stack.item != "minecraft:compass" {
return false;
}
let [x, y, z] = hit.pos;
if self
.res
.facts()
.get(self.world.block(x, y, z))
.name
.as_ref()
!= "minecraft:lodestone"
{
return false;
}
let at = [x, y, z].map(|v| f64::from(v) + 0.5);
self.audio
.play("minecraft:item.lodestone_compass.lock", Some(at), 1.0, 1.0);
let target = Tag::compound([(
"target",
Tag::compound([
("dimension", Tag::String(self.dimension_id().into())),
("pos", Tag::IntArray(vec![x, y, z])),
]),
)]);
if !self.creative && stack.count == 1 {
if let Some(held) = self.held_mut() {
held.data_mut()
.set_other("minecraft:lodestone_tracker", Some(target));
}
} else {
let mut locked = stack.clone();
locked.count = 1;
locked
.data_mut()
.set_other("minecraft:lodestone_tracker", Some(target));
self.consume_held();
self.give_or_drop_stack(locked);
}
self.stats.add("used", &stack.item, 1);
self.swing_arm();
true
}
/// `CompassItem.inventoryTick` / `LodestoneTracker.tick`: a compass whose
/// lodestone is gone loses its target. A target in an unloaded chunk waits.
pub(super) fn tick_lodestone_compasses(&mut self) {
let dim = self.dimension_id();
let gone = |game: &Self, stack: &ItemStack| -> bool {
let Some(tracker) = stack
.data()
.and_then(|d| d.other("minecraft:lodestone_tracker"))
else {
return false;
};
let (Some(target), true) = (
tracker.get("target"),
horizon_client::save::number(tracker.get("tracked")).is_none_or(|v| v != 0),
) else {
return false;
};
let Some(Tag::IntArray(pos)) = target.get("pos") else {
return false;
};
let [x, y, z] = [pos[0], pos[1], pos[2]];
horizon_client::save::text(target.get("dimension")).as_deref() == Some(dim)
&& game.world.chunks.contains_key(&(x >> 4, z >> 4))
&& game
.res
.facts()
.get(game.world.block(x, y, z))
.name
.as_ref()
!= "minecraft:lodestone"
};
for slot in (0..self.inventory.len()).chain([super::shield::OFFHAND_SLOT]) {
if self.stack_in(slot).is_some_and(|s| gone(self, s))
&& let Some(s) = self.stack_in_mut(slot)
{
s.data_mut().set_other(
"minecraft:lodestone_tracker",
Some(Tag::Compound(Default::default())),
);
}
}
}
fn give_or_drop_stack(&mut self, stack: ItemStack) {
if let Some(rest) = self.give(stack)
&& let Some(eye) = self.eye_position()
@@ -781,9 +868,8 @@ impl Game<'_> {
(d * 2.0 + 0.5) as i8
}
};
let y = f64::from(yaw);
let adjusted = if y < 0.0 { y - 8.0 } else { y + 8.0 };
let rot = ((adjusted * 16.0 / 360.0) as i32 & 15) as u8;
// calculateRotation: the arrow spins in the Nether.
let rot = decoration_rotation(nether, game_time, f64::from(yaw));
let sprite = if inside {
Some("map/decorations/player")
} else if dx.abs() < 320.0 && dz.abs() < 320.0 {
+7 -5
View File
@@ -386,13 +386,15 @@ impl Game<'_> {
owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item;
owner.crossbow_charge_duration = 25;
}
let context = if left {
horizon_assets::item_model::DisplayContext::ThirdPersonLeftHand
} else {
horizon_assets::item_model::DisplayContext::ThirdPersonRightHand
use horizon_assets::item_model::DisplayContext as Context;
// PandaHoldsItemLayer shows the item as it lies on the ground.
let (context, ordinal) = match (mob.species(), left) {
(Species::Panda, _) => (Context::Ground, 7),
(_, true) => (Context::ThirdPersonLeftHand, 1),
(_, false) => (Context::ThirdPersonRightHand, 2),
};
// `updateForLiving`: seeded by the entity id plus the context ordinal.
let seed = mob.id as i32 + if left { 1 } else { 2 };
let seed = mob.id as i32 + ordinal;
let state = self.resolve_item(&stack, context, Some(&owner), seed);
if lit {
self.submit_item_world(&state, t, light, out);
+15 -8
View File
@@ -273,10 +273,7 @@ impl Game<'_> {
/// `LocalPlayer.aiStep`'s riding jump: the bar charges while jump is
/// held; on release, the jump's strength (0 when there is none).
pub(super) fn charge_mount_jump(&mut self, i: usize, keys: Keys) -> f32 {
// PlayerRideableJumping: horses, camels and nautili (the dash).
let saddled = self.mobs[i].extra.saddled
&& (equine::is_equine(self.mobs[i].species())
|| horizon_client::mobs::nautilus::is_nautilus(self.mobs[i].species()));
let saddled = self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species());
let mut jump = 0.0;
if saddled {
let st = &mut self.mount;
@@ -485,10 +482,15 @@ impl Game<'_> {
_ => {}
}
}
/// `Player.jumpableVehicle`: a saddled mount that jumps.
/// `PlayerRideableJumping`: horses, camels and nautili (the dash).
fn jumps(species: Species) -> bool {
equine::is_equine(species) || horizon_client::mobs::nautilus::is_nautilus(species)
}
/// `Player.jumpableVehicle`: a saddled mount that jumps (not a pig or a
/// strider, which a saddle only steers).
pub(super) fn jumpable_mount(&self) -> bool {
self.mount_index()
.is_some_and(|i| self.mobs[i].extra.saddled)
.is_some_and(|i| self.mobs[i].extra.saddled && Self::jumps(self.mobs[i].species()))
}
/// `willPrioritizeJumpInfo`: charging a jump or recharging.
pub(super) fn mount_jumping(&self) -> bool {
@@ -513,8 +515,13 @@ impl Game<'_> {
let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health);
horizon_client::hud_layout::paint(batch, atlas, &draws);
if jump_bar {
// JumpableVehicleBar: the cooldown shows while the jump recharges.
let cooldown = i32::from(self.mount.jump_ticks < 0);
// JumpableVehicleBar: `getJumpCooldown`, which only the camel's and
// the nautilus' dash have; a horse always shows the progress.
let cooldown = i32::from(
self.mount.jump_ticks < 0
&& (matches!(m.species(), Species::Camel | Species::CamelHusk)
|| horizon_client::mobs::nautilus::is_nautilus(m.species())),
);
let draws =
horizon_client::hud_overlays::jump_bar(w, h, cooldown, self.mount.jump_scale);
horizon_client::hud_layout::paint(batch, atlas, &draws);
@@ -662,6 +662,17 @@ impl Game<'_> {
);
}
}
/// `Entity.setPortalCooldown` on an entity that has just spawned in a
/// portal: it stands in the portal for 300 ticks without going through.
pub(super) fn set_portal_cooldown(&mut self, id: u32) {
self.portals.entities.insert(
id,
PortalState {
cooldown: ENTITY_DELAY,
process: None,
},
);
}
/// `canUsePortal(false)` of a mob: alive, riding nothing, not asleep,
/// not carrying the player, and not a boss that never travels.
fn mob_can_use_portal(&self, m: &horizon_client::mobs::Mob) -> bool {
+165
View File
@@ -0,0 +1,165 @@
//! Pandas on the game side: the food they find on the ground and pick up
//! (`Mob.aiStep`, `Panda.pickUpItem`), the bamboo a player gives them
//! (`Panda.mobInteract`), the start a sneeze gives the grown pandas about,
//! and the crumbs and the sneeze a window draws.
use super::{
Game,
pickups::{Collector, Taken},
};
use horizon_client::{
items::ItemStack,
mobs::{Species, panda},
particles::{ParticleOptions, ParticleType},
};
use horizon_core::geometry::Vec3;
impl Game<'_> {
/// `Panda.canPickUpAndEat`'s tag.
fn panda_eats_from_ground(&self, item: &str) -> bool {
self.res
.items()
.item_tags
.get("minecraft:panda_eats_from_ground")
.is_some_and(|tag| tag.contains(item))
}
/// A panda takes what lies at its feet when its mouth is free, and
/// looks for food within 6 and 8 blocks for `PandaSitGoal`.
pub(super) fn tick_pandas(&mut self) {
let griefing = self.ui.rules.bool("mob_griefing");
for i in 0..self.mobs.len() {
let m = &self.mobs[i];
if m.species() != Species::Panda || !m.alive() {
continue;
}
let id = m.id;
let wants = |g: &Self, e: &horizon_client::entities::ItemEntity| {
e.pickup_delay == 0 && g.panda_eats_from_ground(&e.stack.item)
};
// Mob.aiStep: the items within the box grown by (1, 0, 1).
if griefing && m.can_pick_up_loot() && m.extra.main_hand.is_none() {
let reach = m.bounds().inflate(Vec3::new(1.0, 0.0, 1.0));
let taken = self
.dropped
.iter()
.position(|e| wants(self, e) && reach.intersects(e.bounds()));
if let Some(j) = taken {
let e = self.dropped.remove(j);
self.add_pickup(Taken::Item(Box::new(e.clone())), Collector::Mob(id));
panda::hold(&mut self.mobs[i], &e.stack.item, e.stack.count, true);
}
}
let m = &self.mobs[i];
let area = |r: f64| m.bounds().inflate(Vec3::new(r, r, r));
let (near, wide) = (area(6.0), area(8.0));
let food_near = self
.dropped
.iter()
.any(|e| wants(self, e) && near.intersects(e.bounds()));
let food_at = self
.dropped
.iter()
.find(|e| wants(self, e) && wide.intersects(e.bounds()))
.map(|e| [e.position.x, e.position.y, e.position.z]);
panda::set_food(&mut self.mobs[i], food_near, food_at);
}
}
/// `Panda.mobInteract` for a click with `item`; whether the click is taken.
pub(super) fn interact_panda(&mut self, index: usize, item: &str) -> bool {
let creative = self.creative;
let m = &mut self.mobs[index];
if panda::scared(m) {
return false;
}
if panda::get_up(m) {
return true;
}
if !m.kind.food.iter().any(|f| f == item) {
return false;
}
if m.ai.target.is_some() {
panda::got_bamboo(m);
}
let at = [m.position.x, m.position.y, m.position.z];
let mut dropped = None;
if m.is_baby() {
// ageUp((int) (-getAge() / 20 * 0.1F), true).
let seconds = ((-m.extra.age / 20) as f32 * 0.1) as i32;
horizon_client::mobs::ai::age_up(m, seconds, true);
} else if m.extra.age == 0 && m.extra.in_love <= 0 {
m.extra.in_love = 600;
m.extra.love_player = true;
} else {
if panda::is_sitting(m) || m.fluids.in_water {
return false;
}
panda::try_to_sit(m);
panda::start_eating(m);
// What it held falls, unless the player has infinite materials.
if let Some(held) = m.extra.main_hand.clone()
&& !creative
{
dropped = Some(ItemStack::new(&held, panda::held_count(m)));
}
panda::hold(m, item, 1, false);
}
self.consume_held();
if let Some(stack) = dropped {
self.spawn_item(stack, at, [0.0, 0.2, 0.0], 10);
}
true
}
/// `Panda.afterSneeze`: the grown pandas within 10 blocks of a cub jump.
pub(super) fn panda_sneezed(&mut self, id: u32) {
let Some(area) = self
.mobs
.iter()
.find(|m| m.id == id)
.map(|m| m.bounds().inflate(Vec3::new(10.0, 10.0, 10.0)))
else {
return;
};
for m in &mut self.mobs {
if m.species() == Species::Panda
&& !m.is_baby()
&& m.on_ground
&& !m.fluids.in_water
&& panda::can_perform_action(m, panda::scared(m))
&& area.intersects(m.bounds())
{
// LivingEntity.jumpFromGround.
m.needs_sync = true;
let power = f64::from(m.jump_power());
if power > 1.0e-5 {
m.velocity.y = power.max(m.velocity.y);
}
}
}
}
/// What a window draws of its pandas: the crumbs of a bite
/// (`addEatingParticles`) and the sneeze's particle.
pub(super) fn panda_effects(&mut self) {
let mut bites = Vec::new();
let mut sneezes = Vec::new();
for m in self
.mobs
.iter_mut()
.filter(|m| m.species() == Species::Panda)
{
let (crumbs, sneeze) = panda::effects(m);
if let (Some(crumbs), Some(item)) = (crumbs, m.extra.main_hand.clone()) {
bites.push((item, crumbs));
}
sneezes.extend(sneeze);
}
for (item, crumbs) in bites {
let options = self.item_particle(&ItemStack::new(&item, 1));
for (at, velocity) in crumbs {
self.particles.add(&options, at, velocity);
}
}
let options = ParticleOptions::simple(ParticleType::Sneeze);
for (at, velocity) in sneezes {
self.particles.add(&options, at, velocity);
}
}
}
@@ -0,0 +1,98 @@
//! Pick Block on an entity (`Minecraft.pickBlockOrEntity`'s entity case and
//! `ServerGamePacketListenerImpl.handlePickItemFromEntity`): the client aims,
//! the server answers with `Entity.getPickResult`.
use super::Game;
use horizon_client::items::ItemStack;
impl Game<'_> {
/// The entity the crosshair hits before any block, as `Entity.getId`; an
/// entity with nothing to pick (a projectile, a player, the dragon) is
/// `Some(None)`. `None` when the view hits a block or nothing.
pub(super) fn pick_entity_hit(&self) -> Option<Option<i32>> {
let mut best: Option<(f64, Option<i32>)> = None;
let mut offer = |distance: f64, id: Option<i32>| {
if self.before_block(distance) && best.is_none_or(|b| distance < b.0) {
best = Some((distance, id));
}
};
if let Some(hit) = self.remote_object_hit(true) {
offer(hit.distance, Some(hit.id));
}
if let Some((i, d)) = self.mob_hit() {
offer(d, Some(self.mobs[i].id as i32));
}
if let Some((_, d)) = self.guest_hit() {
offer(d, None);
}
if let Some((_, d)) = self.redirectable_hit() {
offer(d, None);
}
if let Some((_, d)) = self.dragon_hit() {
offer(d, None);
}
best.map(|b| b.1)
}
/// `Entity.getPickResult` of the entity `id`: a mob's spawn egg, the item
/// of a boat, minecart, armor stand, cushion, painting, item frame (the
/// framed item when it holds one) or end crystal.
pub(super) fn entity_pick_result(&self, id: i32) -> Option<ItemStack> {
let id = u32::try_from(id).ok()?;
let item = if let Some(m) = self.mobs.iter().find(|m| m.id == id) {
// Mob.getPickResult: SpawnEggItem.byId.
let egg = format!("{}_spawn_egg", m.kind.id);
return self.res.items().get(&egg).map(|_| ItemStack::new(&egg, 1));
} else if let Some(b) = self.boats.iter().find(|b| b.id == id) {
b.entity_type()
} else if let Some(c) = self.carts.iter().find(|c| c.id == id) {
c.kind.id().to_owned()
} else if self.armor_stands.iter().any(|a| a.id == id) {
"minecraft:armor_stand".to_owned()
} else if let Some(c) = self.cushions.iter().find(|c| c.id == id) {
c.item()
} else if let Some(f) = self.item_frames.iter().find(|f| f.id == id) {
// ItemFrame.getPickResult: what it frames, else the frame itself.
return Some(
f.item
.clone()
.unwrap_or_else(|| ItemStack::new(f.kind(), 1)),
);
} else if self.paintings.iter().any(|p| p.id == id) {
"minecraft:painting".to_owned()
} else if self.crystals.iter().any(|c| c.id == id) {
"minecraft:end_crystal".to_owned()
} else {
return None;
};
Some(ItemStack::new(&item, 1))
}
/// `Player.isWithinEntityInteractionRange(entity, 3.0)`: the entity's box
/// within the interaction range plus 3 of the eyes.
pub(super) fn within_entity_range(&self, id: i32) -> bool {
let Some(eye) = self.eye_position() else {
return false;
};
let mob = u32::try_from(id)
.ok()
.and_then(|id| self.mobs.iter().find(|m| m.id == id))
.map(|m| m.bounds());
let Some(b) = self
.object_target(id)
.map(|(lo, hi, _)| (lo, hi))
.or_else(|| {
mob.or_else(|| self.tracked_special_box(id)).map(|b| {
let (lo, hi) = (b.min_position(), b.max_position());
([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z])
})
})
else {
return false;
};
let d2: f64 = (0..3)
.map(|a| (eye[a] - eye[a].clamp(b.0[a], b.1[a])).powi(2))
.sum();
let range = if self.creative { 5.0 } else { 3.0 } + 3.0;
d2 < range * range
}
}
+21 -2
View File
@@ -1215,9 +1215,28 @@ impl Game<'_> {
}
}
}
/// `Hud.extractEffects`: icons top-right, beneficial row then harmful row.
/// `Screen.showsActiveEffects`: the survival and creative inventories
/// draw their own effect list when `EffectsInInventory.canSeeEffects`
/// (32 or more pixels right of the screen).
fn screen_shows_active_effects(&self, batch: &HudBatch) -> bool {
let (ox, image_width) = match self.screen {
Screen::Inventory
if self.container.is_none() && self.craft_size == 2 && !self.mount_active() =>
{
(self.inventory_origin(batch).0, 176)
}
Screen::Creative => (
Self::creative_origin(batch).0,
horizon_client::creative::Creative::WIDTH as i32,
),
_ => return false,
};
batch.width as i32 - (ox as i32 + image_width + 2) >= 32
}
/// `Hud.extractEffects`: icons top-right, beneficial row then harmful row;
/// every screen but the inventories keeps them.
pub(super) fn draw_effect_icons(&self, batch: &mut HudBatch) {
if self.screen != Screen::Playing || self.potions.effects.list.is_empty() {
if self.potions.effects.list.is_empty() || self.screen_shows_active_effects(batch) {
return;
}
let icons: Vec<hud_overlays::EffectIcon> = self
+5 -8
View File
@@ -821,14 +821,11 @@ impl Game<'_> {
if !alive {
continue;
}
// Raider.updateNoActionTime adds two per tick, and a raider
// fighting a player or golem in a raid is never idle.
if s.raid_id.is_some() {
m.ai.no_action_time = if target_player || target_golem {
0
} else {
m.ai.no_action_time + 1
};
// Raider.aiStep: a raider fighting a player or golem in a raid is
// never idle. The per-tick growth (+1 serverAiStep, +2
// Raider.updateNoActionTime) is added by the mob's own step.
if s.raid_id.is_some() && (target_player || target_golem) {
m.ai.no_action_time = 0;
}
// Raider.aiStep: join the raid the raider stands in.
if s.raid_id.is_none()
+133 -14
View File
@@ -119,7 +119,7 @@ pub(super) struct Remote {
pub(super) entity_id: i32,
/// The item the player's use began with (`LivingEntity.useItem`).
pub(super) use_item: Option<Arc<str>>,
dimension: DimensionType,
pub(super) dimension: DimensionType,
/// What chunk packets decode with (the dimension's height and sky, the
/// biome registry); replaced whenever one of them changes.
pub(super) chunk_format: Arc<ChunkFormat>,
@@ -194,6 +194,8 @@ pub(super) struct Remote {
/// The local player's profile name: its score holder and team member.
pub(super) profile_name: String,
destroying: Option<([i32; 3], u8, f32)>,
/// `MultiPlayerGameMode.destroyingItem`: the held item key the break began with.
destroying_item: String,
destroy_delay: u32,
input: horizon_client::interaction_input::InteractionInput,
/// Keys whose presses send a packet (swap hands, drop, a mount's
@@ -202,6 +204,8 @@ pub(super) struct Remote {
pub(super) pending_keys: Vec<KeyCode>,
stop_mining: bool,
placing: Option<([i32; 3], u64)>,
/// `CommonPlayerSpawnInfo.isFlat`: the level is a superflat one.
pub(super) flat: bool,
death_message: Option<String>,
/// `LocalPlayer.showDeathScreen`: off with `immediate_respawn`.
show_death_screen: bool,
@@ -492,11 +496,13 @@ impl Game<'_> {
profile: 0,
profile_name: String::new(),
destroying: None,
destroying_item: String::new(),
destroy_delay: 0,
input: Default::default(),
pending_keys: Vec::new(),
stop_mining: false,
placing: None,
flat: false,
death_message: None,
show_death_screen: true,
player_type,
@@ -1018,6 +1024,7 @@ impl Game<'_> {
r.chunk_format = Arc::new(r.chunk_format.with_dimension(&dimension));
r.dimension = dimension;
r.game_mode = spawn.game_type;
r.flat = spawn.flat;
r.loaded_sent = false;
// A replacement LocalPlayer has a fresh sendPosition baseline.
r.position_sender = Default::default();
@@ -1647,6 +1654,41 @@ impl Game<'_> {
}
}
/// `ClientPacketListener.handleUpdateAttributes` for a mob: its maximum
/// health (the hearts drawn over its mount) takes the server's value, from
/// `AttributeInstance.calculateValue`.
fn remote_mob_attributes(&mut self, id: i32, values: &[play::AttributeSnapshot]) {
let catalog = &self.motion.attributes;
let Some(max_health) = catalog.id("minecraft:max_health") else {
return;
};
let Some(s) = values
.iter()
.find(|s| s.attribute == max_health.registry_id())
else {
return;
};
let amounts = |op: i32| {
s.modifiers
.iter()
.filter(move |m| m.operation == op)
.map(|m| m.amount)
};
let base = s.base + amounts(0).sum::<f64>();
let mut value = base + amounts(1).map(|a| base * a).sum::<f64>();
for amount in amounts(2) {
value *= 1.0 + amount;
}
let value = catalog.attribute(max_health).definition.sanitize(value);
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
horizon_client::mobs::finalize::set_base(
m,
horizon_client::mobs::finalize::Attr::MaxHealth,
value,
);
}
}
fn handle_packet(&mut self, packet: C) -> Result<()> {
match packet {
// ClientCommonPacketListenerImpl.handlePing runs on the game
@@ -2338,6 +2380,7 @@ impl Game<'_> {
}
self.apply_remote_health();
}
C::UpdateAttributes(p) => self.remote_mob_attributes(p.id, &p.values),
C::UpdateMobEffect(p) => self.remote_effect(&p),
C::RemoveMobEffect(p) => {
if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id)
@@ -2513,6 +2556,20 @@ impl Game<'_> {
r.state_id = p.state;
}
let stack = self.to_stack(&p.item);
// ClientPacketListener.handleContainerSetSlot: a hotbar slot that
// gains items squeezes for 5 ticks.
if p.container == 0
&& (36..=45).contains(&p.slot)
&& let Some(new) = &stack
{
let (pop, old) = match p.slot {
45 => (9, self.offhand.as_ref()),
s => (s as usize - 36, self.inventory[s as usize - 36].as_ref()),
};
if old.is_none_or(|old| old.count < new.count) {
self.hotbar_pop[pop] = 5;
}
}
self.set_menu_slot(p.container, i32::from(p.slot), stack);
self.remote_synced();
}
@@ -3405,10 +3462,15 @@ impl Game<'_> {
// a client. Ticking it after the keybinds keeps a held use from
// trying again a tick before the server's entry ends.
self.cooldowns.tick();
// Inventory.tick's ItemStack.inventoryTick: the pop time runs down.
for pop in &mut self.hotbar_pop {
*pop = pop.saturating_sub(1);
}
// ClientLevel.tick: the border's size change.
self.border.tick();
self.player_border();
self.tick_remote_entities(running);
self.tick_remote_guardian_eyes(running);
// ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells,
// and the moving pistons a block event's client-side moveBlocks made
// (their progress advances between the server's block updates).
@@ -3546,12 +3608,10 @@ impl Game<'_> {
let feet = [player.position.x, player.position.y, player.position.z];
for event in events {
match event {
horizon_client::motion::MotionEvent::Emission {
state, in_water, ..
} => {
horizon_client::motion::MotionEvent::Emission { state, muffled, .. } => {
let sounds = self.res.facts().get(state).sounds.clone();
// Player.playStepSound: muffled under the swim sound in water.
let (volume, pitch) = if in_water {
let (volume, pitch) = if muffled {
(sounds.volume * 0.05, sounds.pitch * 0.8)
} else {
(sounds.volume * 0.15, sounds.pitch)
@@ -3712,6 +3772,43 @@ impl Game<'_> {
}
/// ClientLevel.tickEntities; a frozen level only ticks the players
/// (`TickRateManager.isEntityFrozen`).
/// `GuardianRenderer.getEntityToLookAt`: a guardian's eye follows its
/// synched attack target, else the camera.
fn tick_remote_guardian_eyes(&mut self, running: bool) {
use horizon_client::mobs::{Species, Who, guardian};
if !running {
return;
}
let camera = self.player.as_ref().map(|p| {
[
p.position.x,
p.position.y + f64::from(p.dimensions.eye_height),
p.position.z,
]
});
let looks: Vec<_> = self
.mobs
.iter()
.enumerate()
.filter(|(_, m)| {
matches!(m.species(), Species::Guardian | Species::ElderGuardian) && m.alive()
})
.filter_map(|(i, m)| {
let look = match m.ai.target.filter(|_| m.extra.flag) {
Some(Who::Mob(id)) => self
.mobs
.iter()
.find(|t| t.id == id)
.map(|t| [t.position.x, t.eye_y(), t.position.z]),
_ => camera,
};
look.map(|look| (i, look))
})
.collect();
for (i, look) in looks {
guardian::look_at(&mut self.mobs[i], look);
}
}
fn tick_remote_entities(&mut self, running: bool) {
if running {
self.tick_text_displays();
@@ -3720,16 +3817,18 @@ impl Game<'_> {
// server never sends the fluid contact, and the renderers read it (cod, salmon and
// tropical fish lie on their side without `in_water`, #1591).
// A frozen level ticks only the players, as below.
let fluids: Vec<_> = {
let (fluids, thundering): (Vec<_>, bool) = {
let w = self.mob_world_base(&[]);
let players = self.remote.as_ref().map(|r| &r.level_players);
self.mobs
let fluids = self
.mobs
.iter()
.map(|m| {
(running || players.is_some_and(|p| p.contains_key(&(m.id as i32))))
.then(|| w.fluids(m.bounds(), m.eye_y()))
})
.collect()
.collect();
(fluids, w.thundering)
};
for (m, fluids) in self.mobs.iter_mut().zip(fluids) {
if let Some(fluids) = fluids {
@@ -3811,6 +3910,10 @@ impl Game<'_> {
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
*steps -= 1;
}
// Fox.tick: the head tilt and crouch follow the synched flags.
if m.species() == horizon_client::mobs::Species::Fox {
horizon_client::mobs::fox::client_tick(m);
}
// Chicken.aiStep: the wings follow the server's on-ground flag.
if m.species() == horizon_client::mobs::Species::Chicken {
horizon_client::mobs::farm::chicken_flap(m);
@@ -3862,6 +3965,9 @@ impl Game<'_> {
}
// The animation states a server computes in its own `ai_step`.
horizon_client::mobs::sync::client_tick(m, game_time);
if m.species() == horizon_client::mobs::Species::Panda {
horizon_client::mobs::panda::client_tick(m, thundering);
}
}
for o in self.orbs.iter_mut().filter(|_| running) {
o.previous = o.position;
@@ -4065,6 +4171,8 @@ impl Game<'_> {
}
}
/// `MultiPlayerGameMode.stopDestroyBlock`: aborts the break and starts
/// the attack strength again.
pub(super) fn stop_remote_mining(&mut self) {
if let Some((pos, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) {
self.send(S::PlayerAction(play::PlayerAction {
@@ -4073,6 +4181,7 @@ impl Game<'_> {
direction: 0,
sequence: 0,
}));
self.reset_attack_strength();
}
}
@@ -4126,11 +4235,11 @@ impl Game<'_> {
} else {
self.destroy_progress(hit.pos)
};
let same = self
.remote
.as_ref()
.and_then(|r| r.destroying)
.is_some_and(|(p, _, _)| p == hit.pos);
// sameDestroyTarget: the same block and still the item the break began with.
let held = self.main_hand_key();
let same = self.remote.as_ref().is_some_and(|r| {
r.destroying.is_some_and(|(p, _, _)| p == hit.pos) && r.destroying_item == held
});
if start && same {
return;
}
@@ -4157,6 +4266,7 @@ impl Game<'_> {
}
if let Some(r) = self.remote.as_mut() {
r.destroying = Some((hit.pos, face, 0.0));
r.destroying_item = held;
}
// startDestroyBlock plays the first hit and crack itself; the
// server's level events 2019 and 2020 do the rest.
@@ -5907,7 +6017,16 @@ impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_
self.0.remote_use();
}
fn pick(&mut self) {
if let Some(hit) = self.0.pick() {
// Minecraft.pickBlockOrEntity: an entity before the block is asked
// for (`handlePickItemFromEntity`), else the block.
if let Some(entity) = self.0.pick_entity_hit() {
if let Some(id) = entity {
self.0.send(S::PickItemFromEntity(play::PickItemFromEntity {
id,
include_data: self.0.has_control_down(),
}));
}
} else if let Some(hit) = self.0.pick() {
self.0.send(S::PickItemFromBlock(play::PickItemFromBlock {
pos: hit.pos,
include_data: self.0.has_control_down(),
@@ -4,10 +4,12 @@
//! own simulation, which a client of a server doesn't run.
use super::Game;
use horizon_client::mobs::render::{PROFESSIONS, VILLAGER_TYPES};
use horizon_client::mobs::{Mob, Species, Who, bat, camel, sniffer, sync, tame};
use horizon_client::mobs::{
Mob, Species, Who, armadillo, bat, bee, camel, creaking, finalize, panda, sniffer, sync, tame,
};
use horizon_client::particles::{ParticleOptions, ParticleType};
use horizon_protocol::entity_data::{Particle, ParticleData, Value};
use horizon_protocol::registry::Builtin;
use horizon_protocol::registry::{Builtin, Dynamic};
/// The values `apply` takes from one SetEntityData packet, by vanilla's entry
/// indices (Entity 0..=7, LivingEntity 8..=14, Mob 15, then the subclasses).
@@ -72,10 +74,23 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
Who::Mob(*target as u32)
});
}
// Panda: the counters, the two genes and DATA_ID_FLAGS (after
// AgeableMob's two entries).
(Species::Panda, 18, Value::Int(n)) => panda::set_unhappy(m, *n),
(Species::Panda, 19, Value::Int(n)) => panda::set_sneeze(m, *n),
(Species::Panda, 20, Value::Int(n)) => panda::set_eat(m, *n),
(Species::Panda, 21, Value::Byte(gene)) => m.extra.variant = (*gene).clamp(0, 6) as u8,
(Species::Panda, 22, Value::Byte(gene)) => m.extra.variant2 = (*gene).clamp(0, 6) as u8,
(Species::Panda, 23, Value::Byte(flags)) => panda::set_flags(m, *flags as u8),
// PolarBear.DATA_STANDING_ID: the client animates the rearing.
(Species::PolarBear, 18, Value::Bool(standing)) => m.extra.flag = *standing,
// Bat.DATA_ID_FLAGS: resting in bit 0.
(Species::Bat, 16, Value::Byte(flags)) => bat::set_resting(m, flags & 1 != 0),
// Fox.DATA_TYPE_ID and DATA_FLAGS_ID.
(Species::Fox, 18, Value::Int(variant)) => {
m.extra.variant = (*variant).clamp(0, 1) as u8
}
(Species::Fox, 19, Value::Byte(flags)) => m.extra.ints[0] = i32::from(*flags as u8),
// Sheep.DATA_WOOL_ID: the colour in the low nibble, 16 sheared.
(Species::Sheep, 18, Value::Byte(wool)) => {
m.extra.color = (*wool & 15) as u8;
@@ -113,6 +128,15 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
(Species::Sniffer, 18, Value::Id(state)) => {
sniffer::set_state(m, (*state).clamp(0, 6) as u8);
}
// Armadillo.ARMADILLO_STATE (after AgeableMob's two): the shell and
// its animations follow it in `sync::client_tick`.
(Species::Armadillo, 18, Value::Id(state)) => {
armadillo::set_state(m, (*state).clamp(0, 3) as u8);
}
// Goat.DATA_HAS_LEFT_HORN and DATA_HAS_RIGHT_HORN: the model hides
// a horn the goat lost.
(Species::Goat, 19, Value::Bool(has)) => m.extra.lost_horns[0] = !*has,
(Species::Goat, 20, Value::Bool(has)) => m.extra.lost_horns[1] = !*has,
// Shulker.DATA_ATTACH_FACE_ID, DATA_PEEK_ID and DATA_COLOR_ID.
(Species::Shulker, 16, Value::Id(face)) => m.extra.variant3 = (*face).clamp(0, 5) as u8,
(Species::Shulker, 17, Value::Byte(peek)) => m.extra.counter = i32::from(*peek),
@@ -125,6 +149,66 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
(Species::Camel | Species::CamelHusk, 20, Value::Long(tick)) => {
camel::set_synced_pose_tick(m, *tick);
}
// Vex.DATA_FLAGS_ID: charging in bit 0.
(Species::Vex, 16, Value::Byte(flags)) => m.extra.flag = flags & 1 != 0,
// Creaking.CAN_MOVE, IS_ACTIVE and IS_TEARING_DOWN.
(Species::Creaking, 16, Value::Bool(can_move)) => m.extra.flag2 = !*can_move,
(Species::Creaking, 17, Value::Bool(active)) => m.extra.flag = *active,
(Species::Creaking, 18, Value::Bool(true)) => creaking::set_tearing_down(m),
// Allay.DATA_DANCING and DATA_CAN_DUPLICATE (a cooldown running
// is any non-zero `egg_time`).
(Species::Allay, 16, Value::Bool(dancing)) => m.extra.flag = *dancing,
(Species::Allay, 17, Value::Bool(can)) => m.extra.egg_time = i32::from(!*can),
// Axolotl.DATA_PLAYING_DEAD (after DATA_VARIANT): the factors
// ease in `sync::client_tick`.
(Species::Axolotl, 19, Value::Bool(dead)) => m.extra.axolotl.playing_dead = *dead,
// CopperGolem.COPPER_GOLEM_STATE (after DATA_WEATHER_STATE).
(Species::CopperGolem, 17, Value::Id(state)) => {
m.extra.variant3 = (*state).clamp(0, 4) as u8;
}
// AbstractHorse's flags take 18. Horse.DATA_ID_TYPE_VARIANT: the
// colour in the low byte, the markings in the next.
(Species::Horse, 19, Value::Int(v)) => {
m.extra.variant = (v & 0xFF).clamp(0, 6) as u8;
m.extra.variant2 = ((v >> 8) & 0xFF).clamp(0, 4) as u8;
}
// AbstractChestedHorse.DATA_ID_CHEST, then Llama.DATA_STRENGTH_ID
// and DATA_VARIANT_ID.
(
Species::Donkey | Species::Mule | Species::Llama | Species::TraderLlama,
19,
Value::Bool(chested),
) => m.extra.chested = *chested,
(Species::Llama | Species::TraderLlama, 20, Value::Int(strength)) => {
m.extra.variant2 = (*strength).clamp(1, 5) as u8;
}
(Species::Llama | Species::TraderLlama, 21, Value::Int(variant)) => {
m.extra.variant = (*variant).clamp(0, 3) as u8;
}
// Axolotl.DATA_VARIANT (lucy 0 to blue 4) and Parrot.DATA_VARIANT_ID
// (after TamableAnimal's flags and owner).
(Species::Axolotl, 18, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8,
(Species::Parrot, 20, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 4) as u8,
// Rabbit.DATA_TYPE_ID: the killer bunny's 99 has no model here.
(Species::Rabbit, 18, Value::Int(t)) if (0..=5).contains(t) => {
m.extra.variant = *t as u8;
}
// Bee.DATA_FLAGS_ID and DATA_ANGER_END_TIME (after Animal's).
(Species::Bee, 18, Value::Byte(flags)) => bee::set_synced(m, Some(*flags as u8), None),
(Species::Bee, 19, Value::Long(end)) => bee::set_synced(m, None, Some(*end)),
// AbstractFish.FROM_BUCKET takes 16: Salmon.DATA_TYPE (small 0
// to large 2), Pufferfish.PUFF_STATE and
// TropicalFish.DATA_ID_TYPE_VARIANT.
(Species::Salmon, 17, Value::Int(v)) => m.extra.variant = (*v).clamp(0, 2) as u8,
(Species::Pufferfish, 17, Value::Int(state)) => m.extra.size = (*state).clamp(0, 2),
(Species::TropicalFish, 17, Value::Int(v)) => tropical_fish(m, *v),
// Ghast.DATA_IS_CHARGING and WitherBoss.DATA_ID_INV.
(Species::Ghast, 16, Value::Bool(charging)) => m.extra.flag = *charging,
(Species::Wither, 19, Value::Int(ticks)) => m.extra.counter = (*ticks).max(0),
// CopperGolem.DATA_WEATHER_STATE: the oxidation the texture shows.
(Species::CopperGolem, 16, Value::Id(state)) => {
m.extra.variant = (*state).clamp(0, 3) as u8;
}
// Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's
// IS_CELEBRATING takes 16).
(Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging,
@@ -146,6 +230,56 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti
}
}
/// A tropical fish's packed variant: the pattern's id (the size, then the
/// index << 8), the base colour << 16 and the pattern colour << 24. Here the
/// pattern is 0 to 5 for the small ones and 6 to 11 for the large ones.
fn tropical_fish(m: &mut Mob, packed: i32) {
let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF);
// TropicalFish.Pattern.byId: an unknown id is a kob.
m.extra.variant = if size <= 1 && index < 6 {
(size * 6 + index) as u8
} else {
0
};
m.extra.variant2 = ((packed >> 16) & 0xFF) as u8 & 15;
m.extra.variant3 = ((packed >> 24) & 0xFF) as u8 & 15;
}
/// The values of one SetEntityData packet that name an entry of a
/// synchronized registry (the variants of the cat, wolf, frog, pig, cow,
/// chicken and zombie nautilus) or count game time (a wolf's anger).
/// `game_time` is the client level's.
fn apply_registry_data(
m: &mut Mob,
values: &[(u8, i32, Value)],
registries: &Dynamic,
game_time: i64,
) {
let species = m.species();
for (index, _, value) in values {
let registry = match (species, *index, value) {
(Species::Cat, 20, Value::Id(_)) => "minecraft:cat_variant",
(Species::Wolf, 23, Value::Id(_)) => "minecraft:wolf_variant",
(Species::Frog, 18, Value::Id(_)) => "minecraft:frog_variant",
(Species::Pig, 19, Value::Id(_)) => "minecraft:pig_variant",
(Species::Cow, 18, Value::Id(_)) => "minecraft:cow_variant",
(Species::Chicken, 18, Value::Id(_)) => "minecraft:chicken_variant",
(Species::ZombieNautilus, 21, Value::Id(_)) => "minecraft:zombie_nautilus_variant",
// Wolf.DATA_ANGER_END_TIME: the angry texture while it lies ahead.
(Species::Wolf, 22, Value::Long(end)) => {
m.extra.anger = (end - game_time).clamp(0, i64::from(i32::MAX)) as i32;
continue;
}
_ => continue,
};
if let Value::Id(id) = value
&& let Some(name) = registries.name(registry, *id)
{
m.extra.variant = finalize::variant_index(species, name);
}
}
}
/// The options of a synched particle list: an entity effect carries its ARGB
/// colour, the omens none.
fn swirls(list: &[Particle], builtin: &Builtin) -> Vec<ParticleOptions> {
@@ -200,6 +334,7 @@ impl Game<'_> {
};
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) {
apply(m, values, &r.builtin, r.entity_id);
apply_registry_data(m, values, &r.registries, self.world.game_time);
}
}
}
@@ -164,6 +164,10 @@ impl Game<'_> {
}
(3, Value::Bool(visible)) => a.name_visible = *visible,
(9, Value::Float(health)) => a.health = *health,
// ArmorStand.DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE.
(16..=21, Value::Floats(r)) if r.len() == 3 => {
a.pose[usize::from(index - 16)] = [r[0], r[1], r[2]];
}
// ArmorStand.DATA_CLIENT_FLAGS.
(15, Value::Byte(flags)) => {
a.small = flags & 1 != 0;
+39 -5
View File
@@ -92,9 +92,8 @@ impl Game<'_> {
distant_terrain: self.lod.is_some(),
cloud_range_chunks: self.settings.cloud_range,
camera_y: camera.y,
// level.getMinY(): the Nether and the End start at y 0.
min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 },
flat: false,
min_y: self.level_min_y(),
flat: self.level_flat(),
forward: forward.map(|c| c as f32),
rain,
thunder,
@@ -108,9 +107,30 @@ impl Game<'_> {
},
)
}
/// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water.
/// `ClientLevelData.isFlat`: on the server thread, the world-wide flag.
fn level_flat(&self) -> bool {
match self.remote.as_ref() {
Some(r) => r.flat,
None => self.world_flat,
}
}
/// `Level.getMinY`: the current dimension type's minimum y.
fn level_min_y(&self) -> i32 {
match self.remote.as_ref() {
Some(r) => r.dimension.min_y,
None => self.dim.min_y(),
}
}
/// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon and not under
/// water. `ClientLevelData.getHorizonHeight`: the bottom of a flat world,
/// otherwise y 63.
pub(super) fn dark_disc(&self, camera: glam::DVec3) -> bool {
camera.y < 63.0
let horizon = if self.level_flat() {
f64::from(self.level_min_y())
} else {
63.0
};
camera.y < horizon
&& fog_type(
&self.world,
self.res.facts(),
@@ -273,6 +293,16 @@ impl Game<'_> {
&& motion_blocking(world, facts, p[0], p[2], p[1] + 64) <= p[1]
&& rains_at(world, biomes, p[0], p[1], p[2])
};
let tables = &self.pack.context.tables;
let model_offset = |state, x, z| tables.offset(state, x, z);
let gateway_particles = |state, p| {
self.res
.block_entity_render()
.gateway_faces(world, state, p)
.len()
};
// Level.isThundering: a thunder level above 0.9 where the sky is open.
let thundering = self.dim == Dim::Overworld && world.weather.levels(1.0).1 > 0.9;
let ctx = AnimateContext {
world,
facts,
@@ -281,6 +311,10 @@ impl Game<'_> {
registry: self.pack.assets.registry,
raining_at: &raining_at,
marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)),
model_offset: &model_offset,
gateway_particles: &gateway_particles,
thundering,
ultrawarm: self.dim == Dim::Nether,
};
if let Some(e) = eye {
let block = [
+1 -1
View File
@@ -683,7 +683,7 @@ impl Game<'_> {
let objective = board.display_objective(sb::SLOT_LIST);
let shown = tab_list::visible(
key,
self.remote.is_none(),
self.has_singleplayer_server(),
players.len(),
objective.is_some(),
);
+21 -6
View File
@@ -67,6 +67,13 @@ impl PackPrompt {
}
}
impl ServerPackState {
/// The `ToastManager` slots the download toasts hold.
pub(super) fn toast_slots(&self) -> impl Iterator<Item = usize> + '_ {
self.notifiers.iter().filter_map(|n| n.toast.as_ref()?.slot)
}
}
/// The game's `DownloadedPackSource`.
#[derive(Default)]
pub(super) struct ServerPackState {
@@ -503,15 +510,22 @@ impl Game<'_> {
.layout(atlas, (w, h))
.draw(batch, atlas, self.cursor, [&yes, &no]);
}
/// The download notifiers' toasts, each in the next 32-pixel slot
/// below an advancement or recipe toast (`ToastManager`).
pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch) {
/// The download notifiers' toasts, each in a free 32-pixel slot of the
/// `ToastManager` (`hidden`, F1, keeps them timing out undrawn).
pub(super) fn draw_pack_toasts(&mut self, batch: &mut HudBatch, hidden: bool) {
let multiplier = f64::from(self.settings.notification_display_time);
let mut slot = usize::from(!self.adv.toasts.is_empty());
let mut used = self.toast_slots_used();
for notifier in &mut self.server_packs.notifiers {
let Some(toast) = &mut notifier.toast else {
continue;
};
if toast.slot.is_none() {
let Some(slot) = (0..Self::TOAST_SLOTS).find(|s| used & (1 << s) == 0) else {
continue;
};
used |= 1 << slot;
toast.slot = Some(slot);
}
let (sound, finished) = toast.update(multiplier);
if let Some(show) = sound {
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
@@ -522,8 +536,9 @@ impl Game<'_> {
notifier.toast = None;
continue;
}
toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32);
slot += 1;
if let (false, Some(slot)) = (hidden, toast.slot) {
toast.draw(&self.gui.atlas, batch, 32.0 * slot as f32);
}
}
}
/// A left click on the prompt: its answer when it hit a button.
+23 -1
View File
@@ -176,7 +176,14 @@ impl Game<'_> {
if projectile {
return;
}
let Some(id) = attacker else { return };
let Some(id) = attacker else {
// Another player's melee hit has no mob behind it.
if let Some((from, disable)) = self.combat.player_attacker {
let fully = outcome.blocked >= damage;
self.blocked_by_attacker(&component, [from[0], from[2]], fully, disable, at);
}
return;
};
let fully = outcome.blocked >= damage;
let Some(m) = self.mobs.iter().find(|m| m.id == id) else {
return;
@@ -219,6 +226,21 @@ impl Game<'_> {
let _ = self.handle_mob_events(events);
return;
}
self.blocked_by_attacker(&component, [mx, mz], fully, disable, at);
}
/// What a blocked melee hit does to the defender once the shield took
/// it: `LivingEntity.blockedByItem` knocks them back unless fully
/// blocked, then `Player.blockUsingItem` disables the shield.
fn blocked_by_attacker(
&mut self,
component: &horizon_client::items::BlocksAttacks,
attacker: [f64; 2],
fully: bool,
disable: f32,
at: Option<[f64; 3]>,
) {
let [mx, mz] = attacker;
// LivingEntity.blockedByItem: defender.knockback(0.5, defender - attacker),
// which moves the defender along -(xd, zd).
if !fully && let Some(p) = self.player.as_mut() {
+45 -1
View File
@@ -5,9 +5,11 @@
//! world as soon as the behaviour returns, within the same tick.
use super::{Game, GameLevel, Screen, dispenser::new_item_motion, storage::is_shulker_box};
use horizon_client::{
block_entity_item, block_entity_nbt,
containers::{Banner, BlockEntity},
item_data,
items::ItemStack,
save,
};
use horizon_core::position::BlockPos;
use horizon_core::random::RandomSource;
@@ -16,7 +18,7 @@ use horizon_world::{
LevelEvent,
removal::{self, PreRemove},
},
nbt::{JavaString, Tag},
nbt::{Compound, JavaString, Tag},
registry::BlockStateId,
};
use std::collections::HashMap;
@@ -32,6 +34,9 @@ pub(super) struct Pending {
pub(super) names: HashMap<[i32; 3], (String, String)>,
/// A decorated pot's sherds (back, left, right, front).
pub(super) pot: HashMap<[i32; 3], [Option<ItemStack>; 4]>,
/// A head's profile, note block sound and name, or a hive's bees: the
/// dropped item and the component patch it takes.
pub(super) copied: HashMap<[i32; 3], (String, Compound)>,
}
impl Pending {
/// Remember what the block entity at `pos` copies into the drops of `block`.
@@ -49,6 +54,31 @@ impl Pending {
if let Some(name) = name {
self.names.insert(pos, (block.to_owned(), name));
}
// `copy_components` from the block entity: the head tables copy the
// profile (player heads), note block sound and name, the hive tables
// the bees.
let include: &[&str] = match entity {
BlockEntity::Skull(_) if block.starts_with("minecraft:player_") => &[
"minecraft:profile",
"minecraft:note_block_sound",
"minecraft:custom_name",
],
BlockEntity::Skull(_) => &["minecraft:custom_name"],
BlockEntity::Beehive(_) => &["minecraft:bees"],
_ => &[],
};
if !include.is_empty() {
let saved = save::encode_block_entity((pos[0], pos[1], pos[2]), entity, block);
let mut patch = block_entity_nbt::canonical(&saved)
.map(|saved| block_entity_item::pick(&saved))
.unwrap_or_default();
patch.retain(|k, _| include.contains(&k.to_string_lossy().as_str()));
if !patch.is_empty() {
// `Blocks.wallVariant`: a wall head drops the standing item.
let item = block.replacen("_wall_", "_", 1);
self.copied.insert(pos, (item, patch));
}
}
if is_shulker_box(block)
&& let BlockEntity::Chest(items) = entity
{
@@ -76,6 +106,19 @@ impl Pending {
{
stack.data_mut().custom_name = Some(name);
}
if self
.copied
.get(&pos)
.is_some_and(|(item, _)| **item == *stack.item)
&& let Some((_, copied)) = self.copied.remove(&pos)
{
let mut patch = match item_data::encode_components(stack) {
Some(Tag::Compound(c)) => c,
_ => Default::default(),
};
patch.extend(copied);
(stack.damage, stack.extra) = item_data::decode_components(Some(&Tag::Compound(patch)));
}
if &*stack.item == "minecraft:decorated_pot" {
// The pot's block entity always copies its decorations, empty or not.
let sides = self.pot.remove(&pos).unwrap_or_default();
@@ -155,6 +198,7 @@ impl Pending {
self.shulker.remove(&pos);
self.banner.remove(&pos);
self.names.remove(&pos);
self.copied.remove(&pos);
}
}
+18 -7
View File
@@ -779,6 +779,7 @@ impl Game<'_> {
return;
};
let pos = s.pos;
let enchanted_item = enchanted.clone();
// Player.onEnchantmentPerformed
self.give_levels(-(lapis_needed as i32));
self.level.xp_seed = self.world.random.next_int();
@@ -795,6 +796,7 @@ impl Game<'_> {
}
let pitch = self.world.random.next_float() * 0.1 + 0.9;
self.stats.custom("enchant_item", 1);
self.trigger_enchanted_item(&enchanted_item, lapis_needed as i32);
self.play_at("minecraft:block.enchantment_table.use", pos, 1.0, pitch);
self.station_changed();
}
@@ -1768,6 +1770,11 @@ impl Game<'_> {
};
let gray = rgba(170, 170, 170, 255);
let item_info = self.res.items().get(&stack.item);
// SmithingTemplateItem.appendHoverText: `Item.appendHoverText` comes
// before the components.
for (text, c) in horizon_client::item_tooltip::smithing_template_lines(stack, &translate) {
push(&mut lines, text, c);
}
// InstrumentComponent.addToTooltip.
if let Some(text) =
horizon_client::item_tooltip::instrument_line(stack, &display, &translate)
@@ -2023,15 +2030,19 @@ impl Game<'_> {
&& stack.damage > 0
&& advanced
{
push(
&mut lines,
format!(
"Durability: {} / {}",
info.max_damage - stack.damage,
info.max_damage
// `item.durability`, in the selected language.
lines.push((
horizon_client::text::Text::translate(
"item.durability",
&[
horizon_client::text::Text::literal(
(info.max_damage - stack.damage).to_string(),
),
horizon_client::text::Text::literal(info.max_damage.to_string()),
],
),
u32::MAX,
);
));
}
// ItemStack.addDetailsToTooltipTail: with advanced tooltips the item id
// and how many components the stack has.
+3 -2
View File
@@ -378,9 +378,10 @@ impl Game<'_> {
if pos[1] < 63 || !self.can_see_sky(pos) {
return;
}
// DifficultyInstance.isHarderThan(random * 3) at normal difficulty.
// `getCurrentDifficultyAt(playerPos).isHarderThan(random * 3)`.
let difficulty = self.local_difficulty([position.x, position.y, position.z]);
let r = &mut self.world.random;
if r.next_float() * 3.0 >= 2.0 {
if difficulty.effective <= r.next_float() * 3.0 {
return;
}
if r.next_int_bound(since_rest.max(1)).unwrap_or(0) < 72000 {
+7 -3
View File
@@ -12,12 +12,14 @@ use horizon_client::{
impl Game<'_> {
/// `Hud.extractOverlayMessage` and `extractTitle`.
pub(super) fn draw_titles(&self, batch: &mut HudBatch) {
pub(super) fn draw_titles(&self, batch: &mut HudBatch, bar_height: i32) {
let (w, h) = (batch.width as i32, batch.height as i32);
let partial = self.clock.fraction() as f32;
let background = self.settings.text_background(0.0);
let font = &self.gui.atlas.font;
let mut draws = self.titles.overlay_message(w, h, partial, font, background);
let mut draws = self
.titles
.overlay_message(w, h, bar_height, partial, font, background);
draws.extend(self.titles.title(w, h, partial, font, background));
hud_layout::paint(batch, &self.gui.atlas, &draws);
}
@@ -60,6 +62,7 @@ impl Game<'_> {
/// The title, action bar and selected-item parts of `Hud.tick`.
pub(super) fn tick_hud(&mut self) {
self.titles.tick();
self.tick_in_bed_chat();
// `MinecraftServer.isCurrentlySaving` of single player's server.
let saving = self
.integrated
@@ -71,10 +74,11 @@ impl Game<'_> {
.tick(held, f64::from(self.settings.notification_display_time));
}
/// `Hud.extractSelectedItemName`.
pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, can_hurt: bool) {
pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, bar_height: i32, can_hurt: bool) {
let draws = self.tool_highlight.draw(
batch.width as i32,
batch.height as i32,
bar_height,
can_hurt,
&self.gui.atlas.font,
self.settings.text_background(0.0),
+18 -2
View File
@@ -257,8 +257,24 @@ impl Game<'_> {
// Player.startAutoSpinAttack(20, 8, stack).
p.auto_spin_attack_ticks = 20;
p.auto_spin_attack_dmg = 8.0;
if p.ground.on_ground {
p.position.y += 1.2;
}
// `player.move(SELF, (0, 1.1999999, 0))` when on the ground: the lift
// stops at a ceiling.
let lift = self
.player
.as_ref()
.filter(|p| p.ground.on_ground)
.map(|p| p.bounds());
if let Some(bounds) = lift {
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
let up = Vec3::new(0.0, f64::from(1.1999999f32), 0.0);
let moved = scene.resolve(bounds, up, 0.0, true).unwrap_or(Vec3::ZERO);
if let Some(p) = self.player.as_mut() {
p.position.y += moved.y;
}
}
let sound = format!("minecraft:item.trident.riptide_{}", riptide.min(3));
+1
View File
@@ -470,6 +470,7 @@ impl Game<'_> {
}
/// The bursts guests' turns put off.
pub(super) fn flush_wind_bursts(&mut self) -> Result<()> {
self.flush_smash_pushes();
for b in std::mem::take(&mut self.creatures.wind_bursts) {
self.wind_burst(b.center, b.radius, b.multiplier, b.breeze, b.wind_charge)?;
}
+20
View File
@@ -119,3 +119,23 @@ pub fn load(path: &Path, known: &dyn Fn(&str) -> bool) -> Vec<Hotbar> {
_ => (0..GROUPS).map(|_| empty()).collect(),
}
}
/// `HotbarManager.save`: the nine rows with the current data version, each
/// stack as `ItemStack.OPTIONAL_CODEC` writes it (an empty one is `{}`).
pub fn save(path: &Path, rows: &[Hotbar]) -> crate::Result<()> {
let mut entries = vec![(
JavaString::from("DataVersion"),
Tag::Int(horizon_world::DATA_VERSION),
)];
for (i, row) in rows.iter().enumerate() {
let stacks = row.iter().map(|s| match s {
Some(s) => save::item_to_nbt(s),
None => Tag::compound(Vec::<(&str, Tag)>::new()),
});
entries.push((
JavaString::from(i.to_string().as_str()),
Tag::List(stacks.collect()),
));
}
save::write_dat(path, Tag::compound(entries))
}
+10
View File
@@ -485,6 +485,11 @@ pub struct HealthHud {
/// `Util.getMillis()` of the last health change.
pub last_health_time: i64,
pub health_blink_time: i64,
/// `Hud.leftHeight` and `rightHeight` once the health, armor, food, mount
/// and air layers have run; the selected item name and the action bar sit
/// above them.
pub left_height: i32,
pub right_height: i32,
}
pub struct HealthInputs {
@@ -645,6 +650,9 @@ impl HealthHud {
let rows = ceil((max_health + absorption as f32) / 2.0 / 10.0);
let row_height = (10 - (rows - 2)).max(3);
let mut y_air = y_base - 10;
self.left_height = 39 + (rows - 1) * row_height + 10 + if i.armor > 0 { 10 } else { 0 };
// The mount's heart rows (`extractVehicleHealth`); food adds its row below.
self.right_height = 39 + 10 * ((i.vehicle_hearts + 9) / 10);
let offset_index = if i.regeneration {
i.tick % ceil(max_health + 5.0)
} else {
@@ -739,11 +747,13 @@ impl HealthHud {
}
}
y_air -= 10;
self.right_height += 10;
}
// Hud.extractAirBubbles.
let max_air = i.max_air.max(1);
let air = i.air.clamp(0, max_air);
if i.under_water || air < max_air {
self.right_height += 10;
let rows = (f64::from(i.vehicle_hearts) / 10.0).ceil() as i32;
let y = y_air - (rows - 1) * 10;
let bubble = |offset: i32| ceil(((air + offset) * 10) as f32 / max_air as f32);
+11 -4
View File
@@ -323,11 +323,13 @@ impl Titles {
}
}
}
/// `Hud.extractOverlayMessage`.
/// `Hud.extractOverlayMessage`; `bar_height` is
/// `max(leftHeight, rightHeight)`.
pub fn overlay_message(
&self,
w: i32,
h: i32,
bar_height: i32,
partial: f32,
font: &Font,
background: u32,
@@ -343,9 +345,12 @@ impl Titles {
let alpha = ((t * 255.0 / 20.0) as i32).min(255);
if alpha > 0 {
let message = message.resolve_legacy();
// The bars' height plus the gap between the item name (59) and the
// overlay (68), at least the default level.
let y_shift = bar_height + (68 - 59);
out.push(GuiDraw::Push(vec![PoseOp::Translate(
(w / 2) as f32,
(h - 68) as f32,
(h - y_shift.max(68)) as f32,
)]));
let color = if self.overlay_animated {
hsv_to_argb(t / 50.0, 0.7, 0.6, alpha as u32)
@@ -463,11 +468,13 @@ impl ToolHighlight {
self.last = selected;
}
/// `Hud.extractSelectedItemName`; `can_hurt` is
/// `gameMode.canHurtPlayer()` (survival and adventure).
/// `gameMode.canHurtPlayer()` (survival and adventure) and `bar_height`
/// is `max(leftHeight, rightHeight)`.
pub fn draw(
&self,
w: i32,
h: i32,
bar_height: i32,
can_hurt: bool,
font: &Font,
background: u32,
@@ -488,7 +495,7 @@ impl ToolHighlight {
}
let str_width = width(font, &name);
let x = (w - str_width) / 2;
let mut y = h - 59;
let mut y = h - bar_height.max(59);
if !can_hurt {
y += 14;
}
+10
View File
@@ -106,6 +106,16 @@ impl StackData {
pub fn other(&self, id: &str) -> Option<&Tag> {
self.other.iter().find(|(k, _)| k == id).map(|(_, v)| v)
}
/// `SetNameFunction.run`: a loot text component stored as `custom_name`
/// (plain text, as modelled) or as the unmodelled `item_name`.
pub fn set_loot_name(&mut self, id: &str, text: &serde_json::Value) {
let tag = crate::scoreboard::json_to_tag(text);
if id == "minecraft:custom_name" {
self.custom_name = read_text(&tag);
} else {
self.set_other(id, Some(tag));
}
}
/// Set (or with None remove) an unmodelled component.
pub fn set_other(&mut self, id: &str, value: Option<Tag>) {
self.other.retain(|(k, _)| k != id);
+16
View File
@@ -95,6 +95,22 @@ fn components_tag(s: &Stack, builtin: &Builtin, synced: &Dynamic) -> Option<Tag>
),
]),
Component::FireworkExplosion(e) => fireworks_tag(e),
Component::LodestoneTracker { target, tracked } => {
let mut entries = Vec::new();
if let Some((dimension, pos)) = target {
entries.push((
"target",
Tag::compound([
("dimension", Tag::String(dimension.as_str().into())),
("pos", Tag::IntArray(pos.to_vec())),
]),
));
}
if !tracked {
entries.push(("tracked", Tag::Byte(0)));
}
Tag::compound(entries)
}
Component::Enchantments(list) => {
// Enchantments are a synced (data-driven) registry: the
// ids index the server's RegistryData, not the builtin
+36 -24
View File
@@ -484,6 +484,37 @@ pub fn component_count(stack: &ItemStack, info: Option<&ItemInfo>) -> usize {
keys.len()
}
/// `SmithingTemplateItem.appendHoverText`: the template's kind, what it applies to
/// and its ingredients (gray titles over blue descriptions); none for other items.
pub fn smithing_template_lines(
stack: &ItemStack,
translate: &dyn Fn(&str) -> Option<String>,
) -> Vec<(String, u32)> {
let path = stack.item.trim_start_matches("minecraft:");
if !path.ends_with("_smithing_template") {
return Vec::new();
}
let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned());
let kind = if path == "netherite_upgrade_smithing_template" {
"netherite_upgrade"
} else {
"armor_trim"
};
let (title, description) = (rgba(170, 170, 170, 255), rgba(85, 85, 255, 255));
let described = |what: &str| {
let key = format!("item.minecraft.smithing_template.{kind}.{what}");
(format!(" {}", text(&key)), description)
};
vec![
(text("item.minecraft.smithing_template"), title),
(String::new(), u32::MAX),
(text("item.minecraft.smithing_template.applies_to"), title),
described("applies_to"),
(text("item.minecraft.smithing_template.ingredients"), title),
described("ingredients"),
]
}
/// The lines of `stack` below its name that its components give, in
/// `ItemStack.addDetailsToTooltip` order.
pub fn detail_lines(
@@ -494,30 +525,11 @@ pub fn detail_lines(
let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned());
let path = stack.item.trim_start_matches("minecraft:");
let mut lines = Vec::new();
// SmithingTemplateItem.appendHoverText.
if path.ends_with("_smithing_template") {
let kind = if path == "netherite_upgrade_smithing_template" {
"netherite_upgrade"
} else {
"armor_trim"
};
lines.push(text("item.minecraft.smithing_template"));
lines.push(String::new());
lines.push(text("item.minecraft.smithing_template.applies_to"));
lines.push(format!(
" {}",
text(&format!(
"item.minecraft.smithing_template.{kind}.applies_to"
))
));
lines.push(text("item.minecraft.smithing_template.ingredients"));
lines.push(format!(
" {}",
text(&format!(
"item.minecraft.smithing_template.{kind}.ingredients"
))
));
}
lines.extend(
smithing_template_lines(stack, translate)
.into_iter()
.map(|l| l.0),
);
let display = TooltipDisplay::for_stack(stack);
lines.extend(bees_line(stack, &display, translate));
lines.extend(honey_line(stack, &display, translate));
+26
View File
@@ -1154,6 +1154,8 @@ impl Items {
ctx.evaluate(table, random)
}
}
/// `DataComponents.BLOCK_STATE`.
const BLOCK_STATE: &str = "minecraft:block_state";
impl LootContext<'_> {
fn evaluate<R: RandomSource>(&self, table: &Value, random: &mut R) -> Vec<ItemStack> {
let ctx = self;
@@ -1561,6 +1563,30 @@ impl LootContext<'_> {
}
}
}
// CopyBlockState: the listed properties of the broken block
// become the item's `block_state` component.
"minecraft:copy_state" => {
use horizon_world::nbt::Tag;
let mut copied = match stack.data().and_then(|d| d.other(BLOCK_STATE)) {
Some(Tag::Compound(c)) => c.clone(),
_ => Default::default(),
};
for name in f["properties"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
if let Some(value) = self.properties.get(name) {
copied.insert(name.into(), Tag::String(value.as_str().into()));
}
}
if !copied.is_empty() {
stack
.data_mut()
.set_other(BLOCK_STATE, Some(Tag::Compound(copied)));
}
}
// ApplyExplosionDecay: each item survives with 1 / radius.
"minecraft:explosion_decay" => {
if let Some(radius) = self.explosion_radius {
+18
View File
@@ -742,6 +742,24 @@ impl Entities {
chunk,
});
}
// TrackedEntity.getEffectiveRange: a vehicle is tracked as far as its
// widest indirect passenger, so a rider never leaves before its mount.
for (&vehicle, passengers) in &riding.passengers {
let Some(own) = self.states.get(&vehicle).filter(|s| s.seen == now) else {
continue;
};
let (index, mut range) = (own.index, own.range);
let mut pending = passengers.clone();
while let Some(id) = pending.pop() {
if let Some(s) = self.states.get(&id).filter(|s| s.seen == now) {
range = range.max(s.range);
}
pending.extend_from_slice(riding.passengers(id));
}
self.probes[index].range = self
.range_percent
.map_or(range * 16, |p| p * (range * 16) / 100);
}
self.flags.resize_with(viewers.len(), Vec::new);
self.pairs.clear();
self.pairs.resize(entities.len(), false);
+15
View File
@@ -614,6 +614,21 @@ fn network_stack(
));
}
stack.added.extend(firework_components(d));
// The compass's lodestone target.
if let Some(t) = d.other("minecraft:lodestone_tracker") {
let target = t.get("target").and_then(|g| {
let Some(horizon_world::nbt::Tag::IntArray(pos)) = g.get("pos") else {
return None;
};
let dimension = crate::save::text(g.get("dimension"))?;
Some((dimension, [*pos.first()?, *pos.get(1)?, *pos.get(2)?]))
});
let tracked = crate::save::number(t.get("tracked")).is_none_or(|v| v != 0);
stack.added.push((
horizon_protocol::item::component::LODESTONE_TRACKER,
horizon_protocol::item::Component::LodestoneTracker { target, tracked },
));
}
// PotionContents: the potion by its `minecraft:potion` id.
if let Some(id) = (d.potion.as_deref()).and_then(|potion| {
synced_id(
+5 -1
View File
@@ -178,6 +178,9 @@ pub struct Hub {
/// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`),
/// whose moves are never checked.
pub singleplayer_owner: Option<u128>,
/// The world is superflat (`ServerLevel.isFlat`, a world-wide flag, sent as
/// `CommonPlayerSpawnInfo.isFlat` in every dimension).
pub flat_world: bool,
/// Who rides what, set by the game before each tick.
pub riding: super::entity::Riding,
/// The scoreboard's teams, set by the game each tick, for players'
@@ -358,6 +361,7 @@ impl Hub {
immediate_respawn: false,
movement_checks: (true, true),
singleplayer_owner: None,
flat_world: false,
riding: Default::default(),
last_clock: i64::MIN,
last_rate: 0.0,
@@ -610,7 +614,7 @@ impl Hub {
game_type: game_mode,
previous_game_type: None,
debug: false,
flat: false,
flat: self.flat_world,
last_death: None,
portal_cooldown: 0,
sea_level: 63,
+2
View File
@@ -23,6 +23,8 @@ fn main() {
};
if !help {
logging::init(&home, thread);
// The log's first line names the build, so a bug report that carries the log says which one it was.
log::info!("Horizon {}", crash::version());
crash::install(home.clone(), side);
}
if let Err(error) = game::run() {
+72 -4
View File
@@ -11,6 +11,7 @@ pub mod ambient;
pub mod anim;
pub mod animal_brain;
pub mod aquatic;
pub mod armadillo;
pub mod axolotl;
pub mod bat;
pub mod bee;
@@ -25,14 +26,18 @@ pub mod creaking;
pub mod creaking_heart;
pub mod cube;
pub mod data;
pub mod dolphin;
pub mod doors;
pub mod drops;
pub mod enderman;
pub mod equine;
pub mod farm;
pub mod finalize;
pub mod fox;
pub mod frog;
pub mod gear;
pub mod goals;
pub mod goat;
pub mod golem;
pub mod guardian;
pub mod happy_ghast;
@@ -47,6 +52,7 @@ pub mod monster_brain;
pub mod nautilus;
pub mod nav;
pub mod nether;
pub mod panda;
pub mod path;
pub mod phantom;
pub mod piglin;
@@ -797,6 +803,8 @@ pub struct Extra {
/// A goat's `IsScreamingGoat` and the horns it lost (left, right).
pub screaming: bool,
pub lost_horns: [bool; 2],
/// A goat's lowered head and ram behaviours.
pub goat: goat::State,
/// Attribute bases and permanent modifiers set by `finalizeSpawn`.
pub attributes: Option<Box<finalize::Attributes>>,
/// Brain memories `finalizeSpawn` sets: (memory, value, ticks to expiry).
@@ -812,6 +820,12 @@ pub struct Extra {
pub brain: Option<Box<monster_brain::Brain>>,
/// A bee's nectar, anger, flower and hive state.
pub bee: Option<Box<bee::Bee>>,
/// An armadillo's state and scare brain.
pub armadillo: armadillo::State,
/// A frog's brain memories and tongue target.
pub frog: frog::State,
/// A panda's flags, counters and amounts.
pub panda: Option<Box<panda::State>>,
}
#[derive(Clone, Debug)]
pub struct Mob {
@@ -998,6 +1012,16 @@ pub enum MobEvent {
state: horizon_world::registry::BlockStateId,
},
AttackPlayer(f32, [f64; 3]),
/// A melee hit whose effect comes only if the hit lands (husk hunger,
/// cave spider poison, wither skeleton wither, bee and pufferfish
/// poison): a shield-blocked hit gives nothing.
AttackPlayerWithEffect {
amount: f32,
from: [f64; 3],
effect: &'static str,
ticks: i32,
amplifier: i32,
},
/// Damage of a given type to the player (guardian lasers, thorns).
DamagePlayer {
amount: f32,
@@ -1048,6 +1072,13 @@ pub enum MobEvent {
amount: f32,
source: Damage,
},
/// `LivingEntity.knockback(power, x, z)`: pushed away from the direction.
Knockback {
target: Who,
power: f64,
x: f64,
z: f64,
},
/// Set another mob's attack target (HurtByTargetGoal alerts).
SetTarget {
mob: u32,
@@ -1128,6 +1159,12 @@ pub enum MobEvent {
},
/// Regeneration support after an axolotl-assisted kill.
AxolotlSupportPlayer,
/// A dolphin that was given a fish asks the game for the nearest
/// shipwreck or ocean ruin (`DolphinSwimToTreasureGoal.start`): the game
/// sets the dolphin's `extra.home` to it, or leaves it empty.
DolphinTreasure {
mob: u32,
},
/// Apply an effect to the player (witch potions, bee stings, cave spider poison).
EffectPlayer {
effect: &'static str,
@@ -1291,6 +1328,10 @@ pub enum MobEvent {
center: [f64; 3],
spread: [f64; 3],
},
/// `Panda.afterSneeze`: the grown pandas within 10 blocks start.
PandaSneezed {
mob: u32,
},
}
/// How a spawned-by-kind mob should be set up.
#[derive(Clone, Debug, Default)]
@@ -1328,6 +1369,8 @@ pub struct Seen {
pub target: Option<Who>,
pub health: f32,
pub variant: u8,
/// A slime's or magma cube's size.
pub size: i32,
/// Dye colour (sheep).
pub color: u8,
/// A villager's claimed job site and bed.
@@ -1373,6 +1416,8 @@ pub struct Seen {
pub sitting: bool,
/// `Entity.isVehicle` or `isPassenger`.
pub ridden: bool,
/// `Attributes.KNOCKBACK_RESISTANCE`.
pub knockback_resistance: f64,
/// The active effects, without namespace (`slowness`, `poison`...).
pub effects: Vec<&'static str>,
}
@@ -1429,6 +1474,7 @@ impl Mob {
target: m.ai.target,
health: m.health,
variant: m.extra.variant,
size: m.extra.size,
color: m.extra.color,
job: villager.then_some(m.extra.home).flatten(),
bed: villager.then_some(m.extra.bed).flatten(),
@@ -1460,6 +1506,7 @@ impl Mob {
],
sitting: m.extra.sitting,
ridden: m.rider.is_some() || m.extra.rider.is_some() || m.extra.mount.is_some(),
knockback_resistance: m.attrs.knockback_resistance,
effects: m
.extra
.effects
@@ -1594,6 +1641,8 @@ pub struct PlayerView {
pub alive: bool,
pub creative: bool,
pub sneaking: bool,
/// `Entity.isSwimming`.
pub swimming: bool,
pub look: [f64; 3],
pub main_hand: Option<Arc<str>>,
pub off_hand: Option<Arc<str>>,
@@ -1610,6 +1659,9 @@ pub struct PlayerView {
pub last_hurt: Option<(Who, i64)>,
pub velocity: Vec3,
pub yaw: f32,
/// `Player.isSprinting` and `isPassenger` (what scares an armadillo).
pub sprinting: bool,
pub riding: bool,
/// The Hero of the Village effect.
pub hero: bool,
/// The active effects, without namespace (`slowness`, `poison`...).
@@ -1673,7 +1725,8 @@ pub struct MobWorld<'a> {
pub mob_griefing: bool,
/// The `mob_drops` game rule (`shouldDropLoot`).
pub mob_drops: bool,
/// `getCurrentDifficultyAt` near the player.
/// `getCurrentDifficultyAt` at the mob being ticked (near the player
/// outside the mob tick).
pub difficulty: spawning::LocalDifficulty,
/// The End (its dimension type's monster spawn light rules).
pub end: bool,
@@ -1854,8 +1907,14 @@ impl Mob {
/// the last-hurt-by bookkeeping goals read.
/// The `armor` and `armor_toughness` modifiers of worn humanoid armour.
pub fn worn_armor(&self) -> (f32, f32) {
// An equine keeps its horse armor in `extra.head`: the item's `armor`
// and `armor_toughness` modifiers of the body slot.
if equine::is_equine(self.species()) {
return (0.0, 0.0);
return self
.extra
.head
.as_deref()
.map_or((0.0, 0.0), spawning::horse_armor_stats);
}
[
&self.extra.head,
@@ -1896,6 +1955,9 @@ impl Mob {
return false;
}
let mut amount = if reflected { 1000.0 } else { amount };
if self.species() == Species::Armadillo {
amount = armadillo::reduce_damage(self, amount);
}
if source.kind == DamageKind::FallingBlock
&& !species::body_slot(self.species())
&& self.extra.head.is_some()
@@ -1912,9 +1974,15 @@ impl Mob {
amount *= 5.0;
}
let (worn, worn_toughness) = self.worn_armor();
if !source.bypasses_armor() && self.kind.armor + worn > 0.0 {
// Shulker.setRawPeekAmount: a closed shell adds the covered armor modifier.
let covered = if self.species() == Species::Shulker && self.extra.counter == 0 {
20.0
} else {
0.0
};
if !source.bypasses_armor() && self.kind.armor + worn + covered > 0.0 {
// CombatRules.getDamageAfterAbsorb
let armor = self.kind.armor + worn;
let armor = self.kind.armor + worn + covered;
let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0;
let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
let mut fraction = effective / 25.0;
+112 -28
View File
@@ -106,6 +106,7 @@ pub enum Family {
Strider,
Bat,
Bee,
Panda,
PolarBear,
}
pub fn family(s: Species) -> Family {
@@ -168,6 +169,7 @@ pub fn family(s: Species) -> Family {
S::Strider => Family::Strider,
S::Bat => Family::Bat,
S::Bee => Family::Bee,
S::Panda => Family::Panda,
S::PolarBear => Family::PolarBear,
_ => Family::Generic,
}
@@ -180,6 +182,9 @@ pub fn register(m: &mut Mob) {
Family::Undead => undead::register(m),
Family::Hostile => hostile::register(m),
Family::Aquatic => aquatic::register(m),
Family::Generic if m.species() == Species::Armadillo => super::armadillo::register(m),
Family::Generic if m.species() == Species::Frog => super::frog::register(m),
Family::Generic if m.species() == Species::Fox => super::fox::register(m),
Family::Generic => {
generic(m);
if m.species() == Species::Rabbit {
@@ -200,19 +205,8 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Turtle {
super::turtle::register(m);
}
if m.species() == Species::Frog {
// `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true).
// The frog's movement speed is 1.0, so the controller's 0.1
// outside-water speed is what keeps a walking frog at
// vanilla's pace; the plain ground controller walks ten
// times too fast (#2213).
m.ai.mov.kind = super::control::MoveKind::SmoothSwimming {
max_turn_x: 85.0,
max_turn_y: 10.0,
in_water: 0.02,
outside: 0.1,
gravity: true,
};
if m.species() == Species::Goat {
super::goat::register(m);
}
}
Family::Inert => {}
@@ -255,6 +249,7 @@ pub fn register(m: &mut Mob) {
Family::Strider => super::strider::register(m),
Family::Bat => super::bat::register(m),
Family::Bee => super::bee::register(m),
Family::Panda => super::panda::register(m),
Family::PolarBear => super::polar_bear::register(m),
}
// FloatGoal's constructor lets the navigation float, as do the
@@ -455,7 +450,10 @@ pub fn tick(
}
// Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen
// creaking's waits).
if m.alive() && (!super::creaking::is_creaking(m) || super::creaking::can_move(m)) {
if m.alive()
&& (!super::creaking::is_creaking(m) || super::creaking::can_move(m))
&& !super::armadillo::scared(m)
{
m.body_rotation_tick();
}
events.append(&mut m.outbox);
@@ -477,6 +475,9 @@ pub fn tick(
if m.species() == Species::Bee {
super::bee::tick(m, level_random);
}
if m.species() == Species::Panda {
super::panda::tick(m, w, events);
}
true
}
/// LivingEntity.updateSwingTime (6-tick swing duration).
@@ -782,6 +783,9 @@ 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);
}
if m.species() == Species::Fox {
super::fox::pre_ai_step(m);
}
// AbstractHorse.aiStep: the tail swishes now and then (moveTail).
if super::equine::is_equine(m.species()) {
super::equine::tail_tick(m);
@@ -1108,7 +1112,11 @@ fn armadillo_server_ai_step(m: &mut Mob, mob_drops: bool, events: &mut Vec<MobEv
fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
match m.species() {
Species::Rabbit => super::rabbit::server_ai_step(m),
Species::Armadillo => armadillo_server_ai_step(m, cx.w.mob_drops, cx.events),
// Armadillo.customServerAiStep: the brain and its activity, then the scute.
Species::Armadillo => {
super::armadillo::server_ai_step(m, cx);
armadillo_server_ai_step(m, cx.w.mob_drops, cx.events);
}
Species::Sheep => {}
Species::Zombie
| Species::Husk
@@ -1129,6 +1137,7 @@ fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
Species::Evoker if m.extra.counter > 0 => m.extra.counter -= 1,
Species::Bat => super::bat::server_ai_step(m, cx.w, cx.events),
Species::Bee => super::bee::server_ai_step(m, cx),
Species::Frog => super::frog::server_ai_step(m, cx.w),
_ => {}
}
}
@@ -1182,6 +1191,10 @@ fn species_ai_step(
}
Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Armadillo => super::armadillo::tick(m),
Species::Frog => super::frog::tick(m),
Species::Goat => super::goat::tick(m),
Species::Fox => super::fox::ai_step(m, w, events),
Species::Turtle => super::turtle::ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => {
m.extra.anim_ticks -= 1;
@@ -1300,6 +1313,18 @@ pub fn voice_sounds(m: &Mob) -> [&'static str; 3] {
match m.species() {
Species::Nautilus | Species::ZombieNautilus => super::nautilus::sounds(m),
Species::SulfurCube => super::sulfur_cube::sounds(m),
Species::Armadillo => super::armadillo::sounds(m),
// Panda.getAmbientSound.
Species::Panda => {
let ambient = if super::panda::is_aggressive(m) {
"entity.panda.aggressive_ambient"
} else if super::panda::is_worried(m) {
"entity.panda.worried_ambient"
} else {
m.kind.sounds[0]
};
[ambient, m.kind.sounds[1], m.kind.sounds[2]]
}
// The sound variant's baby_sounds (classic sets, like the rest here).
Species::Pig if m.is_baby() => [
"entity.baby_pig.ambient",
@@ -1322,6 +1347,10 @@ pub fn feed_animal(
m: &mut Mob,
level: &mut impl RandomSource,
) -> Option<Option<(&'static str, f32, f32)>> {
// Armadillo.mobInteract: a ball takes no food.
if super::armadillo::scared(m) {
return None;
}
if m.extra.age == 0 && m.extra.in_love <= 0 {
m.extra.in_love = 600;
m.extra.love_player = true;
@@ -1498,6 +1527,11 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, _amount: f32) -> bool {
super::bee::hurt(m);
true
}
// Panda.hurtServer: up first, whatever the damage.
Species::Panda => {
super::panda::hurt(m);
true
}
Species::Enderman => super::enderman::on_damage(m, source),
Species::WitherSkeleton | Species::Blaze | Species::MagmaCube | Species::Strider
if source.is_fire() =>
@@ -1512,6 +1546,7 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
m.ai.no_action_time = 0;
match m.species() {
Species::Enderman => super::enderman::after_hurt(m, source),
Species::Armadillo => super::armadillo::after_hurt(m, source),
Species::Shulker => super::shulker::after_hurt(m),
Species::Warden => super::warden::hurt(m, source),
Species::Wolf => super::tame::after_hurt(m, source),
@@ -1525,7 +1560,16 @@ pub fn after_hurt(m: &mut Mob, source: &Damage) {
// PiglinAi.wasHurtBy: drop what is being admired, no admiring for
// a while after a player's hit, and anger.
Species::Piglin if source.attacker == Some(Who::Player) => {
m.extra.using_item = 0;
// stopHoldingOffHandItem(.., false): a gold ingot is not bartered
// and is gone; anything else ends its admiring next tick, as if
// the time ran out, and the game side puts it away.
if m.extra.off_hand.as_deref() == Some("minecraft:gold_ingot") {
m.extra.off_hand = None;
m.extra.using_item = 0;
} else {
m.extra.using_item =
i32::from(m.extra.off_hand.is_some() && m.extra.using_item > 0);
}
m.extra.egg_time = 400;
m.extra.anger = 600;
}
@@ -1549,24 +1593,37 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if m.species() == Species::Ravager {
super::ravager::on_attack(m, cx.events);
}
if m.species() == Species::Panda {
super::panda::bit(m);
}
if super::creaking::is_creaking(m) {
super::creaking::on_attack(m, cx.events);
}
let mut amount = m.attrs.attack_damage;
let from = [m.position.x, m.position.y, m.position.z];
let source = Damage::mob(m.id, from);
let first_event = cx.events.len();
match m.species() {
// Difficulty NORMAL: cave spiders poison for 7 seconds.
Species::CaveSpider if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
effect: "minecraft:poison",
ticks: 7 * 20,
amplifier: 0,
}),
Species::Husk if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
effect: "minecraft:hunger",
ticks: 140,
amplifier: 0,
}),
// CaveSpider.doHurtTarget: poison for 7 s on normal, 15 s on hard.
Species::CaveSpider if who == Who::Player && cx.w.difficulty.base >= 2 => {
cx.events.push(MobEvent::EffectPlayer {
effect: "minecraft:poison",
ticks: if cx.w.difficulty.base == 2 { 7 } else { 15 } * 20,
amplifier: 0,
})
}
// Husk.doHurtTarget: hunger for 140 ticks per whole point of the
// local difficulty, only with an empty main hand.
Species::Husk if who == Who::Player && m.extra.main_hand.is_none() => {
let ticks = 140 * cx.w.difficulty.effective as i32;
if ticks > 0 {
cx.events.push(MobEvent::EffectPlayer {
effect: "minecraft:hunger",
ticks,
amplifier: 0,
})
}
}
Species::WitherSkeleton if who == Who::Player => cx.events.push(MobEvent::EffectPlayer {
effect: "minecraft:wither",
ticks: 200,
@@ -1616,7 +1673,28 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
});
}
match who {
Who::Player => cx.events.push(MobEvent::AttackPlayer(amount, from)),
// The effect picked above goes with the hit: it applies only when
// the player takes damage (a shield-blocked hit gives none).
Who::Player => {
let effect = cx.events[first_event..]
.iter()
.position(|e| matches!(e, MobEvent::EffectPlayer { .. }))
.map(|k| cx.events.remove(first_event + k));
cx.events.push(match effect {
Some(MobEvent::EffectPlayer {
effect,
ticks,
amplifier,
}) => MobEvent::AttackPlayerWithEffect {
amount,
from,
effect,
ticks,
amplifier,
},
_ => MobEvent::AttackPlayer(amount, from),
});
}
Who::Mob(id) => cx.events.push(MobEvent::AttackMob {
target: id,
amount,
@@ -1627,6 +1705,12 @@ pub fn do_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
if super::creaking::is_creaking(m) {
m.voice("entity.creaking.attack", cx.events);
}
// Panda.playAttackSound: playSound(PANDA_BITE, 1.0, 1.0).
if m.species() == Species::Panda && !m.silent {
let at = [m.position.x, m.position.y, m.position.z];
cx.events
.push(MobEvent::Sound("entity.panda.bite", at, 1.0, 1.0));
}
// Axolotl.playAttackSound: playSound(AXOLOTL_ATTACK, 1.0, 1.0).
if m.species() == Species::Axolotl {
let at = [m.position.x, m.position.y, m.position.z];
+5
View File
@@ -133,6 +133,11 @@ pub fn ai_step(m: &mut Mob) {
if m.extra.egg_time > 0 {
m.extra.egg_time -= 1;
}
animate(m);
}
/// `Allay.tick`'s client half: the hold and spin clocks (the server's and a
/// client's).
pub fn animate(m: &mut Mob) {
let holding = m.extra.main_hand.is_some();
let v = &mut m.anim.v;
v[HOLD] = (v[HOLD] + if holding { 1.0 } else { -1.0 }).clamp(0.0, 5.0);
+67 -1
View File
@@ -2,8 +2,10 @@
//! `level().isClientSide()` branches of `aiStep`: nothing of it reaches the
//! server or goes over the network, so the window's game runs it, whether it
//! simulates the world (in-frame) or follows a server.
use super::{Mob, MobEvent, Species};
use super::{Mob, MobEvent, Species, bee};
use horizon_core::geometry::trig::Mth;
use horizon_core::random::RandomSource;
use std::f32::consts::PI;
/// `Enderman.aiStep`, `Endermite.aiStep` and `Blaze.aiStep` on a client:
/// two portal particles a tick around endermen and endermites; two large
@@ -53,3 +55,67 @@ pub fn client_ai_step(m: &mut Mob, out: &mut Vec<MobEvent>) {
out.push(MobEvent::ParticleAt { kind, at, velocity });
}
}
/// `Phantom.tick` and `Bee.tick` on a client, which draw from the client
/// level's random (`random`) and never from the mob's own, so a window that
/// simulates the world keeps the mob's draws as the server has them: a
/// phantom's wings leave mycelium dust, a bee carrying nectar now and then
/// drips it.
pub fn client_particles(m: &Mob, random: &mut impl RandomSource, out: &mut Vec<MobEvent>) {
match m.species() {
Species::Phantom => {
// The wings flap every phantom in a different phase
// (`getUniqueFlapTickOffset`).
let flap = ((m.id.wrapping_mul(3).wrapping_add(m.age)) as i32 as f32
* 7.448451
* (PI / 180.0)
+ PI)
.mcos();
let width = m.width() * 1.48;
let yaw = m.yaw * (PI / 180.0);
let (c, s) = (yaw.mcos() * width, yaw.msin() * width);
let h = (0.3 + flap * 0.45) * m.height() * 2.5;
let p = m.position;
for (dx, dz) in [(c, s), (-c, -s)] {
out.push(MobEvent::ParticleAt {
kind: "mycelium",
at: [p.x + f64::from(dx), p.y + f64::from(h), p.z + f64::from(dz)],
velocity: [0.0; 3],
});
}
}
Species::Bee => {
if !bee::has_nectar(m)
|| !bee::get(m).is_some_and(|b| b.crops_grown < 10)
|| random.next_float() >= 0.05
{
return;
}
// `for (i = 0; i < nextInt(2) + 1; i++)` rolls the bound each time.
let mut i = 0;
while i < random.next_int_bound(2).unwrap_or(0) + 1 {
// Mth.lerp(level.random.nextDouble(), x - 0.3F, x + 0.3F).
let spread = f64::from(0.3_f32);
let lerp = |delta: f64, from: f64, to: f64| from + delta * (to - from);
let x = lerp(
random.next_double(),
m.position.x - spread,
m.position.x + spread,
);
let z = lerp(
random.next_double(),
m.position.z - spread,
m.position.z + spread,
);
out.push(MobEvent::ParticleAt {
kind: "falling_nectar",
// getY(0.5).
at: [x, m.position.y + f64::from(m.height()) * 0.5, z],
velocity: [0.0; 3],
});
i += 1;
}
}
_ => {}
}
}
+6 -4
View File
@@ -128,9 +128,12 @@ pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(0, BreathAir);
g.add(0, TryFindWater::default());
g.add(1, super::dolphin::SwimToTreasure::default());
g.add(2, super::dolphin::SwimWithPlayer::new(4.0));
g.add(4, Stroll::swimming(1.0, 10));
g.add(4, RandomLookAround::default());
g.add(5, LookAtPlayer::new(6.0));
g.add(5, super::dolphin::Jump::new(10));
g.add(6, MeleeAttack::new(1.2, true));
m.ai.targets.add(1, HurtByTarget::new().alert());
m.ai.mov.kind = MoveKind::SmoothSwimming {
@@ -244,11 +247,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
&& m.ai.no_action_time % 10 == 0
{
let amount = 1.0 + m.extra.size as f32;
events.push(MobEvent::AttackPlayer(
// Only when the sting hurt the player.
events.push(MobEvent::AttackPlayerWithEffect {
amount,
[m.position.x, m.position.y, m.position.z],
));
events.push(MobEvent::EffectPlayer {
from: [m.position.x, m.position.y, m.position.z],
effect: "minecraft:poison",
ticks: 60 * m.extra.size,
amplifier: 0,
+407
View File
@@ -0,0 +1,407 @@
//! Armadillos (`Armadillo`, `ArmadilloAi`): a player who sprints or rides
//! nearby, an undead mob or the last attacker scares one into a ball (IDLE,
//! ROLLING, SCARED, UNROLLING); it peeks out now and then, and a ball takes
//! less damage. The brain's `ARMADILLO_SCARE_DETECTED` sensor, its
//! `DANGER_DETECTED_RECENTLY` memory and the `ArmadilloBallUp` behaviour are
//! kept in `State`; the walking behaviours are the goals of `register`.
//! AnimState states: roll out, roll up, peek.
use super::{
Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who,
goals::{
Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone,
},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
pub const IDLE: u8 = 0;
pub const ROLLING: u8 = 1;
pub const SCARED: u8 = 2;
pub const UNROLLING: u8 = 3;
const ROLL_OUT: usize = 0;
const ROLL_UP: usize = 1;
const PEEK: usize = 2;
/// `ArmadilloState.animationDuration`.
fn animation_duration(state: u8) -> i32 {
match state {
ROLLING => 10,
SCARED => 50,
UNROLLING => 30,
_ => 0,
}
}
/// `Armadillo.ARMADILLO_STATE` and the brain's memory and behaviour.
#[derive(Clone, Debug, Default)]
pub struct State {
pub state: u8,
/// `inStateTicks`.
pub in_state_ticks: i32,
/// `DANGER_DETECTED_RECENTLY`: ticks to live, 0 when absent.
danger: i32,
/// Ticks to the sensor's next scan.
sensor: i32,
/// `ArmadilloBallUp`: running, its peek timer and whether it saw the
/// danger around last tick.
ball_up: bool,
next_peek: i32,
danger_was_around: bool,
/// Whether the PANIC activity was the active one after the last tick.
panic_activity: bool,
/// `peekReceivedClient`.
peek_received: bool,
}
pub fn register(m: &mut Mob) {
let mut panic = Panic::new(2.0);
panic.environmental = true;
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, ArmadilloPanic(panic));
g.add(2, Rolled);
g.add(5, Stroll::avoiding_water(1.0));
g.add(6, LookAtPlayer::new(6.0));
g.add(7, RandomLookAround::default());
}
/// `Armadillo.isScared`.
pub fn scared(m: &Mob) -> bool {
m.extra.armadillo.state != IDLE
}
/// `ArmadilloState.shouldHideInShell`: the model shows its shell.
pub fn hiding_in_shell(m: &Mob) -> bool {
let a = &m.extra.armadillo;
match a.state {
ROLLING => a.in_state_ticks > 5,
SCARED => true,
UNROLLING => a.in_state_ticks < 26,
_ => false,
}
}
/// `Armadillo.getState`, as it is synched.
pub fn state(m: &Mob) -> u8 {
m.extra.armadillo.state
}
/// `Armadillo.switchToState` and `onSyncedDataUpdated(ARMADILLO_STATE)`.
pub fn set_state(m: &mut Mob, state: u8) {
let a = &mut m.extra.armadillo;
if a.state != state {
a.state = state;
a.in_state_ticks = 0;
}
}
/// `Armadillo.canStayRolledUp`.
fn can_stay_rolled_up(m: &Mob) -> bool {
!m.ai.panicking
&& !m.fluids.in_water
&& !m.fluids.in_lava
&& m.extra.leash.is_none()
&& m.extra.mount.is_none()
&& m.extra.rider.is_none()
}
/// `Entity.playSound(sound)`.
fn play(m: &Mob, events: &mut Vec<MobEvent>, sound: &'static str) {
if !m.silent {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound(sound, at, 1.0, 1.0));
}
}
/// `Armadillo.rollUp`.
fn roll_up(m: &mut Mob, events: &mut Vec<MobEvent>) {
if !scared(m) {
super::creaking::stop_in_place(m);
m.extra.in_love = 0;
if !m.silent {
m.voice("entity.armadillo.roll", events);
}
set_state(m, ROLLING);
}
}
/// `Armadillo.rollOut`.
fn roll_out(m: &mut Mob, events: &mut Vec<MobEvent>) {
if scared(m) {
if !m.silent {
m.voice("entity.armadillo.unroll_finish", events);
}
set_state(m, IDLE);
}
}
/// `Armadillo.hurtServer`: a ball takes half of the damage past the first
/// point.
pub fn reduce_damage(m: &Mob, amount: f32) -> f32 {
if scared(m) {
((amount - 1.0) / 2.0).max(0.0)
} else {
amount
}
}
/// `Armadillo.actuallyHurt`: a hit by a living thing curls it up (and keeps
/// the danger in mind for 80 ticks), a hit by fire and the like unrolls it.
pub fn after_hurt(m: &mut Mob, source: &Damage) {
if m.no_ai || m.health <= 0.0 {
return;
}
let mut events = Vec::new();
if source.attacker.is_some() {
m.extra.armadillo.danger = 80;
if can_stay_rolled_up(m) {
roll_up(m, &mut events);
}
} else if environmental(source.kind) {
roll_out(m, &mut events);
}
m.outbox.append(&mut events);
}
/// `DamageTypeTags.PANIC_ENVIRONMENTAL_CAUSES`.
pub fn environmental(kind: DamageKind) -> bool {
matches!(
kind,
DamageKind::Cactus | DamageKind::OnFire | DamageKind::InFire | DamageKind::Lava
)
}
/// The hurt sound: a ball's is muffled, and it has no ambient sound
/// (`getAmbientSound`, `getHurtSound`); empty is none.
pub fn sounds(m: &Mob) -> [&'static str; 3] {
let [ambient, hurt, death] = m.kind.sounds;
if scared(m) {
["", "entity.armadillo.hurt_reduced", death]
} else {
[ambient, hurt, death]
}
}
/// `EntityTypeTags.UNDEAD`.
fn undead(s: Species) -> bool {
matches!(
s,
Species::Skeleton
| Species::Stray
| Species::WitherSkeleton
| Species::SkeletonHorse
| Species::Bogged
| Species::Parched
| Species::ZombieHorse
| Species::CamelHusk
| Species::Zombie
| Species::ZombieVillager
| Species::ZombifiedPiglin
| Species::Zoglin
| Species::Drowned
| Species::Husk
| Species::ZombieNautilus
| Species::Wither
| Species::Phantom
)
}
/// `Armadillo.isScaredBy` for the nearby living entities: within 7 blocks
/// sideways and 2 up and down, an undead mob, the last attacker, or a
/// player who sprints or rides.
fn scared_by_someone(m: &Mob, w: &MobWorld) -> bool {
let area = m.bounds().inflate(Vec3::new(7.0, 2.0, 7.0));
let attacker =
m.ai.last_hurt_by
.filter(|_| m.age as i32 - m.ai.last_hurt_by_time <= 100);
if let Some(p) = &w.player
&& p.alive
&& !p.spectator
&& p.bounds.intersects(area)
&& (attacker == Some(Who::Player) || p.sprinting || p.riding)
{
return true;
}
w.others_near(area).any(|s| {
s.id != m.id
&& s.alive
&& s.bounds.intersects(area)
&& (undead(s.species) || attacker == Some(Who::Mob(s.id)))
})
}
/// `Armadillo.customServerAiStep`'s brain: memories expire, the scare
/// sensor scans every fifth tick, the core's rolling out, then the
/// `ArmadilloBallUp` behaviour of the PANIC activity.
pub fn server_ai_step(m: &mut Mob, cx: &mut Cx) {
let events = &mut *cx.events;
let a = &mut m.extra.armadillo;
if a.danger > 0 {
a.danger -= 1;
}
a.sensor -= 1;
if a.sensor <= 0 {
a.sensor = 5;
if !can_stay_rolled_up(m) {
m.extra.armadillo.danger = 0;
} else if scared_by_someone(m, cx.w) {
m.extra.armadillo.danger = 80;
}
}
// ARMADILLO_ROLLING_OUT: no danger left in mind.
if m.extra.armadillo.danger == 0 && scared(m) {
roll_out(m, events);
}
if m.extra.armadillo.panic_activity && !m.extra.armadillo.ball_up && m.on_ground && !liquid(m) {
// ArmadilloBallUp.start.
m.extra.armadillo.ball_up = true;
roll_up(m, events);
}
if m.extra.armadillo.ball_up {
ball_up_tick(m, events);
}
let a = &mut m.extra.armadillo;
a.panic_activity = a.danger > 0 && !m.ai.panicking;
}
fn liquid(m: &Mob) -> bool {
m.fluids.in_water || m.fluids.in_lava
}
/// `ArmadilloBallUp.tickOrStop`.
fn ball_up_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if !scared(m) {
// canStillUse is false: stop.
m.extra.armadillo.ball_up = false;
if !can_stay_rolled_up(m) {
roll_out(m, events);
}
return;
}
let a = &mut m.extra.armadillo;
if a.next_peek > 0 {
a.next_peek -= 1;
}
if a.state == ROLLING && a.in_state_ticks > animation_duration(ROLLING) {
set_state(m, SCARED);
if m.on_ground {
play(m, events, "entity.armadillo.land");
}
return;
}
let danger = m.extra.armadillo.danger;
let around = danger > 75;
if around != m.extra.armadillo.danger_was_around {
m.extra.armadillo.next_peek = next_peek_timer(m);
}
m.extra.armadillo.danger_was_around = around;
let state = m.extra.armadillo.state;
if state == SCARED {
if m.extra.armadillo.next_peek == 0 && m.on_ground && around {
peek(m, events);
m.extra.armadillo.next_peek = next_peek_timer(m);
}
if danger < animation_duration(UNROLLING) {
play(m, events, "entity.armadillo.unroll_start");
set_state(m, UNROLLING);
}
} else if state == UNROLLING && danger > animation_duration(UNROLLING) {
set_state(m, SCARED);
}
}
/// `ArmadilloBallUp.pickNextPeekTimer`.
fn next_peek_timer(m: &mut Mob) -> i32 {
animation_duration(SCARED) + m.random.next_int_between_inclusive(100, 400).unwrap_or(100)
}
/// `level.broadcastEntityEvent(body, 64)`; the sound is the client's
/// `playLocalSound`, which the server plays for everyone here.
fn peek(m: &mut Mob, events: &mut Vec<MobEvent>) {
entity_event(m, 64);
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::EntityEvent {
mob: m.id,
event: 64,
at,
});
events.push(MobEvent::Sound("entity.armadillo.peek", at, 1.0, 1.0));
}
/// `Armadillo.handleEntityEvent`: 64 is a peek.
pub fn entity_event(m: &mut Mob, event: u8) {
if event == 64 {
m.extra.armadillo.peek_received = true;
}
}
/// `Armadillo.tick`: the animation states on a client, the ball's head held
/// to its body, and `inStateTicks`. Server and client both run it.
pub fn tick(m: &mut Mob) {
animate(m);
if scared(m) {
// clampHeadRotationToBody with getMaxHeadYRot 0.
m.head_yaw += super::living::wrap(m.body_yaw - m.head_yaw);
}
m.extra.armadillo.in_state_ticks += 1;
}
/// `Armadillo.setupAnimationStates`.
fn animate(m: &mut Mob) {
let age = m.age as f32;
let a = &mut m.extra.armadillo;
let s = &mut m.anim.states;
match a.state {
ROLLING => {
s[ROLL_OUT].stop();
s[ROLL_UP].start_if_stopped(age);
s[PEEK].stop();
}
SCARED => {
s[ROLL_OUT].stop();
s[ROLL_UP].stop();
if a.peek_received {
s[PEEK].stop();
a.peek_received = false;
}
if a.in_state_ticks == 0 {
s[PEEK].start(age);
s[PEEK].fast_forward(animation_duration(SCARED));
} else {
s[PEEK].start_if_stopped(age);
}
}
UNROLLING => {
s[ROLL_OUT].start_if_stopped(age);
s[ROLL_UP].stop();
s[PEEK].stop();
}
_ => {
s[ROLL_OUT].stop();
s[ROLL_UP].stop();
s[PEEK].stop();
}
}
}
/// `ArmadilloAi.ArmadilloPanic`: it unrolls, then runs.
#[derive(Clone, Debug)]
struct ArmadilloPanic(Panic);
impl Goal for ArmadilloPanic {
goal_clone!();
fn flags(&self) -> u8 {
self.0.flags()
}
fn name(&self) -> &'static str {
"Panic"
}
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) {
roll_out(m, cx.events);
self.0.start(m, cx);
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.stop(m, cx);
}
}
/// The behaviours that do not run while the armadillo is a ball: its
/// `MoveToTargetSink` and the idle activity's walking and looking.
#[derive(Clone, Debug)]
struct Rolled;
impl Goal for Rolled {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
scared(m)
}
}
+18 -3
View File
@@ -103,6 +103,17 @@ pub fn has_stung(m: &Mob) -> bool {
pub fn rolling(m: &Mob) -> bool {
flag(m, FLAG_ROLL)
}
/// A client's bee from the server's `DATA_FLAGS_ID` and `DATA_ANGER_END_TIME`
/// (the texture and the roll read them).
pub fn set_synced(m: &mut Mob, flags: Option<u8>, anger_end: Option<i64>) {
let b = st(m);
if let Some(flags) = flags {
b.flags = flags;
}
if let Some(anger_end) = anger_end {
b.anger_end = anger_end;
}
}
/// `Bee.setHasNectar`: nectar resets the time without it.
pub fn set_has_nectar(m: &mut Mob, value: bool) {
if value {
@@ -322,19 +333,23 @@ pub fn sting(m: &mut Mob, who: Who, cx: &mut Cx) {
let amount = (m.attrs.attack_damage as i32) as f32;
match who {
Who::Player => {
cx.events.push(MobEvent::AttackPlayer(amount, from));
// Poison only on normal (10 s) and hard (18 s).
// Bee.doHurtTarget: the poison only when the sting hurt, and
// only on normal (10 s) and hard (18 s).
let seconds = match cx.w.difficulty.id {
2 => 10,
3 => 18,
_ => 0,
};
if seconds > 0 {
cx.events.push(MobEvent::EffectPlayer {
cx.events.push(MobEvent::AttackPlayerWithEffect {
amount,
from,
effect: "minecraft:poison",
ticks: seconds * 20,
amplifier: 0,
});
} else {
cx.events.push(MobEvent::AttackPlayer(amount, from));
}
}
Who::Mob(id) => cx.events.push(MobEvent::AttackMob {
+7 -7
View File
@@ -59,11 +59,11 @@ pub struct Goat {
pub ramming_x_head_rot: f32,
}
impl Goat {
pub fn from_mob(_m: &Mob) -> Self {
pub fn from_mob(m: &Mob) -> Self {
Self {
left_horn: true,
right_horn: true,
ramming_x_head_rot: 0.0,
left_horn: !m.extra.lost_horns[0],
right_horn: !m.extra.lost_horns[1],
ramming_x_head_rot: super::goat::ramming_x_head_rot(m),
}
}
}
@@ -960,7 +960,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
match m.species() {
Species::Goat => goat(p, s, &Goat::from_mob(m)),
Species::PolarBear => polar_bear(p, s, super::polar_bear::standing_scale(m, s.partial)),
Species::Panda => panda(p, s, &Panda::default()),
Species::Panda => panda(p, s, &super::panda::pose(m, s.partial)),
Species::Llama | Species::TraderLlama => {
llama(p, s, m.extra.chested && !s.baby);
}
@@ -1008,7 +1008,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
p,
s,
&Armadillo {
hiding_in_shell: false,
hiding_in_shell: super::armadillo::hiding_in_shell(m),
roll_out: st[0],
roll_up: st[1],
peek: st[2],
@@ -1029,7 +1029,7 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
a,
),
Species::Rabbit => rabbit(p, s, &st[0], &st[1], a),
Species::Fox => fox(p, s, &Fox::default(), a),
Species::Fox => fox(p, s, &super::fox::pose(m, s.partial), a),
_ => return false,
}
true
+17 -1
View File
@@ -146,6 +146,16 @@ impl Mob {
if self.species() == super::Species::Rabbit {
return super::rabbit::move_control(self, w);
}
// Fox.FoxMoveControl.tick: still while asleep, sitting or faceplanted.
if self.species() == super::Species::Fox && !super::fox::can_move(self) {
return;
}
// Panda.PandaMoveControl: only while it can act.
if self.species() == super::Species::Panda
&& !super::panda::can_perform_action(self, w.thundering)
{
return;
}
if self.species() == super::Species::Turtle {
return super::turtle::move_control(self);
}
@@ -328,6 +338,11 @@ impl Mob {
/// LookControl.tick (and SmoothSwimmingLookControl).
pub fn look_control_tick(&mut self) {
let look = self.ai.look.clone();
let fox = self.species() == super::Species::Fox;
// Fox.FoxLookControl: no turning in sleep.
if fox && super::fox::flag(self, super::fox::SLEEPING) {
return;
}
if look.kind == LookKind::HappyGhast {
return super::happy_ghast::look_control(self);
}
@@ -374,7 +389,8 @@ impl Mob {
// clampHeadRotationToBody does nothing for a shulker.
}
LookKind::Default | LookKind::Fixed => {
if look.kind == LookKind::Default {
// FoxLookControl.resetXRotOnTick keeps a stalking or pouncing pitch.
if look.kind == LookKind::Default && (!fox || super::fox::resets_x_rot(self)) {
self.head_pitch = 0.0;
}
if look.cooldown > 0 {
+12 -2
View File
@@ -70,6 +70,16 @@ pub fn sound(m: &Mob, what: &str) -> &'static str {
}
/// `CopperGolem.setupAnimationStates` (client) and the sound of the head spin.
pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
if animate(m) {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0));
}
}
/// `CopperGolem.setupAnimationStates`, for the server and a client alike;
/// returns whether the head spin sound plays now (a client's sound is the
/// server's `LocalSound`).
pub fn animate(m: &mut Mob) -> bool {
let mut spin = false;
let age = m.age as f32;
let state = m.extra.variant3;
let st = &mut m.anim.states;
@@ -93,8 +103,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
m.extra.ints[0] = tick + 200 + r.next_int_bound(40).unwrap_or(0);
}
if tick == m.extra.ints[0] + 10 {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::LocalSound(sound(m, "spin"), at, 1.0, 1.0));
spin = true;
m.extra.ints[0] = 0;
}
}
@@ -106,6 +115,7 @@ pub fn ai_step(m: &mut Mob, _w: &MobWorld, events: &mut Vec<MobEvent>) {
}
_ => {}
}
spin
}
/// `CopperGolem.updateWeathering` on the level random: the first tick sets
/// the next weathering tick, which advances the weather state; once
+49 -21
View File
@@ -152,8 +152,26 @@ pub fn sway(m: &mut Mob, events: &mut Vec<MobEvent>) {
}
/// `Creaking.doHurtTarget`: the attack animation (the sound is the
/// `playAttackSound` that ends `Mob.doHurtTarget`).
pub fn on_attack(m: &mut Mob, _events: &mut Vec<MobEvent>) {
pub fn on_attack(m: &mut Mob, events: &mut Vec<MobEvent>) {
m.extra.ints[ATTACKING] = ATTACK_TICKS;
broadcast(m, 4, events);
}
/// `Level.broadcastEntityEvent` for a creaking (guests run `entity_event`).
fn broadcast(m: &Mob, event: i8, events: &mut Vec<MobEvent>) {
events.push(MobEvent::EntityEvent {
mob: m.id,
event,
at: [m.position.x, m.position.y, m.position.z],
});
}
/// `Creaking.handleEntityEvent` on a client: 66 the invulnerability flash,
/// 4 the attack swing (the sounds are the server's).
pub fn entity_event(m: &mut Mob, event: u8) {
match event {
66 => m.extra.ints[INVULNERABLE] = INVULNERABILITY_TICKS,
4 => m.extra.ints[ATTACKING] = ATTACK_TICKS,
_ => {}
}
}
/// The heart this creaking is bound to protects it (`isProtector`); a link
/// read from a save is trusted until the heart resolves it.
@@ -176,15 +194,12 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if heart_bound(m) && m.alive() && !protected(m, w) {
m.health = 0.0;
}
for slot in [INVULNERABLE, ATTACKING] {
if m.extra.ints[slot] > 0 {
m.extra.ints[slot] -= 1;
}
// hurtServer set the invulnerability clock since the last tick: entity
// event 66.
if m.extra.ints[INVULNERABLE] == INVULNERABILITY_TICKS {
broadcast(m, 66, events);
}
let age = m.age as f32;
m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age);
m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age);
m.anim.states[2].animate_when(tearing_down(m), age);
animate(m);
if m.extra.counter & HURT != 0 {
// hurtServer: sway, and the heart reacts to a player's hit.
if protected(m, w) {
@@ -200,18 +215,6 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
}
m.extra.counter &= !(HURT | HURT_BY_PLAYER);
}
// checkEyeBlink: the eyes of a creaking falling apart flicker.
if m.death_time > m.extra.ints[NEXT_FLICKER] {
let glowing = m.extra.ints[EYES] != 0;
let (lo, hi) = if glowing {
(2, 8)
} else {
(m.death_time / 4, m.death_time / 2)
};
let span = (hi - lo + 1).max(1);
m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0);
m.extra.ints[EYES] = i32::from(!glowing);
}
if !m.alive() {
return;
}
@@ -226,6 +229,31 @@ pub fn update(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.extra.flag2 = !now;
}
}
/// The clocks and keyframe states `Creaking.aiStep`, `setupAnimationStates`
/// and `checkEyeBlink` run (the server's and a client's).
pub fn animate(m: &mut Mob) {
for slot in [INVULNERABLE, ATTACKING] {
if m.extra.ints[slot] > 0 {
m.extra.ints[slot] -= 1;
}
}
let age = m.age as f32;
m.anim.states[0].animate_when(m.extra.ints[ATTACKING] > 0, age);
m.anim.states[1].animate_when(m.extra.ints[INVULNERABLE] > 0, age);
m.anim.states[2].animate_when(tearing_down(m), age);
// checkEyeBlink: the eyes of a creaking falling apart flicker.
if m.death_time > m.extra.ints[NEXT_FLICKER] {
let glowing = m.extra.ints[EYES] != 0;
let (lo, hi) = if glowing {
(2, 8)
} else {
(m.death_time / 4, m.death_time / 2)
};
let span = (hi - lo + 1).max(1);
m.extra.ints[NEXT_FLICKER] = m.death_time + lo + m.random.next_int_bound(span).unwrap_or(0);
m.extra.ints[EYES] = i32::from(!glowing);
}
}
/// `Mob.stopInPlace`.
pub fn stop_in_place(m: &mut Mob) {
m.nav_stop();
+265
View File
@@ -0,0 +1,265 @@
//! Dolphin goals: `DolphinSwimToTreasureGoal`, `DolphinSwimWithPlayerGoal`
//! and `DolphinJumpGoal`. `extra.flag` is `gotFish` and `extra.home` the
//! `treasurePos` the game found for it (`MobEvent::DolphinTreasure`).
use super::{
Mob, MobEvent, Who,
goals::{Cx, Goal, JUMP, LOOK, MOVE, goal_clone, reduced},
};
use crate::blocks::Fluid;
use horizon_core::random::RandomSource;
/// `Entity.getMotionDirection`: the horizontal step of the yaw
/// (`Direction.fromYRot`: south, west, north, east).
fn motion_step(yaw: f32) -> [i32; 2] {
match (yaw / 90.0 + 0.5).floor() as i32 & 3 {
0 => [0, 1],
1 => [-1, 0],
2 => [0, -1],
_ => [1, 0],
}
}
/// `DolphinSwimToTreasureGoal`: a dolphin that was fed a fish leads the way to
/// a shipwreck or an ocean ruin within 50 sectors.
#[derive(Clone, Debug, Default)]
pub struct SwimToTreasure {
stuck: bool,
}
impl SwimToTreasure {
/// `BlockPos.containing(x, dolphin.getY(), z).closerToCenterThan(position, 4)`.
fn arrived(m: &Mob) -> bool {
let Some(t) = m.extra.home else { return false };
let d = [
f64::from(t[0]) + 0.5 - m.position.x,
m.position.y.floor() + 0.5 - m.position.y,
f64::from(t[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 16.0
}
}
impl Goal for SwimToTreasure {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn interruptable(&self) -> bool {
false
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.flag && m.air >= 100
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
m.extra.home.is_some() && !Self::arrived(m) && !self.stuck && m.air >= 100
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.stuck = false;
m.nav_stop();
// The game looks for the structure and sets the position, or none.
m.extra.home = None;
cx.events.push(MobEvent::DolphinTreasure { mob: m.id });
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
if m.extra.home.is_none() || Self::arrived(m) || self.stuck {
m.extra.flag = false;
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(t) = m.extra.home else { return };
let close = m.ai.nav.target_pos.is_some_and(|p| {
let d = [
f64::from(p[0]) + 0.5 - m.position.x,
f64::from(p[1]) + 0.5 - m.position.y,
f64::from(p[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < 144.0
});
if !close && !m.ai.nav.is_done() {
return;
}
let treasure = [
f64::from(t[0]) + 0.5,
f64::from(t[1]) + 0.5,
f64::from(t[2]) + 0.5,
];
let eighth = f64::from(std::f32::consts::FRAC_PI_8);
let half = f64::from(std::f32::consts::FRAC_PI_2);
let mut next = m.default_random_pos_towards(cx.w, 16, 1, treasure, eighth);
if next.is_none() {
next = m.default_random_pos_towards(cx.w, 8, 4, treasure, half);
}
// isPathfindable(WATER) is a water fluid state.
if let Some(n) = next
&& cx.w.fluid(
n[0].floor() as i32,
n[1].floor() as i32,
n[2].floor() as i32,
) != Fluid::Water
{
next = m.default_random_pos_towards(cx.w, 8, 5, treasure, half);
}
let Some(next) = next else {
self.stuck = true;
return;
};
let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot);
m.look_at_speed(next, y, x);
m.nav_move_to(cx.w, next, 1.3);
if m.random.next_int_bound(80).unwrap_or(1) == 0 {
// Entity event 38: happy villager particles about the dolphin.
cx.events.push(MobEvent::AroundSelf {
mob: m.id,
event: 38,
kind: "happy_villager",
feet: [m.position.x, m.position.y, m.position.z],
width: f64::from(m.width()),
height: f64::from(m.height()),
burst: crate::particles::Burst::DOLPHIN,
});
}
}
}
/// `DolphinSwimWithPlayerGoal`: swim up to a swimming player and give them
/// Dolphin's Grace.
#[derive(Clone, Debug)]
pub struct SwimWithPlayer {
speed: f64,
}
impl SwimWithPlayer {
pub fn new(speed: f64) -> Self {
Self { speed }
}
}
impl Goal for SwimWithPlayer {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
// getNearestPlayer(forNonCombat().range(10).ignoreLineOfSight()).
m.can_see_player_through_walls(cx.w, 10.0)
&& cx.w.player.as_ref().is_some_and(|p| p.swimming)
&& m.ai.target != Some(Who::Player)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
cx.w.player
.as_ref()
.is_some_and(|p| p.swimming && m.distance_sqr(p.position) < 256.0)
}
fn start(&mut self, _: &mut Mob, cx: &mut Cx) {
cx.events.push(grace());
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.nav_stop();
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(p) = cx.w.player.clone() else { return };
let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot);
m.look_at_speed(p.eye, y, x);
if m.distance_sqr(p.position) < 6.25 {
m.nav_stop();
} else {
m.nav_move_to_entity(
cx.w,
[p.position.x, p.position.y, p.position.z],
1,
self.speed,
);
}
if p.swimming && m.random.next_int_bound(6).unwrap_or(1) == 0 {
cx.events.push(grace());
}
}
}
/// `MobEffectInstance(DOLPHINS_GRACE, 100)`.
fn grace() -> MobEvent {
MobEvent::EffectPlayer {
effect: "minecraft:dolphins_grace",
ticks: 100,
amplifier: 0,
}
}
/// `DolphinJumpGoal`: leap out of clear water and arc back in.
#[derive(Clone, Debug)]
pub struct Jump {
interval: i32,
breached: bool,
}
impl Jump {
pub fn new(interval: i32) -> Self {
Self {
interval: reduced(interval),
breached: false,
}
}
}
impl Goal for Jump {
goal_clone!();
fn flags(&self) -> u8 {
JUMP | MOVE
}
fn interruptable(&self) -> bool {
false
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if m.random.next_int_bound(self.interval).unwrap_or(1) != 0 {
return false;
}
let [sx, sz] = motion_step(m.yaw);
let (bx, by, bz) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let w = cx.w;
[0, 1, 4, 5, 6, 7].into_iter().all(|i| {
let (x, z) = (bx + sx * i, bz + sz * i);
// waterIsClear, then surfaceIsClear.
w.fluid(x, by, z) == Fluid::Water
&& !w.has_tag("minecraft:blocks_dolphin_jump", w.block_name(x, by, z))
&& w.facts.is_air(w.world.block(x, by + 1, z))
&& w.facts.is_air(w.world.block(x, by + 2, z))
})
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
let yd = m.velocity.y;
(yd * yd >= f64::from(0.03f32)
|| m.head_pitch == 0.0
|| m.head_pitch.abs() >= 10.0
|| !m.fluids.in_water)
&& !m.on_ground
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
let [sx, sz] = motion_step(m.yaw);
m.velocity.x += f64::from(sx) * 0.6;
m.velocity.y += 0.7;
m.velocity.z += f64::from(sz) * 0.6;
m.nav_stop();
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
m.head_pitch = 0.0;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let already = self.breached;
if !already {
self.breached = cx.w.fluid(
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
) == Fluid::Water;
}
if self.breached && !already {
m.sound("entity.dolphin.jump", cx.events);
}
let v = m.velocity;
if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 {
// Mth.rotLerp(0.2, xRot, 0).
m.head_pitch += 0.2 * super::living::wrap(0.0 - m.head_pitch);
} else if v.length() > f64::from(1.0e-5f32) {
let horizontal = v.x.hypot(v.z);
m.head_pitch = ((-v.y).atan2(horizontal) * f64::from(180.0f32)
/ f64::from(std::f32::consts::PI)) as f32;
}
}
}
+19 -8
View File
@@ -244,7 +244,13 @@ pub fn slot_item(m: &Mob, slot: &str) -> Option<LootStack> {
}
_ => (None, None),
};
let mut stack = loot_stack(item?, 1);
// A panda keeps the whole stack it picked up in its mouth.
let count = if slot == "mainhand" && m.species() == Species::Panda {
super::panda::held_count(m)
} else {
1
};
let mut stack = loot_stack(item?, count as i32);
if let (Some(index), Some(g)) = (index, gear::gear(m)) {
for (e, l) in &g.slots[index] {
stack.enchantments.push((e.to_string(), *l as i32));
@@ -305,6 +311,7 @@ fn loot_stack(item: &str, count: i32) -> LootStack {
exploration: None,
ominous_amplifier: None,
stew_effects: Vec::new(),
names: Vec::new(),
}
}
/// `Mob.dropChances.byEquipment(slot)`: the recorded chance, or the one the
@@ -504,13 +511,7 @@ pub fn die(m: &mut Mob, d: &Death, sequences: &mut RandomSequences) -> (Vec<Drop
}
}
// dropExperience.
let drops_experience = match s {
Species::Tadpole => false,
Species::Hoglin => true,
s if is_monster(s) => true,
_ => !m.is_baby(),
};
if killed_by_player && drops_experience && d.mob_drops {
if killed_by_player && drops_experience(m) && d.mob_drops {
let mut amount = base_experience(m);
while amount > 0 {
let value = orb_value(amount);
@@ -534,6 +535,16 @@ fn roll(
None => Vec::new(),
}
}
/// `LivingEntity.shouldDropExperience`: babies drop none, except monsters and
/// hoglins; tadpoles never do.
pub fn drops_experience(m: &Mob) -> bool {
match m.species() {
Species::Tadpole => false,
Species::Hoglin => true,
s if is_monster(s) => true,
_ => !m.is_baby(),
}
}
/// `getBaseExperienceReward` (no vanilla enchantment changes mob experience).
pub fn base_experience(m: &mut Mob) -> i32 {
use Species as S;
@@ -97,10 +97,26 @@ pub fn teleport_to(
return false;
}
let old = m.center();
let old_block = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
m.position = Vec3::new(x, ny, z);
m.previous = m.position;
m.velocity = Vec3::ZERO;
m.ai.nav.stop();
if !m.silent {
// Level event 2018: the portal trail, from the old block to the new
// one, packed as `BlockUtil.clampedPackDifferenceInPosition` does.
let new_block = [x.floor() as i32, ny.floor() as i32, z.floor() as i32];
let packed = |k: usize| ((new_block[k] - old_block[k]).clamp(-127, 127) + 127) & 255;
events.push(MobEvent::LevelEvent {
id: 2018,
pos: old_block,
data: packed(0) << 16 | packed(1) << 8 | packed(2),
});
}
events.push(MobEvent::Sound("entity.enderman.teleport", old, 1.0, 1.0));
events.push(MobEvent::Sound(
"entity.enderman.teleport",
+2 -8
View File
@@ -1691,13 +1691,7 @@ impl<L: FinalizeLevel + ?Sized, R: RandomSource> Ctx<'_, L, R> {
let hidden = panda_gene(self.int(16));
m.extra.variant = main;
m.extra.variant2 = hidden;
let shown = panda_variant(main, hidden);
if shown == 5 {
set_base(m, Attr::MaxHealth, 10.0);
}
if shown == 1 {
set_base(m, Attr::MovementSpeed, f64::from(0.07f32));
}
super::panda::set_attributes(m);
self.ageable(m, g.or(Some(Group::Ageable(Ageable::chance(0.2)))))
}
S::PolarBear | S::Ocelot => {
@@ -1950,7 +1944,7 @@ fn set_memory(m: &mut Mob, name: &'static str, value: i64, ttl: i64) {
}
/// `Panda.Gene.getRandom` (enum order: normal, lazy, worried, playful,
/// brown, weak, aggressive).
fn panda_gene(roll: i32) -> u8 {
pub fn panda_gene(roll: i32) -> u8 {
match roll {
0 => 1,
1 => 2,
+845
View File
@@ -0,0 +1,845 @@
//! Foxes (`net.minecraft.world.entity.animal.fox.Fox`): the goal list, the
//! flags byte (sleeping, sitting, crouching, interested, pouncing,
//! faceplanted), stalking and pouncing, napping in the shade by day, seeking
//! shelter, perching, eating berries and the food held in the mouth.
//! Picking up items, strolling through villages and trusting players (with
//! defending them) are not ported yet.
use super::{
Mob, MobEvent, MobWorld, Seen, Species,
goals::{
Avoid, AvoidEntity, Breed, Cx, Float, FollowParent, Goal, JUMP, LOOK, LeapAtTarget,
LookAtPlayer, MOVE, MeleeAttack, MoveToBlock, NearestTarget, Panic, Prey, Stroll,
goal_clone, hide_pos, reduced,
},
living::wrap,
};
use horizon_core::{
geometry::{Axis, Vec3},
jmath,
random::RandomSource,
};
use horizon_world::registry::BlockStateId;
// Fox.DATA_FLAGS_ID, kept in `extra.ints[0]` (and sent to clients as is).
pub const SITTING: i32 = 1;
pub const CROUCHING: i32 = 4;
pub const INTERESTED: i32 = 8;
pub const POUNCING: i32 = 16;
pub const SLEEPING: i32 = 32;
pub const FACEPLANTED: i32 = 64;
pub const DEFENDING: i32 = 128;
/// `Fox.ticksSinceEaten`.
const TICKS_SINCE_EATEN: usize = 1;
/// `Fox.interestedAngle` and `crouchAmount` in `anim.v`, the previous tick's
/// values in `anim.vo`.
const INTERESTED_ANGLE: usize = 0;
const CROUCH_AMOUNT: usize = 1;
/// `Fox.MAX_CROUCH_AMOUNT`.
const MAX_CROUCH_AMOUNT: f32 = 5.0;
pub fn flag(m: &Mob, f: i32) -> bool {
m.extra.ints[0] & f != 0
}
fn set_flag(m: &mut Mob, f: i32, on: bool) {
if on {
m.extra.ints[0] |= f;
} else {
m.extra.ints[0] &= !f;
}
}
/// `Fox.clearStates`.
fn clear_states(m: &mut Mob) {
m.extra.ints[0] = 0;
}
/// `Fox.canMove`, which `FoxMoveControl` waits for.
pub fn can_move(m: &Mob) -> bool {
!flag(m, SLEEPING | SITTING | FACEPLANTED)
}
/// `FoxLookControl.resetXRotOnTick`: stalking and pouncing keep their pitch.
pub fn resets_x_rot(m: &Mob) -> bool {
!flag(m, POUNCING | CROUCHING | INTERESTED | FACEPLANTED)
}
/// `Fox.registerGoals` and `setTargetGoals` (the targets wait for the variant:
/// red foxes prefer chickens and rabbits, snow foxes fish).
pub fn register(m: &mut Mob) {
let countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0);
let g = &mut m.ai.goals;
g.add(0, Wrap::new(Float).on_start(clear_states));
g.add(1, Faceplant { countdown: 0 });
g.add(2, Panic::new(2.2));
g.add(3, Wrap::new(Breed::new(1.0)).on_start(clear_states));
// AVOID_PLAYERS: not a sneaking player.
g.add(
4,
AvoidEntity::new(Avoid::Player, 16.0, 1.6, 1.4)
.player_when(|p| !p.sneaking && !p.spectator),
);
g.add(
4,
AvoidEntity::new(Avoid::Species(vec![Species::Wolf]), 8.0, 1.6, 1.4).seen_when(|s| !s.tame),
);
g.add(
4,
AvoidEntity::new(Avoid::Species(vec![Species::PolarBear]), 8.0, 1.6, 1.4),
);
g.add(5, StalkPrey);
g.add(6, Pounce);
g.add(6, SeekShelter::new(1.25));
g.add(
7,
Wrap::new(MeleeAttack::new(1.2, true))
.when(
|m| !flag(m, SITTING | SLEEPING | CROUCHING | FACEPLANTED),
false,
)
.on_start(|m| set_flag(m, INTERESTED, false)),
);
g.add(7, Sleep { countdown });
g.add(8, Wrap::new(FollowParent::new(1.25)).on_start(clear_states));
g.add(10, EatBerries::new());
g.add(10, LeapAtTarget::new(0.4));
g.add(11, Stroll::avoiding_water(1.0));
// FoxLookAtPlayerGoal: not with the nose in the snow or while stalking.
g.add(
12,
Wrap::new(LookAtPlayer::new(24.0)).when(|m| !flag(m, FACEPLANTED | INTERESTED), true),
);
g.add(13, Perch::default());
let red = |m: &Mob, _: &MobWorld| m.extra.variant == 0;
let snow = |m: &Mob, _: &MobWorld| m.extra.variant != 0;
let land = || NearestTarget::new(Prey::Filter(chicken_or_rabbit), false).interval(10);
let turtle = || NearestTarget::new(Prey::Filter(baby_turtle_on_land), false).interval(10);
let fish = || NearestTarget::new(Prey::Filter(schooling_fish), false).interval(20);
let t = &mut m.ai.targets;
t.add(4, land().gate(red));
t.add(4, turtle().gate(red));
t.add(6, fish().gate(red));
t.add(4, fish().gate(snow));
t.add(6, land().gate(snow));
t.add(6, turtle().gate(snow));
}
fn chicken_or_rabbit(s: &Seen) -> bool {
matches!(s.species, Species::Chicken | Species::Rabbit)
}
fn baby_turtle_on_land(s: &Seen) -> bool {
s.species == Species::Turtle && s.baby && !s.in_water
}
fn schooling_fish(s: &Seen) -> bool {
matches!(
s.species,
Species::Cod | Species::Salmon | Species::TropicalFish
)
}
/// The part of `Fox.tick` a client runs too: the head tilt eases toward the
/// interested flag and the crouch builds up to 5 while crouching.
pub fn client_tick(m: &mut Mob) {
let (interested, crouching) = (flag(m, INTERESTED), flag(m, CROUCHING));
let v = &mut m.anim.v;
m.anim.vo[INTERESTED_ANGLE] = v[INTERESTED_ANGLE];
v[INTERESTED_ANGLE] += (if interested { 1.0 } else { 0.0 } - v[INTERESTED_ANGLE]) * 0.4;
m.anim.vo[CROUCH_AMOUNT] = v[CROUCH_AMOUNT];
v[CROUCH_AMOUNT] = if crouching {
(v[CROUCH_AMOUNT] + 0.2).min(MAX_CROUCH_AMOUNT)
} else {
0.0
};
}
/// `Fox.isFullyCrouched`.
fn fully_crouched(m: &Mob) -> bool {
m.anim.v[CROUCH_AMOUNT] == MAX_CROUCH_AMOUNT
}
/// `Fox.tick` and the eating part of `Fox.aiStep`.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
client_tick(m);
if !m.alive() {
return;
}
m.extra.ints[TICKS_SINCE_EATEN] += 1;
if let Some(item) = m.extra.main_hand.clone()
&& eats(w, &item)
&& m.ai.target.is_none()
&& m.on_ground
&& !flag(m, SLEEPING)
{
let eaten = m.extra.ints[TICKS_SINCE_EATEN];
if eaten > 600 {
// ItemStack.finishUsingItem: the food is gone, a use remainder stays.
m.extra.main_hand = w
.items
.and_then(|i| i.items.get(&item))
.and_then(|i| i.use_remainder.as_deref())
.map(Into::into);
m.extra.ints[TICKS_SINCE_EATEN] = 0;
} else if eaten > 560 && m.random.next_float() < 0.1 {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound("entity.fox.eat", at, 1.0, 1.0));
}
}
if !m.target_info(w).is_some_and(|t| t.alive) {
set_flag(m, CROUCHING | INTERESTED, false);
}
let in_water = m.fluids.in_water;
if in_water || m.ai.target.is_some() || w.thundering {
set_flag(m, SLEEPING, false);
}
if in_water || flag(m, SLEEPING) {
set_flag(m, SITTING, false);
}
// Faceplanted: crumbs of the snow now and then (level event 2001).
if flag(m, FACEPLANTED) && m.random.next_float() < 0.2 {
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
events.push(MobEvent::LevelEvent {
id: 2001,
pos: at,
data: w.world.block(at[0], at[1], at[2]).0 as i32,
});
}
}
/// `Fox.aiStep` before the living step: a sleeping fox takes no input.
pub fn pre_ai_step(m: &mut Mob) {
if flag(m, SLEEPING) {
m.ai.jumping = false;
m.ai.xxa = 0.0;
m.ai.zza = 0.0;
}
}
/// `Fox.isConsumableFood`: the item has food and consumable components.
fn eats(w: &MobWorld, item: &str) -> bool {
w.items
.and_then(|i| i.items.get(item))
.is_some_and(|i| i.food.is_some() && i.consumable.is_some())
}
/// `Fox.FoxBehaviorGoal.hasShelter`: out of the sky's sight and not a bad spot.
fn has_shelter(m: &Mob, w: &MobWorld) -> bool {
let at = [
m.position.x.floor() as i32,
m.bounds().max(Axis::Y).floor() as i32,
m.position.z.floor() as i32,
];
!w.can_see_sky(at[0], at[1], at[2]) && m.walk_target_value(w, at) >= 0.0
}
/// `Fox.FoxBehaviorGoal.alertable`: someone within 12 blocks the fox would
/// keep watch over (`FoxAlertableEntitiesSelector`).
fn alertable(m: &Mob, w: &MobWorld) -> bool {
let (from, id, y) = (m.position, m.id, m.position.y);
let mob = w
.nearby(from, 12.0, |s: &Seen| {
s.id != id
&& (s.position.y - y).abs() <= 6.0
&& m.distance_sqr(s.position) <= 144.0
&& match s.species {
Species::Fox => false,
Species::Chicken | Species::Rabbit => true,
Species::Wolf | Species::Cat | Species::Parrot | Species::Nautilus => !s.tame,
_ => true,
}
})
.next()
.is_some();
mob || w.player.as_ref().is_some_and(|p| {
p.alive
&& !p.creative
&& !p.spectator
&& !p.sneaking
&& (p.position.y - y).abs() <= 6.0
&& m.distance_sqr(p.position) <= 144.0
})
}
/// `Fox.SleepGoal`: nap in the shade by day when nothing is around.
#[derive(Clone, Debug)]
struct Sleep {
countdown: i32,
}
impl Sleep {
fn can_sleep(&mut self, m: &Mob, w: &MobWorld) -> bool {
if self.countdown > 0 {
self.countdown -= 1;
return false;
}
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
w.daylight
&& has_shelter(m, w)
&& !alertable(m, w)
&& w.block_name(x, y, z) != "minecraft:powder_snow"
}
}
impl Goal for Sleep {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK | JUMP
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.ai.nav.is_done() && (self.can_sleep(m, cx.w) || flag(m, SLEEPING))
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.can_sleep(m, cx.w)
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
set_flag(m, SITTING | CROUCHING | INTERESTED, false);
m.ai.jumping = false;
set_flag(m, SLEEPING, true);
m.nav_stop();
let p = m.position;
m.ai.mov.set_wanted(p.x, p.y, p.z, 0.0);
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
self.countdown = m.random.next_int_bound(reduced(140)).unwrap_or(0);
clear_states(m);
}
}
/// A shared goal under the fox's own conditions and start-up: the extra
/// `canUse` of `FoxMeleeAttackGoal` and `FoxLookAtPlayerGoal` and the
/// `clearStates` or `setIsInterested(false)` its subclasses do in `start`.
#[derive(Clone, Debug)]
struct Wrap<G> {
goal: G,
when: Option<fn(&Mob) -> bool>,
/// The condition also applies to `canContinueToUse`.
both: bool,
on_start: Option<fn(&mut Mob)>,
}
impl<G: Goal + Clone + 'static> Wrap<G> {
fn new(goal: G) -> Self {
Self {
goal,
when: None,
both: false,
on_start: None,
}
}
fn when(mut self, f: fn(&Mob) -> bool, both: bool) -> Self {
(self.when, self.both) = (Some(f), both);
self
}
fn on_start(mut self, f: fn(&mut Mob)) -> Self {
self.on_start = Some(f);
self
}
}
impl<G: Goal + Clone + 'static> Goal for Wrap<G> {
goal_clone!();
fn flags(&self) -> u8 {
self.goal.flags()
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.when.is_none_or(|f| f(m)) && self.goal.can_use(m, cx)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
(!self.both || self.when.is_none_or(|f| f(m))) && self.goal.can_continue(m, cx)
}
fn interruptable(&self) -> bool {
self.goal.interruptable()
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
if let Some(f) = self.on_start {
f(m);
}
self.goal.start(m, cx);
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
self.goal.stop(m, cx);
}
fn every_tick(&self) -> bool {
self.goal.every_tick()
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.goal.tick(m, cx);
}
fn name(&self) -> &'static str {
self.goal.name()
}
}
/// `Fox.isPathClear`: six points along the way to the target, each with
/// nothing but replaceable blocks in the three above it.
fn path_clear(m: &Mob, w: &MobWorld, to: Vec3) -> bool {
let (zdiff, xdiff) = (to.z - m.position.z, to.x - m.position.x);
let slope = zdiff / xdiff;
for i in 0..6 {
let step = f64::from(i as f32 / 6.0);
let z = if slope == 0.0 { 0.0 } else { zdiff * step };
let x = if slope == 0.0 {
xdiff * step
} else {
z / slope
};
for j in 1..4 {
let at = [
(m.position.x + x).floor() as i32,
(m.position.y + f64::from(j)).floor() as i32,
(m.position.z + z).floor() as i32,
];
if !w.facts.get(w.world.block(at[0], at[1], at[2])).replaceable {
return false;
}
}
}
true
}
fn signum(x: f64) -> f64 {
if x > 0.0 {
1.0
} else if x < 0.0 {
-1.0
} else {
0.0
}
}
/// `Fox.FaceplantGoal`: stay put for 40 ticks with the nose in the snow.
#[derive(Clone, Debug)]
struct Faceplant {
countdown: i32,
}
impl Goal for Faceplant {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK | JUMP
}
fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
flag(m, FACEPLANTED)
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
flag(m, FACEPLANTED) && self.countdown > 0
}
fn start(&mut self, _: &mut Mob, _: &mut Cx) {
self.countdown = reduced(40);
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
set_flag(m, FACEPLANTED, false);
}
fn tick(&mut self, _: &mut Mob, _: &mut Cx) {
self.countdown -= 1;
}
}
/// `Fox.StalkPreyGoal`: creep up on a chicken or rabbit more than 6 blocks
/// away, then crouch and keep still once it is within 6.
#[derive(Clone, Debug)]
struct StalkPrey;
impl StalkPrey {
fn look(m: &mut Mob, eye: [f64; 3]) {
let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot);
m.look_at_speed(eye, y, x);
}
}
impl Goal for StalkPrey {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if flag(m, SLEEPING) {
return false;
}
let Some(t) = m.target_info(cx.w) else {
return false;
};
let stalkable = match m.ai.target {
Some(super::Who::Mob(id)) => {
cx.w.seen(id)
.is_some_and(|s| matches!(s.species, Species::Chicken | Species::Rabbit))
}
_ => false,
};
t.alive
&& stalkable
&& m.distance_sqr(t.position) > 36.0
&& !flag(m, CROUCHING | INTERESTED)
&& !m.ai.jumping
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
set_flag(m, SITTING | FACEPLANTED, false);
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
match m.target_info(cx.w) {
Some(t) if path_clear(m, cx.w, t.position) => {
set_flag(m, INTERESTED | CROUCHING, true);
m.nav_stop();
Self::look(m, [t.position.x, t.eye_y, t.position.z]);
}
_ => set_flag(m, INTERESTED | CROUCHING, false),
}
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(t) = m.target_info(cx.w) else { return };
Self::look(m, [t.position.x, t.eye_y, t.position.z]);
if m.distance_sqr(t.position) <= 36.0 {
set_flag(m, INTERESTED | CROUCHING, true);
m.nav_stop();
} else {
let at = [t.position.x, t.position.y, t.position.z];
m.nav_move_to_entity(cx.w, at, 0, 1.5);
}
}
}
/// `Fox.FoxPounceGoal`: once fully crouched with a clear path, leap at the
/// target, tilt with the flight and bite when within 2 blocks, or end up with
/// the nose in snow.
#[derive(Clone, Debug)]
struct Pounce;
impl Goal for Pounce {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !fully_crouched(m) {
return false;
}
let Some(t) = m.target_info(cx.w).filter(|t| t.alive) else {
return false;
};
let clear = path_clear(m, cx.w, t.position);
if !clear {
set_flag(m, CROUCHING | INTERESTED, false);
}
clear
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !m.target_info(cx.w).is_some_and(|t| t.alive) {
return false;
}
let yd = m.velocity.y;
(yd * yd >= f64::from(0.05f32) || m.head_pitch.abs() >= 15.0 || !m.on_ground)
&& !flag(m, FACEPLANTED)
}
fn interruptable(&self) -> bool {
false
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.ai.jumping = true;
set_flag(m, POUNCING, true);
set_flag(m, INTERESTED, false);
if let Some(t) = m.target_info(cx.w) {
m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0);
let u = m.position.vector_to(t.position).normalize();
m.velocity = m.velocity.add_vector(Vec3::new(u.x * 0.8, 0.9, u.z * 0.8));
}
m.nav_stop();
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
set_flag(m, CROUCHING | INTERESTED | POUNCING, false);
m.anim.v[CROUCH_AMOUNT] = 0.0;
m.anim.vo[CROUCH_AMOUNT] = 0.0;
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let target = m.target_info(cx.w);
if let Some(t) = &target {
m.look_at_speed([t.position.x, t.eye_y, t.position.z], 60.0, 30.0);
}
if !flag(m, FACEPLANTED) {
let v = m.velocity;
if v.y * v.y < f64::from(0.03f32) && m.head_pitch != 0.0 {
m.head_pitch += 0.2 * wrap(-m.head_pitch);
} else {
let horizontal = v.horizontal_distance();
let bias = if m.ai.jumping && v.y > 0.0 { 6.5 } else { 1.0 };
let y = v.y * bias;
let len = (horizontal * horizontal + y * y).sqrt();
if len > f64::from(1.0e-5f32) {
let pitch = signum(-y) * jmath::acos(horizontal / len) * 180.0
/ f64::from(std::f32::consts::PI);
m.head_pitch = (pitch as f32 % 360.0).clamp(-90.0, 90.0);
}
}
}
if let (Some(t), Some(who)) = (&target, m.ai.target)
&& m.distance_sqr(t.position) <= 4.0
{
super::ai::do_hurt_target(m, who, cx);
} else if m.head_pitch > 0.0
&& m.on_ground
&& m.velocity.y as f32 != 0.0
&& cx.w.block_name(
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
) == "minecraft:snow"
{
m.head_pitch = 60.0;
m.ai.target = None;
set_flag(m, FACEPLANTED, true);
}
}
}
/// `Fox.SeekShelterGoal`: by day, or in a thunderstorm, leave open sky for
/// somewhere the sky does not see. Villages are not told apart yet (vanilla
/// stays put in one).
#[derive(Clone, Debug)]
struct SeekShelter {
speed: f64,
interval: i32,
wanted: [f64; 3],
}
impl SeekShelter {
fn new(speed: f64) -> Self {
Self {
speed,
interval: reduced(100),
wanted: [0.0; 3],
}
}
fn set_wanted_pos(&mut self, m: &mut Mob, w: &MobWorld) -> bool {
hide_pos(m, w).is_some_and(|at| {
self.wanted = at;
true
})
}
}
impl Goal for SeekShelter {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if flag(m, SLEEPING) || m.ai.target.is_some() {
return false;
}
let at = [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
];
let sees_sky = cx.w.can_see_sky(at[0], at[1], at[2]);
if cx.w.thundering && sees_sky {
self.set_wanted_pos(m, cx.w)
} else if self.interval > 0 {
self.interval -= 1;
false
} else {
self.interval = 100;
cx.w.daylight && sees_sky && self.set_wanted_pos(m, cx.w)
}
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
clear_states(m);
m.nav_move_to(cx.w, self.wanted, self.speed);
}
}
/// `Fox.PerchAndSearchGoal`: now and then sit down and look around two to
/// four times when nothing is going on.
#[derive(Clone, Debug, Default)]
struct Perch {
rel: [f64; 2],
look_time: i32,
looks_remaining: i32,
}
impl Perch {
fn reset_look(&mut self, m: &mut Mob) {
let angle = std::f64::consts::TAU * m.random.next_double();
self.rel = [angle.cos(), angle.sin()];
self.look_time = reduced(80 + m.random.next_int_bound(20).unwrap_or(0));
}
}
impl Goal for Perch {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
m.ai.last_hurt_by.is_none()
&& m.random.next_float() < 0.02
&& !flag(m, SLEEPING)
&& m.ai.target.is_none()
&& m.ai.nav.is_done()
&& !alertable(m, cx.w)
&& !flag(m, POUNCING | CROUCHING)
}
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
self.looks_remaining > 0
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
self.reset_look(m);
self.looks_remaining = 2 + m.random.next_int_bound(3).unwrap_or(0);
set_flag(m, SITTING, true);
m.nav_stop();
}
fn stop(&mut self, m: &mut Mob, _: &mut Cx) {
set_flag(m, SITTING, false);
}
fn tick(&mut self, m: &mut Mob, _: &mut Cx) {
self.look_time -= 1;
if self.look_time <= 0 {
self.looks_remaining -= 1;
self.reset_look(m);
}
let at = [
m.position.x + self.rel[0],
m.eye_y(),
m.position.z + self.rel[1],
];
let (y, x) = (m.kind.max_head_y_rot, m.kind.max_head_x_rot);
m.look_at_speed(at, y, x);
}
}
/// `BlockState` with one property changed.
fn with_prop(w: &MobWorld, p: [i32; 3], key: &str, value: &str) -> Option<BlockStateId> {
let mut s = w.registry.state(w.world.block(p[0], p[1], p[2]))?.clone();
s.properties.insert(key.into(), value.into());
w.registry.id(&s)
}
/// `FoxEatBerriesGoal.isValidTarget`: a ripe sweet berry bush or glow berries.
fn has_berries(w: &MobWorld, p: [i32; 3]) -> bool {
match w.block_name(p[0], p[1], p[2]) {
"minecraft:sweet_berry_bush" => w
.prop(p[0], p[1], p[2], "age")
.and_then(|a| a.parse::<i32>().ok())
.is_some_and(|a| a >= 2),
"minecraft:cave_vines" | "minecraft:cave_vines_plant" => {
w.prop(p[0], p[1], p[2], "berries") == Some("true")
}
_ => false,
}
}
/// `Fox.FoxEatBerriesGoal`: walk to a ripe berry bush and pick it after 40 ticks.
#[derive(Clone, Debug)]
struct EatBerries {
block: MoveToBlock,
waited: i32,
}
impl EatBerries {
fn new() -> Self {
Self {
block: MoveToBlock::new(1.2, 12, 1),
waited: 0,
}
}
fn pick(&mut self, m: &mut Mob, cx: &mut Cx) {
let p = self.block.block;
let at = [
f64::from(p[0]) + 0.5,
f64::from(p[1]) + 0.5,
f64::from(p[2]) + 0.5,
];
if cx.w.block_name(p[0], p[1], p[2]) == "minecraft:sweet_berry_bush" {
let age: i32 =
cx.w.prop(p[0], p[1], p[2], "age")
.and_then(|a| a.parse().ok())
.unwrap_or(0);
let mut count = 1 + m.random.next_int_bound(2).unwrap_or(0) + i32::from(age == 3);
if m.extra.main_hand.is_none() {
m.extra.main_hand = Some("minecraft:sweet_berries".into());
count -= 1;
}
if count > 0 {
cx.events.push(MobEvent::DropItem {
item: "minecraft:sweet_berries".into(),
count: count as u32,
at,
});
}
if let Some(state) = with_prop(cx.w, p, "age", "1") {
cx.events.push(MobEvent::SetBlock { pos: p, state });
}
cx.events.push(MobEvent::Sound(
"block.sweet_berry_bush.pick_berries",
at,
1.0,
1.0,
));
} else {
// CaveVines.use: one glow berry, the vine goes back to bare.
cx.events.push(MobEvent::DropItem {
item: "minecraft:glow_berries".into(),
count: 1,
at,
});
if let Some(state) = with_prop(cx.w, p, "berries", "false") {
cx.events.push(MobEvent::SetBlock { pos: p, state });
}
let pitch = 0.8 + m.random.next_float() * 0.4;
cx.events.push(MobEvent::Sound(
"block.cave_vines.pick_berries",
at,
1.0,
pitch,
));
}
}
}
impl Goal for EatBerries {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if flag(m, SLEEPING) {
return false;
}
// MoveToBlockGoal.canUse draws the next delay only once the last one
// has run out.
if self.block.next_start > 0 {
self.block.next_start -= 1;
return false;
}
let next = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
self.block.can_use(m, cx.w, next, has_berries)
}
fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool {
self.block.can_continue(cx.w, has_berries)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.waited = 0;
set_flag(m, SITTING, false);
self.block.start(m, cx.w);
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
if self.block.reached {
if self.waited >= 40 {
if cx.w.mob_griefing {
self.pick(m, cx);
}
} else {
self.waited += 1;
}
} else if m.random.next_float() < 0.05 {
let at = [m.position.x, m.position.y, m.position.z];
cx.events
.push(MobEvent::Sound("entity.fox.sniff", at, 1.0, 1.0));
}
self.block.tick_within(m, cx.w, 2.0);
}
}
/// `FoxRenderState` as the renderer reads it: the flags, `getHeadRollAngle`
/// and `getCrouchAmount` at the partial tick. `FoxModel.legMotionPos` gains
/// 0.67 a frame; this takes 60 frames a second.
pub fn pose(m: &Mob, partial: f32) -> super::body_anim::Fox {
super::body_anim::Fox {
crouching: flag(m, CROUCHING),
sleeping: flag(m, SLEEPING),
sitting: flag(m, SITTING),
pouncing: flag(m, POUNCING),
faceplanted: flag(m, FACEPLANTED),
head_roll_angle: m.anim.lerp(INTERESTED_ANGLE, partial) * 0.11 * std::f32::consts::PI,
crouch_amount: m.anim.lerp(CROUCH_AMOUNT, partial),
leg_motion_pos: (m.age as f32 + partial) * 0.67 * 3.0,
}
}
+312
View File
@@ -0,0 +1,312 @@
//! Frogs (`Frog`, `FrogAi`): the `Croak` and `ShootTongue` behaviours as
//! goals, the poses they set and the client's animation states.
//! AnimState states: jump, croak, tongue, swim idle.
//!
//! The brain's idle `RunOne` picks a croak three times as often as a stroll
//! (weights 3 and 1; it also holds a do-nothing option that only repeats
//! the pick), so a frog that is not walking croaks in three of four idle
//! picks: `Croak` takes those, and the frog's stroll then follows at once.
use super::{
Mob, MobEvent, MobWorld, Species, Who,
goals::{
Cx, Float, Goal, LOOK, LookAtPlayer, MOVE, Panic, RandomLookAround, Stroll, goal_clone,
},
sync,
};
use horizon_core::{geometry::Vec3, random::RandomSource};
const JUMP: usize = 0;
const CROAK: usize = 1;
const TONGUE: usize = 2;
const SWIM_IDLE: usize = 3;
/// `Croak.CROAK_TICKS`.
const CROAK_TICKS: i32 = 60;
/// `ShootTongue`'s duration and eating distance.
const TONGUE_TIME_OUT: i32 = 100;
const EATING_DISTANCE: f64 = 1.75;
/// `FrogAttackablesSensor.TARGET_DETECTION_DISTANCE` and the sensor's scan
/// rate.
const DETECTION_DISTANCE: f64 = 10.0;
const SCAN_RATE: i32 = 20;
/// `ShootTongue.State`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Phase {
MoveToTarget,
CatchAnimation,
EatAnimation,
#[default]
Done,
}
/// The frog's brain memories and `DATA_TONGUE_TARGET_ID`.
#[derive(Clone, Debug, Default)]
pub struct State {
croak: i32,
/// Ticks to the attackables sensor's next scan, and `NEAREST_ATTACKABLE`.
scan: i32,
nearest: Option<u32>,
/// `UNREACHABLE_TONGUE_TARGETS`: the mob and the ticks it stays in mind.
unreachable: Vec<(u32, i32)>,
/// `ATTACK_TARGET` while `ShootTongue` runs, and the synched tongue target.
target: Option<u32>,
pub tongue_target: Option<u32>,
phase: Phase,
eat_timer: i32,
path_counter: i32,
time: i32,
}
pub fn register(m: &mut Mob) {
// `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). The
// frog's movement speed is 1.0, so the controller's 0.1 outside-water
// speed is what keeps a walking frog at vanilla's pace; the plain ground
// controller walks ten times too fast (#2213).
m.ai.mov.kind = super::control::MoveKind::SmoothSwimming {
max_turn_x: 85.0,
max_turn_y: 10.0,
in_water: 0.02,
outside: 0.1,
gravity: true,
};
let g = &mut m.ai.goals;
g.add(0, Float);
g.add(1, Panic::new(1.25));
g.add(2, ShootTongue);
g.add(4, Croak);
g.add(5, Stroll::avoiding_water(1.0).interval(1));
g.add(6, LookAtPlayer::new(6.0));
g.add(7, RandomLookAround::default());
}
/// `Entity.setPose` and `Frog.onSyncedDataUpdated(DATA_POSE)`.
pub fn set_pose(m: &mut Mob, id: u8) {
let old = std::mem::replace(&mut m.extra.pose, id);
if old != id {
pose_changed(m);
}
}
/// The animation states of the pose the frog has taken.
pub fn pose_changed(m: &mut Mob) {
let age = m.age as f32;
let pose = m.extra.pose;
let states = &mut m.anim.states;
for (state, on) in [
(JUMP, pose == sync::LONG_JUMPING),
(CROAK, pose == sync::CROAKING),
(TONGUE, pose == sync::USING_TONGUE),
] {
if on {
states[state].start(age);
} else {
states[state].stop();
}
}
}
/// `Frog.tick` on a client: the idle swim while it floats still. The server
/// runs it too, for a window that shows its own mobs.
pub fn tick(m: &mut Mob) {
let age = m.age as f32;
let still = m.fluids.in_water && m.limb_speed <= 1.0e-5;
m.anim.states[SWIM_IDLE].animate_when(still, age);
}
/// `Frog.canEat`: a slime or magma cube of size 1.
fn can_eat(species: Species, size: i32) -> bool {
matches!(species, Species::Slime | Species::MagmaCube) && size == 1
}
/// `FrogAttackablesSensor` (every 20 ticks) and the memory timers.
pub fn server_ai_step(m: &mut Mob, w: &MobWorld) {
let f = &mut m.extra.frog;
f.unreachable.retain_mut(|(_, ttl)| {
*ttl -= 1;
*ttl > 0
});
f.scan -= 1;
if f.scan > 0 {
return;
}
f.scan = SCAN_RATE;
let unreachable: Vec<u32> = f.unreachable.iter().map(|u| u.0).collect();
let eye = Vec3::new(m.position.x, m.eye_y(), m.position.z);
let nearest = w
.nearby(m.position, DETECTION_DISTANCE, |s| {
can_eat(s.species, s.size)
&& !unreachable.contains(&s.id)
&& w.line_of_sight(eye, Vec3::new(s.position.x, s.eye_y, s.position.z))
})
.find(|s| s.position.distance_squared(m.position) < DETECTION_DISTANCE * DETECTION_DISTANCE)
.map(|s| s.id);
m.extra.frog.nearest = nearest;
}
/// `Croak`: the pose sync::CROAKING for 60 ticks (the croak is the frog's ambient
/// sound).
#[derive(Clone, Debug)]
struct Croak;
impl Goal for Croak {
goal_clone!();
fn flags(&self) -> u8 {
MOVE
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
// checkExtraStartConditions (standing), no walk target, and not in
// a liquid (start does nothing there).
m.extra.pose == sync::STANDING
&& m.on_ground
&& !m.fluids.in_water
&& !m.fluids.in_lava
&& m.ai.nav.is_done()
&& m.random.next_int_bound(4).unwrap_or(0) != 0
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
m.extra.frog.croak < CROAK_TICKS
}
fn start(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.extra.frog.croak = 0;
set_pose(m, sync::CROAKING);
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
set_pose(m, sync::STANDING);
}
fn tick(&mut self, m: &mut Mob, _cx: &mut Cx) {
m.extra.frog.croak += 1;
}
fn every_tick(&self) -> bool {
true
}
}
/// `ShootTongue` with the tongue activity's `StartAttacking` and
/// `StopAttackingIfTargetInvalid`: walk up to a small slime or magma cube,
/// shoot the tongue, pull it in and eat it.
#[derive(Clone, Debug)]
struct ShootTongue;
impl Goal for ShootTongue {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let Some(id) = m.extra.frog.nearest else {
return false;
};
// The start conditions: no walk target, no panic, not croaking.
if m.ai.panicking || m.extra.pose == sync::CROAKING || !m.ai.nav.is_done() {
return false;
}
let Some(t) = cx.w.seen(id).filter(|t| t.alive) else {
m.extra.frog.nearest = None;
return false;
};
// canPathfindToTarget: a path that ends at the target.
let at = [t.position.x, t.position.y, t.position.z];
let ends = m
.create_path_to_entity(cx.w, at, 0)
.is_some_and(|p| f64::from(p.dist_to_target) < EATING_DISTANCE);
if !ends {
// The target is forgotten and not taken for 100 ticks.
let f = &mut m.extra.frog;
f.nearest = None;
if !f.unreachable.iter().any(|u| u.0 == id) {
if f.unreachable.len() == 5 {
f.unreachable.remove(0);
}
f.unreachable.push((id, 100));
}
return false;
}
m.extra.frog.target = Some(id);
true
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let f = &m.extra.frog;
f.phase != Phase::Done
&& f.time <= TONGUE_TIME_OUT
&& !m.ai.panicking
&& f.target
.is_some_and(|id| cx.w.seen(id).is_some_and(|t| t.alive))
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(t) = m.extra.frog.target.and_then(|id| cx.w.seen(id)) else {
return;
};
let at = [t.position.x, t.position.y, t.position.z];
let eye = [t.position.x, t.eye_y, t.position.z];
m.look_at(eye);
m.extra.frog.tongue_target = m.extra.frog.target;
m.nav_move_to_entity(cx.w, at, 0, 2.0);
let f = &mut m.extra.frog;
f.path_counter = 10;
f.time = 0;
f.phase = Phase::MoveToTarget;
}
fn stop(&mut self, m: &mut Mob, _cx: &mut Cx) {
let f = &mut m.extra.frog;
f.target = None;
f.tongue_target = None;
f.phase = Phase::Done;
set_pose(m, sync::STANDING);
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let Some(id) = m.extra.frog.target else {
return;
};
let Some(t) = cx.w.seen(id) else {
return;
};
let (at, pos) = ([t.position.x, t.position.y, t.position.z], t.position);
m.look_at([t.position.x, t.eye_y, t.position.z]);
m.extra.frog.tongue_target = Some(id);
m.extra.frog.time += 1;
let here = [m.position.x, m.position.y, m.position.z];
match m.extra.frog.phase {
Phase::MoveToTarget => {
if pos.distance_squared(m.position) < EATING_DISTANCE * EATING_DISTANCE {
cx.events
.push(MobEvent::Sound("entity.frog.tongue", here, 2.0, 1.0));
set_pose(m, sync::USING_TONGUE);
// The target is drawn in at 0.75 a tick.
let pull = m.position.subtract(pos).normalize().scale(0.75);
cx.events.push(MobEvent::Push {
target: Who::Mob(id),
velocity: [pull.x, pull.y, pull.z],
});
let f = &mut m.extra.frog;
f.eat_timer = 0;
f.phase = Phase::CatchAnimation;
} else if m.extra.frog.path_counter <= 0 {
m.nav_move_to_entity(cx.w, at, 0, 2.0);
m.extra.frog.path_counter = 10;
} else {
m.extra.frog.path_counter -= 1;
}
}
Phase::CatchAnimation => {
let f = &mut m.extra.frog;
f.eat_timer += 1;
if f.eat_timer > 6 {
f.phase = Phase::EatAnimation;
// eatEntity.
cx.events
.push(MobEvent::Sound("entity.frog.eat", here, 2.0, 1.0));
super::ai::do_hurt_target(m, Who::Mob(id), cx);
}
}
Phase::EatAnimation => {
let f = &mut m.extra.frog;
if f.eat_timer >= 10 {
f.phase = Phase::Done;
} else {
f.eat_timer += 1;
}
}
Phase::Done => {}
}
}
}
+71 -15
View File
@@ -604,6 +604,11 @@ impl Mob {
pub fn can_see_player(&mut self, w: &MobWorld, range: f64) -> bool {
self.player_in_range(w, range, true, true)
}
/// `TargetingConditions.forNonCombat().range(range).ignoreLineOfSight()`
/// for the player (still scaled by visibility).
pub fn can_see_player_through_walls(&mut self, w: &MobWorld, range: f64) -> bool {
self.player_in_range(w, range, false, true)
}
/// `scale` is `TargetingConditions.testInvisible`: scale the range by
/// the player's visibility.
fn player_in_range(
@@ -668,12 +673,15 @@ impl Goal for Float {
#[derive(Clone, Debug)]
pub struct Panic {
pub speed: f64,
/// Only the damage of `#panic_environmental_causes` (an armadillo).
pub environmental: bool,
pos: [f64; 3],
}
impl Panic {
pub fn new(speed: f64) -> Self {
Self {
speed,
environmental: false,
pos: [0.0; 3],
}
}
@@ -689,7 +697,14 @@ impl Goal for Panic {
MOVE
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !should_panic(m) {
let wanted = if self.environmental {
m.last_damage.is_some_and(|(d, t)| {
super::armadillo::environmental(d.kind) && i64::from(m.age) - t <= 40
}) || m.fire_ticks > 0 && !m.kind.flags.fire_immune
} else {
should_panic(m)
};
if !wanted {
return false;
}
if m.fire_ticks > 0 {
@@ -1456,6 +1471,9 @@ pub struct HurtByTarget {
/// `Bee.BeeHurtByOtherGoal`: kept only while angry, and alerting others
/// only when the attacker is in sight.
pub bee: bool,
/// Whom `alertOther` calls: a filter on the mob (`PandaHurtByTargetGoal`
/// calls aggressive pandas only).
pub alert_if: Option<fn(&Seen) -> bool>,
/// `PolarBear.PolarBearHurtByTargetGoal`: a hurt cub only calls the
/// adult bears and drops the target itself.
pub polar_bear: bool,
@@ -1469,6 +1487,7 @@ impl HurtByTarget {
alert_except: vec![],
ignore: vec![],
bee: false,
alert_if: None,
polar_bear: false,
timestamp: 0,
st: TargetState {
@@ -1489,6 +1508,10 @@ impl HurtByTarget {
self.bee = true;
self
}
pub fn alert_if(mut self, f: fn(&Seen) -> bool) -> Self {
self.alert_if = Some(f);
self
}
pub fn polar_bear(mut self) -> Self {
self.polar_bear = true;
self
@@ -1566,6 +1589,7 @@ impl Goal for HurtByTarget {
&& (s.position.z - pos.z).abs() <= range + 1.0
})
.filter(|s| !self.alert_except.contains(&s.species))
.filter(|s| self.alert_if.is_none_or(|f| f(s)))
// PolarBearHurtByTargetGoal.alertOther: adults only.
.filter(|s| !(self.polar_bear && s.baby))
.filter(|s| Who::Mob(s.id) != by)
@@ -1605,6 +1629,10 @@ pub struct AvoidEntity {
pub sprint: f64,
/// Extra condition on the avoider (e.g. untamed cats only).
pub when: Option<fn(&Mob) -> bool>,
/// Extra condition on the player or mob avoided (`AvoidEntityGoal`'s
/// predicate: a sneaking player, a tame wolf).
pub player_when: Option<fn(&super::PlayerView) -> bool>,
pub seen_when: Option<fn(&Seen) -> bool>,
from: Vec3,
/// The mob being avoided (`toAvoid`), when it is one.
pub found: Option<u32>,
@@ -1617,6 +1645,8 @@ impl AvoidEntity {
walk,
sprint,
when: None,
player_when: None,
seen_when: None,
from: Vec3::ZERO,
found: None,
}
@@ -1625,6 +1655,14 @@ impl AvoidEntity {
self.when = Some(f);
self
}
pub fn player_when(mut self, f: fn(&super::PlayerView) -> bool) -> Self {
self.player_when = Some(f);
self
}
pub fn seen_when(mut self, f: fn(&Seen) -> bool) -> Self {
self.seen_when = Some(f);
self
}
}
impl Goal for AvoidEntity {
goal_clone!();
@@ -1645,6 +1683,7 @@ impl Goal for AvoidEntity {
.filter(|p| {
p.alive
&& !p.creative
&& self.player_when.is_none_or(|f| f(p))
&& m.distance_sqr(p.position) <= max * max
&& (p.position.y - m.position.y).abs() <= max + 3.0
})
@@ -1653,10 +1692,12 @@ impl Goal for AvoidEntity {
Avoid::Species(list) => {
let id = m.id;
let y = m.position.y;
let seen_when = self.seen_when;
let hit =
cx.w.nearby(m.position, max, move |s| {
s.id != id
&& list.contains(&s.species)
&& seen_when.is_none_or(|f| f(s))
&& (s.position.y - y).abs() <= 3.0 + max
})
.map(|s| (s.id, s.position))
@@ -2035,6 +2076,30 @@ impl Goal for RestrictSun {
m.ai.nav.avoid_sun = false;
}
}
/// `FleeSunGoal.getHidePos`: a spot within 10 blocks that the sky does not
/// see and the mob likes.
pub fn hide_pos(m: &mut Mob, w: &MobWorld) -> Option<[f64; 3]> {
let (bx, by, bz) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
for _ in 0..10 {
let p = [
bx + m.random.next_int_bound(20).unwrap_or(0) - 10,
by + m.random.next_int_bound(6).unwrap_or(0) - 3,
bz + m.random.next_int_bound(20).unwrap_or(0) - 10,
];
if !w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(w, p) < 0.0 {
return Some([
f64::from(p[0]) + 0.5,
f64::from(p[1]),
f64::from(p[2]) + 0.5,
]);
}
}
None
}
/// FleeSunGoal: find shade while burning.
#[derive(Clone, Debug)]
pub struct FleeSun {
@@ -2066,22 +2131,13 @@ impl Goal for FleeSun {
if !cx.w.can_see_sky(bx, by, bz) {
return false;
}
for _ in 0..10 {
let p = [
bx + m.random.next_int_bound(20).unwrap_or(0) - 10,
by + m.random.next_int_bound(6).unwrap_or(0) - 3,
bz + m.random.next_int_bound(20).unwrap_or(0) - 10,
];
if !cx.w.can_see_sky(p[0], p[1], p[2]) && m.walk_target_value(cx.w, p) < 0.0 {
self.wanted = [
f64::from(p[0]) + 0.5,
f64::from(p[1]),
f64::from(p[2]) + 0.5,
];
return true;
match hide_pos(m, cx.w) {
Some(at) => {
self.wanted = at;
true
}
None => false,
}
false
}
fn can_continue(&mut self, m: &mut Mob, _: &mut Cx) -> bool {
!m.ai.nav.is_done()
+467
View File
@@ -0,0 +1,467 @@
//! Goats (`Goat`, `GoatAi`): the lowered head (`lowerHeadTick`, entity
//! events 58 and 59) and the ram activity: `PrepareRamNearestTarget` picks
//! the nearest living thing it can see, walks to a spot four to seven
//! blocks away in a straight line and waits there 20 ticks with its head
//! down; `RamTarget` then charges at it, knocks it back, or breaks a horn
//! on a log, stone or ore. Both are one goal here.
use super::{
Damage, Mob, MobEvent, MobWorld, Who,
goals::{Cx, Goal, LOOK, MOVE, goal_clone},
};
use horizon_core::{geometry::Vec3, random::RandomSource};
/// `GoatAi.TIME_BETWEEN_RAMS` and `TIME_BETWEEN_RAMS_SCREAMER`.
const RAMS: (i32, i32) = (600, 6000);
const RAMS_SCREAMER: (i32, i32) = (100, 300);
const RAM_PREPARE_TIME: i64 = 20;
const MIN_RAM_DISTANCE: i32 = 4;
const MAX_RAM_DISTANCE: i32 = 7;
/// `PrepareRamNearestTarget.TIME_OUT_DURATION` and `RamTarget`'s.
const PREPARE_TIME_OUT: i32 = 160;
const RAM_TIME_OUT: i32 = 200;
/// `NEAREST_VISIBLE_LIVING_ENTITIES` reaches 16 blocks.
const SENSE_RANGE: f64 = 16.0;
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Phase {
#[default]
Done,
Prepare,
/// `RAM_TARGET` is set; `RamTarget` starts on the next tick.
RamStart,
Ram,
}
#[derive(Clone, Copy, Debug)]
struct Candidate {
start: [i32; 3],
target_pos: [i32; 3],
target: Who,
}
/// The lowered head and the ram behaviours' state. `RAM_COOLDOWN_TICKS` is a
/// brain memory (`ram_cooldown`), saved with the others.
#[derive(Clone, Debug, Default)]
pub struct State {
lower_head_tick: i32,
lowering_head: bool,
phase: Phase,
candidate: Option<Candidate>,
reached_at: Option<i32>,
/// `RAM_TARGET`, and the direction of the charge.
ram_target: Option<Vec3>,
ram_direction: Vec3,
time: i32,
}
pub fn register(m: &mut Mob) {
m.ai.goals.add(2, Ram);
}
/// `Goat.handleEntityEvent`: 58 lowers the head, 59 raises it.
pub fn entity_event(m: &mut Mob, event: u8) {
match event {
58 => m.extra.goat.lowering_head = true,
59 => m.extra.goat.lowering_head = false,
_ => {}
}
}
/// `Goat.aiStep`'s `lowerHeadTick`; a client runs it too.
pub fn tick(m: &mut Mob) {
let g = &mut m.extra.goat;
g.lower_head_tick += if g.lowering_head { 1 } else { -2 };
g.lower_head_tick = g.lower_head_tick.clamp(0, 20);
// `CountDownCooldownTicks(RAM_COOLDOWN_TICKS)`: one less each tick, erased
// once it runs out.
let cooldown = ram_cooldown(m);
if cooldown > 0 {
set_ram_cooldown(m, cooldown - 1);
}
}
/// `RAM_COOLDOWN_TICKS`: 0 when absent.
pub fn ram_cooldown(m: &Mob) -> i32 {
m.extra
.memories
.iter()
.find(|x| x.0 == RAM_COOLDOWN)
.map_or(0, |x| x.1 as i32)
}
fn set_ram_cooldown(m: &mut Mob, ticks: i32) {
let memories = &mut m.extra.memories;
match memories.iter().position(|x| x.0 == RAM_COOLDOWN) {
Some(i) if ticks > 0 => memories[i].1 = i64::from(ticks),
Some(i) => {
memories.remove(i);
}
None if ticks > 0 => memories.push((RAM_COOLDOWN, i64::from(ticks), i64::MAX)),
None => {}
}
}
const RAM_COOLDOWN: &str = "ram_cooldown";
/// `Goat.getRammingXHeadRot`.
pub fn ramming_x_head_rot(m: &Mob) -> f32 {
let max = if m.is_baby() { 52.5_f32 } else { 30.0 };
m.extra.goat.lower_head_tick as f32 / 20.0 * max * (std::f32::consts::PI / 180.0)
}
/// A server's `level.broadcastEntityEvent(goat, 58 or 59)`, sent when it
/// changes what the goat does.
fn lower_head(m: &mut Mob, events: &mut Vec<MobEvent>, lower: bool) {
if m.extra.goat.lowering_head != lower {
let event: i8 = if lower { 58 } else { 59 };
entity_event(m, event as u8);
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::EntityEvent {
mob: m.id,
event,
at,
});
}
}
fn between(m: &mut Mob, (min, max): (i32, i32)) -> i32 {
m.random.next_int_between_inclusive(min, max).unwrap_or(min)
}
fn rams(m: &Mob) -> (i32, i32) {
if m.extra.screaming {
RAMS_SCREAMER
} else {
RAMS
}
}
fn block_of(p: Vec3) -> [i32; 3] {
[p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]
}
fn play(m: &Mob, events: &mut Vec<MobEvent>, sound: &'static str, pitch: f32) {
if !m.silent {
let at = [m.position.x, m.position.y, m.position.z];
events.push(MobEvent::Sound(sound, at, 1.0, pitch));
}
}
/// `PrepareRamNearestTarget.isWalkableBlock`.
fn walkable(m: &Mob, w: &MobWorld, p: [i32; 3]) -> bool {
m.stable_destination(w, p) && m.malus(w.path_type_static(p[0], p[1], p[2])) == 0.0
}
/// `PrepareRamNearestTarget.calculateRammingStartPosition`.
fn ramming_start(m: &mut Mob, w: &MobWorld, target: [i32; 3]) -> Option<[i32; 3]> {
if !walkable(m, w, target) {
return None;
}
// Direction.Plane.HORIZONTAL: north, east, south, west.
let mut starts = Vec::new();
for (dx, dz) in [(0, -1), (1, 0), (0, 1), (-1, 0)] {
let mut p = target;
for _ in 0..MAX_RAM_DISTANCE {
p = [p[0] + dx, p[1], p[2] + dz];
if !walkable(m, w, p) {
p = [p[0] - dx, p[1], p[2] - dz];
break;
}
}
let manhattan =
(p[0] - target[0]).abs() + (p[1] - target[1]).abs() + (p[2] - target[2]).abs();
if manhattan >= MIN_RAM_DISTANCE {
starts.push(p);
}
}
let here = block_of(m.position);
let sqr = |p: &[i32; 3]| {
(0..3)
.map(|i| i64::from(p[i] - here[i]).pow(2))
.sum::<i64>()
};
starts.sort_by_key(sqr);
starts
.into_iter()
.find(|&p| m.create_path_to(w, p, 0).is_some_and(|path| path.reached))
}
/// `PrepareRamNearestTarget.chooseRamPosition`.
fn choose(m: &mut Mob, w: &MobWorld, target: Who) {
let g = &mut m.extra.goat;
g.reached_at = None;
let Some(t) = w.target_info(target) else {
g.candidate = None;
return;
};
let target_pos = block_of(t.position);
m.extra.goat.candidate = ramming_start(m, w, target_pos).map(|start| Candidate {
start,
target_pos,
target,
});
}
/// The nearest living thing the goat sees that `RAM_TARGET_CONDITIONS`
/// allow: not a goat, a player who is not creative or a spectator.
fn nearest_target(m: &mut Mob, w: &MobWorld) -> Option<Who> {
let mut best: Option<(Who, f64)> = None;
if let Some(p) = &w.player
&& p.alive
&& !p.creative
&& !p.spectator
&& !p.allies.contains(&m.id)
&& m.distance_sqr(p.position) <= SENSE_RANGE * SENSE_RANGE
&& m.sees(w, Who::Player)
{
best = Some((Who::Player, m.distance_sqr(p.position)));
}
let id = m.id;
let mobs: Vec<(u32, f64)> = w
.nearby(m.position, SENSE_RANGE, |s| {
s.id != id && s.species != super::Species::Goat && !s.playing_dead
})
.map(|s| (s.id, m.distance_sqr(s.position)))
.collect();
for (mob, d) in mobs {
if best.is_none_or(|b| d < b.1) && m.sees(w, Who::Mob(mob)) {
best = Some((Who::Mob(mob), d));
}
}
best.map(|b| b.0)
}
/// `PrepareRamNearestTarget` and `RamTarget` of the ram activity.
#[derive(Clone, Debug)]
struct Ram;
impl Goal for Ram {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | LOOK
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
// The ram activity needs the cooldown to be over (it also waits for
// no tempting player and no breed target, which goats lack here).
ram_cooldown(m) <= 0
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
let g = &m.extra.goat;
match g.phase {
Phase::Done => false,
Phase::Prepare => {
g.time <= PREPARE_TIME_OUT
&& g.candidate
.is_some_and(|c| cx.w.target_info(c.target).is_some_and(|t| t.alive))
}
Phase::RamStart | Phase::Ram => g.ram_target.is_some() && g.time <= RAM_TIME_OUT,
}
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
m.extra.goat.phase = Phase::Prepare;
m.extra.goat.time = 0;
m.extra.goat.reached_at = None;
m.extra.goat.candidate = None;
if let Some(target) = nearest_target(m, cx.w) {
choose(m, cx.w, target);
}
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
match m.extra.goat.phase {
// PrepareRamNearestTarget.stop: no ram target, so the head comes
// up and the cooldown starts.
Phase::Prepare => {
lower_head(m, cx.events, false);
let wait = rams(m).0;
set_ram_cooldown(m, wait);
}
// RamTarget.finishRam (also what its timeout leaves undone).
Phase::RamStart | Phase::Ram => finish_ram(m, cx.events),
Phase::Done => {}
}
m.extra.goat.phase = Phase::Done;
m.extra.goat.candidate = None;
}
fn every_tick(&self) -> bool {
true
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
m.extra.goat.time += 1;
match m.extra.goat.phase {
Phase::Prepare => prepare_tick(m, cx),
Phase::RamStart => {
// RamTarget.start: charge from here at the ram target.
let (Some(target), here) = (m.extra.goat.ram_target, block_of(m.position)) else {
return;
};
let d = Vec3::new(
f64::from(here[0]) - target.x,
0.0,
f64::from(here[2]) - target.z,
);
m.extra.goat.ram_direction = d.normalize();
m.extra.goat.phase = Phase::Ram;
m.extra.goat.time = 0;
m.nav_move_to_entity(cx.w, [target.x, target.y, target.z], 0, 3.0);
ram_tick(m, cx);
}
Phase::Ram => ram_tick(m, cx),
Phase::Done => {}
}
}
}
/// `PrepareRamNearestTarget.tick`.
fn prepare_tick(m: &mut Mob, cx: &mut Cx) {
let Some(c) = m.extra.goat.candidate else {
return;
};
let Some(t) = cx.w.target_info(c.target) else {
return;
};
m.look_at([t.position.x, t.eye_y, t.position.z]);
let now = m.age as i32;
let at = [
f64::from(c.start[0]) + 0.5,
f64::from(c.start[1]),
f64::from(c.start[2]) + 0.5,
];
if m.ai.nav.is_done() && block_of(m.position) != c.start {
m.nav_move_to_entity(cx.w, at, 0, 1.25);
}
if block_of(t.position) != c.target_pos {
// The target moved: the head comes up and a new spot is chosen.
lower_head(m, cx.events, false);
m.nav_stop();
choose(m, cx.w, c.target);
} else if block_of(m.position) == c.start {
lower_head(m, cx.events, true);
let since = *m.extra.goat.reached_at.get_or_insert(now);
if i64::from(now - since) >= RAM_PREPARE_TIME {
// getEdgeOfBlock.
let (x, z) = (
f64::from(c.target_pos[0])
+ 0.5
+ 0.5 * f64::from(sign(c.target_pos[0] - c.start[0])),
f64::from(c.target_pos[2])
+ 0.5
+ 0.5 * f64::from(sign(c.target_pos[2] - c.start[2])),
);
m.extra.goat.ram_target = Some(Vec3::new(x, f64::from(c.target_pos[1]), z));
let sound = if m.extra.screaming {
"entity.goat.screaming.prepare_ram"
} else {
"entity.goat.prepare_ram"
};
let pitch = m.voice_pitch();
play(m, cx.events, sound, pitch);
m.extra.goat.candidate = None;
m.extra.goat.phase = Phase::RamStart;
}
}
}
fn sign(v: i32) -> i32 {
v.signum()
}
/// `RamTarget.tick`.
fn ram_tick(m: &mut Mob, cx: &mut Cx) {
let impact = if m.extra.screaming {
"entity.goat.screaming.ram_impact"
} else {
"entity.goat.ram_impact"
};
let from = [m.position.x, m.position.y, m.position.z];
if let Some(target) = rammed(m, cx.w) {
// hurtServer by `noAggroMobAttack`, then the knockback.
let amount = m.attrs.attack_damage;
match target {
Who::Player => cx.events.push(MobEvent::DamagePlayer {
amount,
from,
kind: "minecraft:mob_attack_no_aggro",
}),
Who::Mob(id) => cx.events.push(MobEvent::AttackMob {
target: id,
amount,
source: Damage::mob(m.id, from),
}),
}
let level = |effect: &str| {
m.extra
.effects
.iter()
.find(|e| e.0 == effect)
.map_or(0, |e| e.2 + 1)
};
let boost = 0.25 * (level("minecraft:speed") - level("minecraft:slowness")) as f32;
let factor = (m.ai.speed * 1.65).clamp(0.2, 3.0) + boost;
let force = if m.is_baby() { 1.0 } else { 2.5 };
let d = m.extra.goat.ram_direction;
cx.events.push(MobEvent::Knockback {
target,
power: f64::from(factor * force),
x: d.x,
z: d.z,
});
finish_ram(m, cx.events);
play(m, cx.events, impact, 1.0);
} else if rammed_horn_block(m, cx.w) {
play(m, cx.events, impact, 1.0);
if drop_horn(m, cx.events) {
play(m, cx.events, "entity.goat.horn_break", 1.0);
}
finish_ram(m, cx.events);
} else if m.ai.nav.is_done() || m.extra.goat.ram_target.is_none() {
// The walk target is gone: the charge ended where it could.
finish_ram(m, cx.events);
}
}
/// The first living thing in the goat's box that `RAM_TARGET_CONDITIONS`
/// allow.
fn rammed(m: &Mob, w: &MobWorld) -> Option<Who> {
let bounds = m.bounds();
if let Some(p) = &w.player
&& p.alive
&& !p.creative
&& !p.spectator
&& !p.allies.contains(&m.id)
&& p.bounds.intersects(bounds)
{
return Some(Who::Player);
}
w.others_near(bounds)
.find(|s| {
s.id != m.id
&& s.alive
&& s.species != super::Species::Goat
&& !s.playing_dead
&& s.bounds.intersects(bounds)
})
.map(|s| Who::Mob(s.id))
}
/// `RamTarget.hasRammedHornBreakingBlock`: the block one step ahead, or the
/// one above it, snaps a horn.
fn rammed_horn_block(m: &Mob, w: &MobWorld) -> bool {
let ahead = Vec3::new(m.velocity.x, 0.0, m.velocity.z).normalize();
let at = block_of(m.position.add_vector(ahead));
let snaps =
|p: [i32; 3]| w.has_tag("minecraft:snaps_goat_horn", w.block_name(p[0], p[1], p[2]));
snaps(at) || snaps([at[0], at[1] + 1, at[2]])
}
/// `Goat.dropHorn`: one of the horns it still has comes off and drops.
fn drop_horn(m: &mut Mob, events: &mut Vec<MobEvent>) -> bool {
if m.is_baby() {
return false;
}
let [left_lost, right_lost] = m.extra.lost_horns;
if left_lost && right_lost {
return false;
}
let lose_left = if left_lost {
false
} else if right_lost {
true
} else {
m.random.next_boolean()
};
m.extra.lost_horns[usize::from(!lose_left)] = true;
events.push(MobEvent::DropItem {
item: "minecraft:goat_horn".into(),
count: 1,
at: [m.position.x, m.position.y, m.position.z],
});
true
}
/// `RamTarget.finishRam`.
fn finish_ram(m: &mut Mob, events: &mut Vec<MobEvent>) {
lower_head(m, events, false);
let wait = rams(m);
let cooldown = between(m, wait);
set_ram_cooldown(m, cooldown);
m.extra.goat.ram_target = None;
m.extra.goat.phase = Phase::Done;
}
+33 -1
View File
@@ -157,12 +157,16 @@ impl Goal for OfferFlower {
fn can_continue(&mut self, _: &mut Mob, _: &mut Cx) -> bool {
self.ticks > 0
}
fn start(&mut self, m: &mut Mob, _: &mut Cx) {
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.ticks = 400;
m.extra.counter = 400;
// IronGolem.offerFlower(true): entity event 11.
entity_event(m, 11, cx);
}
fn stop(&mut self, m: &mut Mob, cx: &mut Cx) {
m.extra.counter = 0;
// IronGolem.offerFlower(false): entity event 34.
entity_event(m, 34, cx);
// A copper golem the offer ran out beside takes the poppy on its
// antenna (#accepts_iron_golem_gift) when it has none.
if self.ticks == 0
@@ -198,6 +202,7 @@ impl Goal for OfferFlower {
/// the target is thrown upward.
pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
m.extra.anim_ticks = 10;
entity_event(m, 4, cx);
let attack = m.attrs.attack_damage;
let amount = if attack as i32 > 0 {
attack / 2.0 + m.random.next_int_bound(attack as i32).unwrap_or(0) as f32
@@ -224,6 +229,33 @@ pub fn iron_hurt_target(m: &mut Mob, who: Who, cx: &mut Cx) {
1.0,
));
}
/// `Level.broadcastEntityEvent` for an iron golem (guests run `client_event`).
fn entity_event(m: &Mob, event: i8, cx: &mut Cx) {
cx.events.push(MobEvent::EntityEvent {
mob: m.id,
event,
at: [m.position.x, m.position.y, m.position.z],
});
}
/// `IronGolem.handleEntityEvent` on a client: 4 the swing, 11 and 34 the
/// poppy offer starting and stopping.
pub fn client_event(m: &mut Mob, event: u8) {
match event {
4 => m.extra.anim_ticks = 10,
11 => m.extra.counter = 400,
34 => m.extra.counter = 0,
_ => {}
}
}
/// The swing and offer clocks of `IronGolem.aiStep` on a client.
pub fn client_tick(m: &mut Mob) {
if m.extra.anim_ticks > 0 {
m.extra.anim_ticks -= 1;
}
if m.extra.counter > 0 {
m.extra.counter -= 1;
}
}
/// `IronGolem.aiStep` timers and anger.
pub fn iron_ai_step(m: &mut Mob) {
if m.extra.anim_ticks > 0 {

Some files were not shown because too many files have changed in this diff Show More